diff --git a/.editorconfig b/.editorconfig index 63c4bf9..c9c1473 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,8 +8,8 @@ indent_style = space indent_size = 4 trim_trailing_whitespace = true -[*.{json,yml,yaml,xml}] -indent_size = 2 - [*.md] trim_trailing_whitespace = false + +[*.{yml,yaml,json}] +indent_size = 2 diff --git a/.gitattributes b/.gitattributes index 9346568..117c956 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,15 +1,16 @@ * text=auto eol=lf /.github export-ignore -/docs export-ignore /tests export-ignore +/docs export-ignore /.editorconfig export-ignore /.gitattributes export-ignore /.gitignore export-ignore -/phpcs.xml.dist export-ignore -/phpstan.neon.dist export-ignore /phpunit.xml.dist export-ignore -/CHANGELOG.md export-ignore -/CODE_OF_CONDUCT.md export-ignore +/phpstan.neon.dist export-ignore +/pint.json export-ignore /CONTRIBUTING.md export-ignore +/CODE_OF_CONDUCT.md export-ignore /SECURITY.md export-ignore +/SUPPORT.md export-ignore +/MAINTAINING.md export-ignore diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index d2b15e5..47762e8 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,12 +1,15 @@ name: Bug report description: Report something that is not working as expected. -labels: [bug] +title: "[Bug]: " +labels: + - "type: bug" + - "status: needs triage" body: - type: input id: package-version attributes: label: Package version - placeholder: '1.0.0' + placeholder: '8.4.0' validations: required: true - type: input diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 56ba978..0fc247d 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,8 +1,11 @@ blank_issues_enabled: false contact_links: + - name: Documentation + url: https://pharaonic.dev/packages/php/smart-enum + about: Read the Pharaonic documentation. - name: Community support url: https://discord.gg/XQG9RhvEvf about: Get help from the Pharaonic Discord community. - - name: Documentation - url: https://pharaonic.dev/packages/php/smart-enum - about: Read the documentation for this project. + - name: Security vulnerability + url: https://github.com/Pharaonic/php-smart-enum/security + about: Do not report security vulnerabilities in public issues. diff --git a/.github/ISSUE_TEMPLATE/documentation.yml b/.github/ISSUE_TEMPLATE/documentation.yml new file mode 100644 index 0000000..a302c9d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/documentation.yml @@ -0,0 +1,25 @@ +name: Documentation issue +description: Report missing, incorrect, or unclear documentation +title: "[Docs]: " +labels: + - "type: docs" + - "status: needs triage" +body: + - type: input + id: page + attributes: + label: Documentation page + description: Link to the affected page when possible. + + - type: textarea + id: issue + attributes: + label: What is unclear or incorrect? + validations: + required: true + + - type: textarea + id: improvement + attributes: + label: Suggested improvement + description: Explain what information would make the documentation clearer. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 0126583..1186b64 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -1,7 +1,9 @@ name: Feature request description: Suggest an idea or improvement. title: "[Feature]: " -labels: [enhancement] +labels: + - "type: feature" + - "status: needs triage" body: - type: textarea id: problem diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index a3dc7d8..e1ee35f 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,26 +1,15 @@ ## Summary - +Explain what changed and why. ## Changes -- +Describe the meaningful implementation or API changes. -## Testing +## Compatibility - +Describe compatibility or deprecation impact when relevant. -## Backward compatibility +## Notes - - -## Checklist - -- [ ] Tests added/updated -- [ ] Backward compatibility considered (no public API change, or it is described above) -- [ ] PHPStan passes (`composer analyse`) -- [ ] Coding style passes (`composer lint`) -- [ ] Documentation updated if applicable -- [ ] `CHANGELOG.md` updated if applicable -- [ ] Scope is focused on a single change -- [ ] No unnecessary dependencies added +Add reviewer context only when useful. diff --git a/.github/dependabot.yml b/.github/dependabot.yml index ed40137..473f3fb 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,19 +1,26 @@ +# Dependabot only opens PRs against develop. Runtime lines (8.N.x) receive +# tooling updates through the normal port flow, retested on their own PHP. version: 2 - updates: - package-ecosystem: composer - directory: / + directory: "/" + target-branch: develop + labels: + - "area: dependencies" schedule: - interval: monthly - versioning-strategy: widen + interval: weekly groups: - dev-dependencies: + development-dependencies: dependency-type: development - package-ecosystem: github-actions - directory: / + directory: "/" + target-branch: develop + labels: + - "area: dependencies" schedule: - interval: monthly + interval: weekly groups: github-actions: - patterns: ["*"] + patterns: + - "*" diff --git a/.github/labels.yml b/.github/labels.yml new file mode 100644 index 0000000..04b1904 --- /dev/null +++ b/.github/labels.yml @@ -0,0 +1,44 @@ +# Standard Pharaonic repository labels. +# Apply/update these through repository tooling only after explicit approval. +- name: "type: bug" + description: "Something is not working as intended" + color: "d73a4a" +- name: "type: feature" + description: "New capability or enhancement" + color: "a2eeef" +- name: "type: docs" + description: "Documentation improvement" + color: "0075ca" +- name: "type: maintenance" + description: "Repository or maintenance work" + color: "cfd3d7" +- name: "status: needs triage" + description: "Needs maintainer review" + color: "fbca04" +- name: "status: needs info" + description: "More information is required" + color: "d4c5f9" +- name: "status: blocked" + description: "Cannot proceed yet" + color: "b60205" +- name: "area: dependencies" + description: "Dependency-related change" + color: "0366d6" +- name: "area: compatibility" + description: "Backward/runtime compatibility" + color: "5319e7" +- name: "area: tests" + description: "Test suite work" + color: "0e8a16" +- name: "area: ci" + description: "CI or automation" + color: "1d76db" +- name: "breaking-change" + description: "Potential or confirmed breaking change" + color: "b60205" +- name: "good first issue" + description: "Suitable for a first contribution" + color: "7057ff" +- name: "help wanted" + description: "Extra community help is welcome" + color: "008672" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f85d0e5..4e5a27b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,79 +1,201 @@ name: Build - -on: +'on': push: branches: - - '8.*.x' - + - develop + - 8.*.x pull_request: branches: - - '8.*.x' - -permissions: - contents: read - + - develop + - 8.*.x + workflow_dispatch: null concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + group: build-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true - +permissions: + contents: read jobs: - build: - name: ${{ matrix.os }} - ${{ matrix.dependencies }} dependencies - + matrix: + runs-on: ubuntu-latest + outputs: + php: ${{ steps.php.outputs.versions }} + lowest: ${{ steps.php.outputs.lowest }} + steps: + - name: Checkout + uses: actions/checkout@v7 + - name: Read supported PHP minors + id: php + shell: bash + run: | + constraint="$(jq -r '.require.php' composer.json)" + if [[ ! "$constraint" =~ ^\>=8\.([0-9]+)\ \<8\.([0-9]+)$ ]] || (( BASH_REMATCH[2] != BASH_REMATCH[1] + 1 )); then + echo "require.php must declare exactly one PHP minor as >=8.N <8.N+1, got: $constraint" >&2 + exit 1 + fi + version="8.${BASH_REMATCH[1]}" + echo "versions=$(jq -cn --arg php "$version" '[$php]')" >> "$GITHUB_OUTPUT" + echo "lowest=$version" >> "$GITHUB_OUTPUT" + validate: + needs: + - matrix + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + - name: Setup PHP + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ needs.matrix.outputs.lowest }} + coverage: none + tools: composer:v2 + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + with: + dependency-versions: highest + - name: Validate + run: composer validate --strict + style: + needs: + - matrix + - validate + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + - name: Setup PHP + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ needs.matrix.outputs.lowest }} + coverage: none + tools: composer:v2 + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + with: + dependency-versions: highest + - name: Style + run: composer format:check + analyse: + needs: + - matrix + - style + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + - name: Setup PHP + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ needs.matrix.outputs.lowest }} + coverage: none + tools: composer:v2 + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + with: + dependency-versions: highest + - name: Analyse + run: composer analyse + tests: + name: Tests - PHP ${{ matrix.php }} - ${{ matrix.os }} - ${{ matrix.dependencies }} + needs: + - matrix + - analyse strategy: - max-parallel: 2 - - fail-fast: false - + fail-fast: true matrix: - os: - - ubuntu-latest - - windows-latest + php: ${{ fromJSON(needs.matrix.outputs.php) }} dependencies: - - lowest - - highest - + - lowest + - highest + os: + - ubuntu-latest + - windows-latest runs-on: ${{ matrix.os }} - steps: - - name: Checkout - uses: actions/checkout@v7 - - - name: Resolve PHP version - id: php - shell: bash - run: | - BRANCH="${GITHUB_BASE_REF:-${GITHUB_REF_NAME}}" - PHP_VERSION="${BRANCH%.x}" - - echo "branch=${BRANCH}" - echo "version=${PHP_VERSION}" - - echo "version=${PHP_VERSION}" >> "$GITHUB_OUTPUT" - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ steps.php.outputs.version }} - coverage: none - tools: composer:v2 - - - name: Validate Composer - run: composer validate --strict - - - name: Install dependencies - uses: ramsey/composer-install@v4 - with: - dependency-versions: ${{ matrix.dependencies }} - # Composer blocks releases with security advisories by default, which - # would silently lift "lowest" above the declared dev-tool floors. - composer-options: ${{ matrix.dependencies == 'lowest' && '--no-blocking' || '' }} - - - name: Run tests - run: composer test - - - name: PHPStan - run: composer analyse -- --no-progress - - - name: Coding style - run: composer lint + - name: Checkout + uses: actions/checkout@v7 + - name: Setup PHP + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ matrix.php }} + coverage: none + tools: composer:v2 + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + with: + dependency-versions: ${{ matrix.dependencies }} + # Lets the locale test prove that is() names do not follow LC_CTYPE. + - name: Install a Turkish locale + if: runner.os == 'Linux' + run: sudo locale-gen tr_TR.UTF-8 + - name: Run tests + run: composer test + security: + needs: + - matrix + - tests + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + - name: Setup PHP + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ needs.matrix.outputs.lowest }} + coverage: none + tools: composer:v2 + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + with: + dependency-versions: highest + - name: Security audit + run: composer security + archive: + needs: + - matrix + - security + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + - name: Setup PHP + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ needs.matrix.outputs.lowest }} + coverage: none + tools: composer:v2 + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + with: + dependency-versions: highest + - name: Verify Composer archive + shell: bash + run: | + mkdir -p /tmp/pharaonic-ci-archive + composer archive --format=zip --dir=/tmp/pharaonic-ci-archive --file=package + unzip -t /tmp/pharaonic-ci-archive/package.zip + quality: + name: Quality gate + if: ${{ always() }} + needs: + - matrix + - validate + - style + - analyse + - tests + - security + - archive + runs-on: ubuntu-latest + steps: + - name: Require every stage to succeed + env: + NEEDS_JSON: ${{ toJSON(needs) }} + run: | + python3 - <<'PY_CHECK' + import json, os, sys + results = json.loads(os.environ['NEEDS_JSON']) + failed = {name: job['result'] for name, job in results.items() if job['result'] != 'success'} + if failed: + print('Required stages did not succeed:', failed) + sys.exit(1) + print('Every required stage succeeded.') + PY_CHECK diff --git a/.github/workflows/labels.yml b/.github/workflows/labels.yml new file mode 100644 index 0000000..d96990d --- /dev/null +++ b/.github/workflows/labels.yml @@ -0,0 +1,28 @@ +name: Labels + +on: + push: + branches: + - develop + paths: + - .github/labels.yml + workflow_dispatch: + +permissions: + issues: write + +jobs: + sync: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v7 + + # Creates and updates the labels in .github/labels.yml. Labels that are + # not listed are left alone. + - name: Sync labels + uses: crazy-max/ghaction-github-labeler@548a7c3603594ec17c819e1239f281a3b801ab4d # v6.0.0 + with: + yaml-file: .github/labels.yml + skip-delete: true diff --git a/.gitignore b/.gitignore index 6a7a3ba..fd26035 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,10 @@ /vendor/ -/.idea/ -/.vscode/ -.phpunit.result.cache -.phpunit.cache/ -composer.lock -phpunit.xml +/composer.lock +/.phpunit.cache/ +/.phpunit.result.cache +/.phpstan-cache/ +/coverage/ +.idea/ +.vscode/ +.DS_Store +Thumbs.db diff --git a/CHANGELOG.md b/CHANGELOG.md index 893c164..865e544 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to this project will be documented in this file. +## 8.4.1 - Unreleased + +### Changed + +- The documentation has an upgrade guide, and the README shows installation and a usage example. +- Tests run on Pest and the code style is checked by Pint; CI runs validation, style, static analysis, tests, the security audit and an archive check in order, behind one quality gate. + ## 8.4.0 - 2026-10-09 ### Added diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index cb3afbf..8dbb760 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -2,7 +2,7 @@ ## Our standards -Be respectful, constructive, and focused on the technical work. Harassment, discrimination, personal attacks, and intentionally disruptive behavior are not acceptable. +Be respectful, constructive, and focused on the technical work. Respect other people's privacy and never publish their private information. Harassment, discrimination, personal attacks, and intentionally disruptive behavior are not acceptable. ## Scope @@ -11,3 +11,5 @@ This code of conduct applies to repository discussions, issues, pull requests, r ## Enforcement Project maintainers may edit, remove, or reject contributions and participation that violate these standards. + +Report conduct concerns privately to the maintainers rather than in public threads. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5154591..775e51f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,7 +16,15 @@ Please open an issue before proposing a new public method. ## Supported PHP versions -PHP 8.4 (`>=8.4 <8.5`) on this branch. Each PHP minor has its own `8.N.x` release line. Keep code compatible with PHP 8.1 so fixes can be backported to every line. +Each release line targets exactly one PHP version, and the branch name tells you which: + +```text +8.1.x → PHP 8.1 +8.2.x → PHP 8.2 +... +``` + +Code on a branch must not use syntax or functions introduced after that branch's PHP version. For a bug fix, start from the oldest line that has the bug; maintainers port it to the newer lines. ## 1. Fork @@ -38,7 +46,11 @@ composer install ## 4. Create a branch +Start from the line you are targeting: + ```bash +git checkout 8.1.x +git pull upstream 8.1.x git checkout -b fix/short-description ``` @@ -55,18 +67,18 @@ docs/ ## 5. Run tests ```bash -composer test # PHPUnit -composer analyse # PHPStan (level max) -composer lint # PHP_CodeSniffer (PSR-12) -composer check # all of the above -composer validate --strict +composer test # Pest +composer analyse # PHPStan (level max) +composer format:check # Pint; `composer format` fixes the style +composer security # Composer audit +composer check # composer validate --strict and all of the above ``` -All checks must pass. CI runs them on the PHP version of the branch (PHP 8.4 on `8.4.x`). +All checks must pass. CI runs them on the branch's PHP version, on Linux and Windows, with the lowest and highest allowed dependencies. ## 6. Follow the coding style -- PSR-12, enforced by `composer lint`; `composer format` fixes most issues. +- PER coding style, enforced by Pint (`composer format:check`); `composer format` fixes it. - `declare(strict_types=1);` in every PHP file. - Strict comparisons only (`===`). Loose comparison needs a documented reason. - Do not assume every enum is backed: handle `UnitEnum` and `BackedEnum` deliberately. @@ -78,11 +90,11 @@ All checks must pass. CI runs them on the PHP version of the branch (PHP 8.4 on git push origin fix/short-description ``` -Open the pull request and fill in the template. +Open the pull request against the version branch you started from, and fill in the template. - Keep each change focused. - Add or update tests for every behavior change. -- Add an entry to `CHANGELOG.md` under `Unreleased`. +- Add an entry to `CHANGELOG.md` under the line's next version, headed `## 8.N.p - Unreleased`. - Update `docs/` (the pharaonic.dev documentation) when the public API or usage changes. ## Public API changes diff --git a/MAINTAINING.md b/MAINTAINING.md new file mode 100644 index 0000000..4f87884 --- /dev/null +++ b/MAINTAINING.md @@ -0,0 +1,41 @@ +# Maintaining This Package + +This file records package-specific maintainer facts that are safe to keep in the public repository. + +## Purpose + +Smart, lightweight helpers for native PHP enums: one `SmartEnum` trait adds names, values, labels, options, lookup by case name, strict comparisons and `is()` checks next to PHP's own `cases()`, `from()` and `tryFrom()`. Framework integrations, enum base classes and code generation are out of scope. + +## Supported PHP lines + +One branch per PHP minor, each requiring exactly that minor (`"php": ">=8.N <8.N+1"`): + +```text +8.1.x 8.2.x 8.3.x 8.4.x 8.5.x 8.6.x +``` + +There is no `8.0.x`: native enums arrived in PHP 8.1. `develop` follows the newest line. + +## Public API invariants + +- The public API is the `Pharaonic\SmartEnum\SmartEnum` trait: the methods pinned by `tests/Unit/StructureTest.php`, the `is()` checks resolved by `__call()`, and the optional global `smart_enum_label()` hook. `CaseMethods` is `@internal`. +- The trait's FQCN stays `Pharaonic\SmartEnum\SmartEnum` on every line. It predates the `Concerns/` folder and the `Has`/`Can`/`-able` trait names, and every consumer enum imports it, so it is not moved or renamed. +- The trait never redefines `cases()`, `from()` or `tryFrom()` and declares no magic method besides `__call()`. +- Values are compared strictly (`===`). Unit enums use the case name wherever a backing value is expected. +- `is()` names are built from ASCII letters only and never depend on the process locale. A check shared by two cases throws `BadMethodCallException`; any other unknown call throws PHP's own `Error` message. +- Adding a public method can collide with methods in users' enums, so new methods need an issue discussion first. + +## Package-specific constraints + +- No runtime dependencies and no required extensions. +- CI installs a Turkish locale on Linux so the locale test runs instead of being skipped. + +## Branch notes + +Tooling follows each line's PHP. `8.4.x` uses Pest 4 on PHPUnit 12.5 and Pint's `per` preset. PHPStan analyses `src/` and `tests/Fixtures/`, because the trait is only analysed where an enum uses it. + +## Documentation + +https://pharaonic.dev/packages/php/smart-enum + +Keep this file factual and package-specific. General Pharaonic engineering policy belongs in the private engineering repository, not here. diff --git a/README.md b/README.md index c157c51..8845b1c 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -

+

PHP Version : 8.4 License - Tests + Build
Source Packagist Version @@ -11,17 +11,41 @@

Smart, lightweight helpers for native PHP enums.

-
No runtime dependencies.

+## Installation + +```bash +composer require pharaonic/php-smart-enum +``` + +## Usage + +```php +use Pharaonic\SmartEnum\SmartEnum; + +enum Status: string +{ + use SmartEnum; + + case Pending = 'pending'; + case Active = 'active'; +} + +Status::options(); // ['pending' => 'Pending', 'active' => 'Active'] +Status::fromName('Active'); // Status::Active +Status::Active->is('active'); // true +Status::Active->isActive(); // true +``` + ## Documentation -You can find the detailed documentation here in [PHP Smart Enum Documentation](https://pharaonic.dev/packages/php/smart-enum). +Full documentation: [PHP Smart Enum Documentation](https://pharaonic.dev/packages/php/smart-enum). -## Contributing +## Support & Security -Thank you for considering contributing to this package! Be one of Pharaonic team. +See [SUPPORT.md](SUPPORT.md) and [SECURITY.md](SECURITY.md). Contributions are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md). ## License -This package is an open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT). +MIT. See [LICENSE](LICENSE). diff --git a/SECURITY.md b/SECURITY.md index d1d5f79..0c24b40 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,16 @@ ## Supported versions -Security fixes are released for the latest release only. The package has not had a stable release yet. +Security fixes are released for the latest version of each maintained release line: + +| Version | PHP | Supported | +|----------|-----|--------------------| +| `8.6.x` | 8.6 | :white_check_mark: | +| `8.5.x` | 8.5 | :white_check_mark: | +| `8.4.x` | 8.4 | :white_check_mark: | +| `8.3.x` | 8.3 | :white_check_mark: | +| `8.2.x` | 8.2 | :white_check_mark: | +| `8.1.x` | 8.1 | :white_check_mark: | ## Reporting a vulnerability diff --git a/SUPPORT.md b/SUPPORT.md new file mode 100644 index 0000000..fe7d503 --- /dev/null +++ b/SUPPORT.md @@ -0,0 +1,8 @@ +# Support + +- **Documentation:** [pharaonic.dev/packages/php/smart-enum](https://pharaonic.dev/packages/php/smart-enum). +- **Questions and help:** the [Pharaonic Discord community](https://discord.gg/XQG9RhvEvf). +- **Bugs and feature requests:** [GitHub issues](https://github.com/Pharaonic/php-smart-enum/issues/new/choose), using the issue templates. +- **Security vulnerabilities:** never in public issues; follow [SECURITY.md](SECURITY.md). + +When asking for help, include your package version, PHP version, and the smallest enum that shows the problem. diff --git a/composer.json b/composer.json index 9f71773..11abbb9 100644 --- a/composer.json +++ b/composer.json @@ -1,62 +1,73 @@ { - "name": "pharaonic/php-smart-enum", - "description": "Smart, lightweight helpers for native PHP enums.", - "keywords": [ - "php", - "enum", - "enums", - "php enum", - "native enum", - "backed enum", - "trait", - "pharaonic" - ], - "type": "library", - "license": "MIT", - "authors": [ - { - "name": "Moamen Eltouny (Raggi)", - "email": "raggigroup@gmail.com" - } - ], - "homepage": "https://github.com/Pharaonic/php-smart-enum", - "support": { - "issues": "https://github.com/Pharaonic/php-smart-enum/issues", - "source": "https://github.com/Pharaonic/php-smart-enum", - "security": "https://github.com/Pharaonic/php-smart-enum/security/policy" + "name": "pharaonic/php-smart-enum", + "description": "Smart, lightweight helpers for native PHP enums.", + "type": "library", + "license": "MIT", + "keywords": [ + "php", + "enum", + "enums", + "php enum", + "native enum", + "backed enum", + "trait", + "pharaonic" + ], + "authors": [ + { + "name": "Moamen Eltouny (Raggi)", + "email": "raggigroup@gmail.com" + } + ], + "homepage": "https://pharaonic.dev/packages/php/smart-enum", + "support": { + "docs": "https://pharaonic.dev/packages/php/smart-enum", + "issues": "https://github.com/Pharaonic/php-smart-enum/issues", + "source": "https://github.com/Pharaonic/php-smart-enum", + "security": "https://github.com/Pharaonic/php-smart-enum/security/policy" + }, + "require": { + "php": ">=8.4 <8.5" + }, + "require-dev": { + "laravel/pint": "^1.20", + "pestphp/pest": "^4.0", + "phpstan/phpstan": "^2.2", + "phpunit/phpunit": "^12.5.8" + }, + "autoload": { + "psr-4": { + "Pharaonic\\SmartEnum\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Pharaonic\\SmartEnum\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "@php vendor/bin/pest", + "analyse": "@php vendor/bin/phpstan analyse --memory-limit=1G", + "format": "@php vendor/bin/pint", + "format:check": "@php vendor/bin/pint --test", + "security": "@composer audit", + "check": [ + "@composer validate --strict", + "@format:check", + "@analyse", + "@test", + "@security" + ] + }, + "config": { + "allow-plugins": { + "pestphp/pest-plugin": true }, - "require": { - "php": ">=8.4 <8.5" + "audit": { + "abandoned": "report" }, - "require-dev": { - "phpstan/phpstan": "^2.2", - "phpunit/phpunit": "^10.5", - "squizlabs/php_codesniffer": "^3.13 || ^4.0" - }, - "config": { - "sort-packages": true - }, - "autoload": { - "psr-4": { - "Pharaonic\\SmartEnum\\": "src/" - } - }, - "autoload-dev": { - "psr-4": { - "Pharaonic\\SmartEnum\\Tests\\": "tests/" - } - }, - "scripts": { - "test": "phpunit", - "analyse": "phpstan analyse", - "lint": "phpcs", - "format": "phpcbf", - "check": [ - "@lint", - "@analyse", - "@test" - ] - }, - "minimum-stability": "stable", - "prefer-stable": true + "sort-packages": true + }, + "minimum-stability": "stable", + "prefer-stable": true } diff --git a/docs/sections/05-instance-methods.md b/docs/sections/05-instance-methods.md index 953a61b..d215355 100644 --- a/docs/sections/05-instance-methods.md +++ b/docs/sections/05-instance-methods.md @@ -40,6 +40,7 @@ The matching rules: - An enum case matches only when it is the same case, like `eq()`. - A string or an int matches when it equals **this case's own** name or backing value. - Comparison is strict: an int-backed case matches `1`, never `'1'`. +- Strictness applies to the value the method receives. In a file without `declare(strict_types=1)`, PHP itself converts `1.0` or `true` to `1` before `is()` and `hasValue()` see it, so `Priority::High->is(true)` is `true` there. `in()` and `notIn()` reject a float, `bool` or `null` in the list with a `TypeError`. ```php $priority = Priority::High; // case High = 1 diff --git a/docs/sections/12-upgrade-guide.md b/docs/sections/12-upgrade-guide.md new file mode 100644 index 0000000..b34d8ce --- /dev/null +++ b/docs/sections/12-upgrade-guide.md @@ -0,0 +1,23 @@ +## Upgrade Guide + +Smart Enum has one release line per PHP version, and every line has the same trait, methods and results. This page covers the `8.4.x` line, for PHP 8.4. + +### Patch Releases + +Patch releases such as `8.4.0` to `8.4.1` never break your code. Update with: + +```bash no-line-numbers +composer update pharaonic/php-smart-enum +``` + +Results change only to fix a bug, and every such change is listed in the changelog. + +### Moving To Another PHP Version + +No code changes are needed. Composer picks the line that matches your PHP version, so after upgrading PHP run `composer update pharaonic/php-smart-enum`. + +The constraint that `composer require` writes (for example `^8.4`) already allows the newer lines. If you pinned a line with a tilde constraint such as `~8.4.0`, widen it first, or Composer stays on `8.4.x` and cannot install on the new PHP version. + +### Changelog + +Every release is listed in the [changelog](https://github.com/Pharaonic/php-smart-enum/blob/8.4.x/CHANGELOG.md) and on the [GitHub releases](https://github.com/Pharaonic/php-smart-enum/releases) page. diff --git a/docs/sidebar.md b/docs/sidebar.md index a5c2052..8d8b82f 100644 --- a/docs/sidebar.md +++ b/docs/sidebar.md @@ -15,3 +15,5 @@ - [Troubleshooting](#troubleshooting) - Community - [Contributors](#contributors) +- Upgrades + - [Upgrade Guide](#upgrade-guide) diff --git a/phpcs.xml.dist b/phpcs.xml.dist deleted file mode 100644 index 2258fc6..0000000 --- a/phpcs.xml.dist +++ /dev/null @@ -1,9 +0,0 @@ - - - PSR-12 coding standard for pharaonic/php-smart-enum. - src - tests - - - - diff --git a/phpstan.neon.dist b/phpstan.neon.dist index eaca9e0..844769a 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -3,4 +3,6 @@ parameters: phpVersion: 80400 paths: - src - - tests + # The trait is only analysed where an enum uses it. + - tests/Fixtures + tmpDir: .phpstan-cache diff --git a/phpunit.xml.dist b/phpunit.xml.dist index f46e299..2f64a88 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -2,20 +2,13 @@ + failOnDeprecation="true"> - + tests - - - src - - diff --git a/pint.json b/pint.json new file mode 100644 index 0000000..5ad32f4 --- /dev/null +++ b/pint.json @@ -0,0 +1,3 @@ +{ + "preset": "per" +} diff --git a/src/CaseMethods.php b/src/CaseMethods.php index 1df39d3..0f3cced 100644 --- a/src/CaseMethods.php +++ b/src/CaseMethods.php @@ -21,9 +21,7 @@ final class CaseMethods */ private static array $methods = []; - private function __construct() - { - } + private function __construct() {} /** * Cases of the given enum keyed by their is() method name. diff --git a/src/SmartEnum.php b/src/SmartEnum.php index 3540d31..8267b45 100644 --- a/src/SmartEnum.php +++ b/src/SmartEnum.php @@ -30,7 +30,7 @@ public function __call(string $name, array $arguments): mixed 'Call to ambiguous method %s::%s(): matches cases %s.', static::class, $name, - implode(', ', array_map(static fn (\UnitEnum $match): string => $match->name, $matches)), + implode(', ', array_map(static fn(\UnitEnum $match): string => $match->name, $matches)), )); } @@ -44,7 +44,7 @@ public function __call(string $name, array $arguments): mixed */ public static function names(): array { - return array_map(static fn (\UnitEnum $case): string => $case->name, static::cases()); + return array_map(static fn(\UnitEnum $case): string => $case->name, static::cases()); } /** @@ -54,7 +54,7 @@ public static function names(): array */ public static function labels(): array { - return array_map(static fn (self $case): string => $case->label(), static::cases()); + return array_map(static fn(self $case): string => $case->label(), static::cases()); } /** diff --git a/tests/Fixtures/LocaleStatus.php b/tests/Fixtures/LocaleStatus.php new file mode 100644 index 0000000..4b02939 --- /dev/null +++ b/tests/Fixtures/LocaleStatus.php @@ -0,0 +1,19 @@ + StringStatus::Active->label(), + 'labels' => StringStatus::labels(), + 'options' => StringStatus::options(), + 'info' => StringStatus::Active->info()['label'], + 'unit' => UnitStatus::Active->label(), + 'int' => IntStatus::Active->label(), +], JSON_THROW_ON_ERROR); diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..174d7fd --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,3 @@ +() checks resolved by SmartEnum::__call(). - */ -final class SmartEnumCallTest extends TestCase -{ - /** - * @return iterable - */ - public static function matchProvider(): iterable - { - foreach ([UnitStatus::class, StringStatus::class, IntStatus::class] as $enum) { - yield "{$enum}::isPending" => [$enum::Pending, 'isPending']; - yield "{$enum}::isActive" => [$enum::Active, 'isActive']; - yield "{$enum}::isDisabled" => [$enum::Disabled, 'isDisabled']; - } - - yield 'PENDING' => [MixedCaseStatus::PENDING, 'isPending']; - yield 'IN_COOKING' => [MixedCaseStatus::IN_COOKING, 'isInCooking']; - yield 'InProgress' => [MixedCaseStatus::InProgress, 'isInProgress']; - yield 'onHold' => [MixedCaseStatus::onHold, 'isOnHold']; - yield 'HTTPError' => [MixedCaseStatus::HTTPError, 'isHTTPError']; - yield 'Level2' => [MixedCaseStatus::Level2, 'isLevel2']; - yield 'beside an ambiguous check' => [AmbiguousStatus::Done, 'isDone']; - } - - #[DataProvider('matchProvider')] - public function testCheckIsTrueOnlyForTheMatchingCase(\UnitEnum $case, string $method): void - { - foreach ($case::cases() as $candidate) { - $this->assertSame( - $candidate === $case, - $candidate->{$method}(), - "{$candidate->name}->{$method}()", - ); - } - } - - /** - * @return iterable - */ - public static function undefinedProvider(): iterable - { - yield 'unknown case' => ['isArchived']; - yield 'no is prefix' => ['pending']; - yield 'other prefix' => ['hasPending']; - yield 'raw upper-case name' => ['isPENDING']; - yield 'raw snake-case name' => ['isIN_COOKING']; - yield 'lower-case first letter' => ['isonHold']; - yield 'title-cased acronym' => ['isHttpError']; - yield 'all lower case' => ['isinprogress']; - yield 'capital prefix' => ['IsPending']; - yield 'protected enum method' => ['tag']; - } - - - #[DataProvider('undefinedProvider')] - public function testUndefinedMethodThrows(string $method): void - { - $this->expectException(Error::class); - $this->expectExceptionMessage('Call to undefined method ' . MixedCaseStatus::class . "::{$method}()"); - - MixedCaseStatus::PENDING->{$method}(); - } - - /** - * @return iterable - */ - public static function ambiguousProvider(): iterable - { - yield 'IN_PROGRESS and InProgress' => ['isInProgress']; - } - - #[DataProvider('ambiguousProvider')] - public function testAmbiguousCheckThrows(string $method): void - { - $this->expectException(BadMethodCallException::class); - $this->expectExceptionMessage( - 'Call to ambiguous method ' . AmbiguousStatus::class - . "::{$method}(): matches cases IN_PROGRESS, InProgress.", - ); - - AmbiguousStatus::Done->{$method}(); - } - - #[DataProvider('matchProvider')] - public function testArgumentsToACheckAreIgnored(\UnitEnum $case, string $method): void - { - $this->assertTrue($case->{$method}('ignored', 1)); - } -} diff --git a/tests/SmartEnumInstanceTest.php b/tests/SmartEnumInstanceTest.php deleted file mode 100644 index bc2d63c..0000000 --- a/tests/SmartEnumInstanceTest.php +++ /dev/null @@ -1,122 +0,0 @@ -assertSame($case->name, $case->label()); - } - } - } - - public function testEqIsStrictCaseIdentity(): void - { - $this->assertTrue(StringStatus::Active->eq(StringStatus::Active)); - $this->assertFalse(StringStatus::Active->eq(StringStatus::Disabled)); - $this->assertFalse(StringStatus::Active->eq(UnitStatus::Active), 'Same name in another enum.'); - $this->assertFalse(IntStatus::Active->eq(UnitStatus::Active), 'Same name in another enum.'); - } - - /** - * @return iterable - */ - public static function isProvider(): iterable - { - yield 'same case' => [StringStatus::Active, StringStatus::Active, true]; - yield 'other case' => [StringStatus::Active, StringStatus::Disabled, false]; - yield 'same name in another enum' => [StringStatus::Active, UnitStatus::Active, false]; - yield 'case name' => [StringStatus::Active, 'Active', true]; - yield 'backing value' => [StringStatus::Active, 'active', true]; - yield 'other case name' => [StringStatus::Active, 'Disabled', false]; - yield 'other backing value' => [StringStatus::Active, 'disabled', false]; - yield 'upper-case value' => [StringStatus::Active, 'ACTIVE', false]; - yield 'int value' => [IntStatus::Active, 1, true]; - yield 'int value as string' => [IntStatus::Active, '1', false]; - yield 'int case name' => [IntStatus::Active, 'Active', true]; - yield 'int other value' => [IntStatus::Active, 2, false]; - yield 'zero is not a name' => [IntStatus::Pending, 'Pending', true]; - yield 'zero is not an empty string' => [IntStatus::Pending, '', false]; - yield 'unit case name' => [UnitStatus::Active, 'Active', true]; - yield 'unit lower case' => [UnitStatus::Active, 'active', false]; - yield 'unit int' => [UnitStatus::Active, 1, false]; - yield 'own name over other value' => [CrossedStatus::Open, 'Open', true]; - yield 'own value over other name' => [CrossedStatus::Open, 'Closed', true]; - yield 'other own name' => [CrossedStatus::Closed, 'Closed', true]; - yield 'other own value' => [CrossedStatus::Closed, 'Open', true]; - } - - #[DataProvider('isProvider')] - public function testIsAndIsNot(\UnitEnum $case, \UnitEnum|int|string $value, bool $expected): void - { - /** @var UnitStatus|StringStatus|IntStatus|CrossedStatus $case */ - $this->assertSame($expected, $case->is($value), 'is()'); - $this->assertSame(!$expected, $case->isNot($value), 'isNot()'); - } - - /** - * @return iterable, bool}> - */ - public static function inProvider(): iterable - { - yield 'empty list' => [[], false]; - yield 'matching case' => [[StringStatus::Pending, StringStatus::Active], true]; - yield 'no matching case' => [[StringStatus::Pending, StringStatus::Disabled], false]; - yield 'matching value' => [['pending', 'active'], true]; - yield 'matching name' => [['Pending', 'Active'], true]; - yield 'mixed kinds' => [[StringStatus::Pending, 'Disabled', 'active'], true]; - yield 'nothing matches' => [[StringStatus::Pending, 'Disabled', 'archived', 1], false]; - yield 'same name in another enum' => [[UnitStatus::Active], false]; - } - - /** - * @param list<\UnitEnum|int|string> $values - */ - #[DataProvider('inProvider')] - public function testInAndNotIn(array $values, bool $expected): void - { - $this->assertSame($expected, StringStatus::Active->in($values), 'in()'); - $this->assertSame(!$expected, StringStatus::Active->notIn($values), 'notIn()'); - } - - public function testInAcceptsAnAssociativeArray(): void - { - $this->assertTrue(StringStatus::Active->in(['first' => 'pending', 'second' => 'active'])); - } - - /** - * @return iterable - */ - public static function infoProvider(): iterable - { - yield 'string-backed' => [StringStatus::Active, ['name' => 'Active', 'value' => 'active', 'label' => 'Active']]; - yield 'int-backed' => [IntStatus::Pending, ['name' => 'Pending', 'value' => 0, 'label' => 'Pending']]; - yield 'unit' => [UnitStatus::Active, ['name' => 'Active', 'value' => 'Active', 'label' => 'Active']]; - } - - /** - * @param array{name: string, value: int|string, label: string} $expected - */ - #[DataProvider('infoProvider')] - public function testInfo(\UnitEnum $case, array $expected): void - { - /** @var UnitStatus|StringStatus|IntStatus $case */ - $this->assertSame($expected, $case->info()); - } -} diff --git a/tests/SmartEnumLabelHookTest.php b/tests/SmartEnumLabelHookTest.php deleted file mode 100644 index ced284d..0000000 --- a/tests/SmartEnumLabelHookTest.php +++ /dev/null @@ -1,44 +0,0 @@ -assertSame('ACTIVE', StringStatus::Active->label()); - $this->assertSame(['PENDING', 'ACTIVE', 'DISABLED'], StringStatus::labels()); - $this->assertSame( - ['pending' => 'PENDING', 'active' => 'ACTIVE', 'disabled' => 'DISABLED'], - StringStatus::options(), - ); - $this->assertSame('ACTIVE', StringStatus::Active->info()['label']); - } - - public function testLabelFallsBackToTheCaseNameWhenTheHookReturnsNoString(): void - { - $this->assertSame('Active', UnitStatus::Active->label()); - $this->assertSame('Active', IntStatus::Active->label()); - } -} diff --git a/tests/SmartEnumStaticTest.php b/tests/SmartEnumStaticTest.php deleted file mode 100644 index 41ebb9c..0000000 --- a/tests/SmartEnumStaticTest.php +++ /dev/null @@ -1,150 +0,0 @@ -, list}> - */ - public static function valuesProvider(): iterable - { - yield 'unit' => [UnitStatus::class, ['Pending', 'Active', 'Disabled']]; - yield 'string-backed' => [StringStatus::class, ['pending', 'active', 'disabled']]; - yield 'int-backed' => [IntStatus::class, [0, 1, 2]]; - } - - /** - * @param class-string $enum - */ - #[DataProvider('valuesProvider')] - public function testNames(string $enum): void - { - $this->assertSame(['Pending', 'Active', 'Disabled'], $enum::names()); - } - - public function testNamesKeepCaseNamesAsDeclared(): void - { - $this->assertSame( - ['PENDING', 'IN_COOKING', 'InProgress', 'onHold', 'HTTPError', 'Level2'], - MixedCaseStatus::names(), - ); - } - - /** - * @param class-string $enum - */ - #[DataProvider('valuesProvider')] - public function testLabelsListTheCaseLabels(string $enum): void - { - $this->assertSame(['Pending', 'Active', 'Disabled'], $enum::labels()); - } - - /** - * @param class-string $enum - * @param list $values - */ - #[DataProvider('valuesProvider')] - public function testValuesFallBackToCaseNamesOnUnitEnums(string $enum, array $values): void - { - $this->assertSame($values, $enum::values()); - } - - /** - * @param class-string $enum - * @param list $values - */ - #[DataProvider('valuesProvider')] - public function testOptionsAreLabelsKeyedByValue(string $enum, array $values): void - { - $this->assertSame(array_combine($values, ['Pending', 'Active', 'Disabled']), $enum::options()); - } - - /** - * @param class-string $enum - */ - #[DataProvider('valuesProvider')] - public function testFromNameAndTryFromNameFindTheCase(string $enum): void - { - foreach ($enum::cases() as $case) { - $this->assertSame($case, $enum::fromName($case->name)); - $this->assertSame($case, $enum::tryFromName($case->name)); - } - } - - /** - * @return iterable - */ - public static function unknownNameProvider(): iterable - { - yield 'unknown name' => ['Archived']; - yield 'different case' => ['active']; - yield 'backing value' => ['pending']; - yield 'empty string' => ['']; - } - - #[DataProvider('unknownNameProvider')] - public function testTryFromNameReturnsNullForAnUnknownName(string $name): void - { - $this->assertNull(StringStatus::tryFromName($name)); - $this->assertFalse(StringStatus::hasName($name)); - } - - #[DataProvider('unknownNameProvider')] - public function testFromNameThrowsForAnUnknownName(string $name): void - { - $this->expectException(ValueError::class); - $this->expectExceptionMessage("No case with name {$name} in enum " . StringStatus::class . '.'); - - StringStatus::fromName($name); - } - - /** - * @param class-string $enum - */ - #[DataProvider('valuesProvider')] - public function testHasName(string $enum): void - { - $this->assertTrue($enum::hasName('Active')); - $this->assertFalse($enum::hasName('ACTIVE')); - $this->assertFalse($enum::hasName('Archived')); - } - - /** - * @return iterable, int|string, bool}> - */ - public static function hasValueProvider(): iterable - { - yield 'string value' => [StringStatus::class, 'active', true]; - yield 'string case name' => [StringStatus::class, 'Active', false]; - yield 'string unknown' => [StringStatus::class, 'archived', false]; - yield 'int value' => [IntStatus::class, 1, true]; - yield 'int value as string' => [IntStatus::class, '1', false]; - yield 'int unknown' => [IntStatus::class, 3, false]; - yield 'unit case name' => [UnitStatus::class, 'Active', true]; - yield 'unit lower case' => [UnitStatus::class, 'active', false]; - yield 'unit int' => [UnitStatus::class, 1, false]; - } - - /** - * @param class-string $enum - */ - #[DataProvider('hasValueProvider')] - public function testHasValueIsStrict(string $enum, int|string $value, bool $expected): void - { - $this->assertSame($expected, $enum::hasValue($value)); - } -} diff --git a/tests/SmartEnumStructureTest.php b/tests/SmartEnumStructureTest.php deleted file mode 100644 index b3de328..0000000 --- a/tests/SmartEnumStructureTest.php +++ /dev/null @@ -1,215 +0,0 @@ - [static, [parameter name => type], return type]. - * - * @var array, string}> - */ - private const API = [ - 'names' => [true, [], 'array'], - 'labels' => [true, [], 'array'], - 'values' => [true, [], 'array'], - 'options' => [true, [], 'array'], - 'fromName' => [true, ['name' => 'string'], 'static'], - 'tryFromName' => [true, ['name' => 'string'], '?static'], - 'hasName' => [true, ['name' => 'string'], 'bool'], - 'hasValue' => [true, ['value' => 'int|string'], 'bool'], - 'label' => [false, [], 'string'], - 'eq' => [false, ['enum' => 'UnitEnum'], 'bool'], - '__call' => [false, ['name' => 'string', 'arguments' => 'array'], 'mixed'], - 'is' => [false, ['value' => 'UnitEnum|int|string'], 'bool'], - 'isNot' => [false, ['value' => 'UnitEnum|int|string'], 'bool'], - 'in' => [false, ['values' => 'array'], 'bool'], - 'notIn' => [false, ['values' => 'array'], 'bool'], - 'info' => [false, [], 'array'], - ]; - - /** - * @return iterable, string}> - */ - public static function apiProvider(): iterable - { - foreach (self::API as $method => [$static, $parameters, $return]) { - yield $method => [$method, $static, $parameters, $return]; - } - } - - /** - * @return iterable}> - */ - public static function fixtureProvider(): iterable - { - yield 'unit' => [UnitStatus::class]; - yield 'string-backed' => [StringStatus::class]; - yield 'int-backed' => [IntStatus::class]; - yield 'mixed-case' => [MixedCaseStatus::class]; - } - - public function testSmartEnumIsATrait(): void - { - $this->assertTrue(trait_exists(SmartEnum::class)); - $this->assertTrue((new ReflectionClass(SmartEnum::class))->isTrait()); - } - - public function testTraitDeclaresExactlyTheAgreedApi(): void - { - $declared = array_map( - static fn (ReflectionMethod $method): string => $method->getName(), - (new ReflectionClass(SmartEnum::class))->getMethods(), - ); - - sort($declared); - $expected = array_keys(self::API); - sort($expected); - - $this->assertSame($expected, $declared); - } - - public function testTraitHasNoStateOrNestedTraits(): void - { - $trait = new ReflectionClass(SmartEnum::class); - - $this->assertSame([], $trait->getProperties()); - $this->assertSame([], $trait->getReflectionConstants()); - $this->assertSame([], $trait->getTraitNames()); - } - - /** - * @param array $parameters - */ - #[DataProvider('apiProvider')] - public function testMethodSignature(string $method, bool $static, array $parameters, string $return): void - { - $reflection = new ReflectionMethod(SmartEnum::class, $method); - - $this->assertTrue($reflection->isPublic(), "{$method}() must be public."); - $this->assertSame($static, $reflection->isStatic(), "{$method}() static-ness."); - $this->assertFalse($reflection->isAbstract(), "{$method}() must not be abstract."); - $this->assertSame(count($parameters), $reflection->getNumberOfParameters(), "{$method}() parameter count."); - $this->assertSame( - count($parameters), - $reflection->getNumberOfRequiredParameters(), - "{$method}() required parameters.", - ); - - foreach ($reflection->getParameters() as $index => $parameter) { - $name = array_keys($parameters)[$index]; - - $this->assertSame($name, $parameter->getName(), "{$method}() parameter #{$index} name."); - $this->assertFalse($parameter->isVariadic(), "{$method}() \${$name} must not be variadic."); - $this->assertFalse($parameter->isPassedByReference(), "{$method}() \${$name} must not be by reference."); - $this->assertSame($parameters[$name], self::describe($parameter->getType()), "{$method}() \${$name} type."); - } - - $this->assertSame($return, self::describe($reflection->getReturnType()), "{$method}() return type."); - } - - public function testTraitUsesNoMagicMethodsBesidesCall(): void - { - $trait = new ReflectionClass(SmartEnum::class); - - foreach (['__callStatic', '__get', '__set', '__isset', '__invoke'] as $magic) { - $this->assertFalse($trait->hasMethod($magic), "SmartEnum must not declare {$magic}()."); - } - } - - public function testTraitDoesNotRedefineNativeEnumMethods(): void - { - $trait = new ReflectionClass(SmartEnum::class); - - foreach (['cases', 'from', 'tryFrom'] as $native) { - $this->assertFalse($trait->hasMethod($native), "SmartEnum must not declare {$native}()."); - } - } - - /** - * @param class-string<\UnitEnum> $enum - */ - #[DataProvider('fixtureProvider')] - public function testFixtureUsesTraitAndExposesApi(string $enum): void - { - $reflection = new ReflectionEnum($enum); - - $this->assertContains(SmartEnum::class, $reflection->getTraitNames()); - - foreach (self::API as $method => [$static]) { - $this->assertTrue($reflection->hasMethod($method), "{$enum} is missing {$method}()."); - $this->assertSame( - $static, - $reflection->getMethod($method)->isStatic(), - "{$enum}::{$method}() static-ness.", - ); - } - } - - public function testFixturesCoverUnitAndBackedEnums(): void - { - /** @var array, ?string> $backing */ - $backing = [ - UnitStatus::class => null, - StringStatus::class => 'string', - IntStatus::class => 'int', - ]; - - foreach ($backing as $enum => $type) { - $reflection = new ReflectionEnum($enum); - - $this->assertSame($type !== null, $reflection->isBacked(), "{$enum} backed-ness."); - $this->assertSame((string) $type, (string) $reflection->getBackingType(), "{$enum} backing type."); - $this->assertSame( - ['Pending', 'Active', 'Disabled'], - array_map(static fn (\UnitEnum $case): string => $case->name, $enum::cases()), - ); - } - } - - /** - * Normalises a type to a string. - * - * Union members are sorted (classes first) so declaration order does not matter. - */ - private static function describe(?ReflectionType $type): string - { - if ($type instanceof ReflectionUnionType) { - $names = array_map( - static fn (ReflectionType $member): string => self::describe($member), - $type->getTypes(), - ); - usort( - $names, - static fn (string $a, string $b): int => [ctype_lower($a[0]), $a] <=> [ctype_lower($b[0]), $b], - ); - - return implode('|', $names); - } - - if ($type instanceof ReflectionNamedType) { - return ($type->allowsNull() && $type->getName() !== 'mixed' ? '?' : '') . $type->getName(); - } - - return 'none'; - } -} diff --git a/tests/Unit/CaseChecksTest.php b/tests/Unit/CaseChecksTest.php new file mode 100644 index 0000000..00f00f8 --- /dev/null +++ b/tests/Unit/CaseChecksTest.php @@ -0,0 +1,58 @@ + [$enum::Pending, 'isPending']; + yield "{$enum}::isActive" => [$enum::Active, 'isActive']; + yield "{$enum}::isDisabled" => [$enum::Disabled, 'isDisabled']; + } + + yield 'PENDING' => [MixedCaseStatus::PENDING, 'isPending']; + yield 'IN_COOKING' => [MixedCaseStatus::IN_COOKING, 'isInCooking']; + yield 'InProgress' => [MixedCaseStatus::InProgress, 'isInProgress']; + yield 'onHold' => [MixedCaseStatus::onHold, 'isOnHold']; + yield 'HTTPError' => [MixedCaseStatus::HTTPError, 'isHTTPError']; + yield 'Level2' => [MixedCaseStatus::Level2, 'isLevel2']; + yield 'beside an ambiguous check' => [AmbiguousStatus::Done, 'isDone']; +}); + +it('is true only for the matching case', function (UnitEnum $case, string $method) { + foreach ($case::cases() as $candidate) { + expect($candidate->{$method}())->toBe($candidate === $case); + } +})->with('checks'); + +it('ignores the arguments passed to a check', function (UnitEnum $case, string $method) { + expect($case->{$method}('ignored', 1))->toBeTrue(); +})->with('checks'); + +it('throws for a method that is not a check', function (string $method) { + expect(fn() => MixedCaseStatus::PENDING->{$method}()) + ->toThrow(Error::class, 'Call to undefined method ' . MixedCaseStatus::class . "::{$method}()"); +})->with([ + 'unknown case' => ['isArchived'], + 'no is prefix' => ['pending'], + 'other prefix' => ['hasPending'], + 'raw upper-case name' => ['isPENDING'], + 'raw snake-case name' => ['isIN_COOKING'], + 'lower-case first letter' => ['isonHold'], + 'title-cased acronym' => ['isHttpError'], + 'all lower case' => ['isinprogress'], + 'capital prefix' => ['IsPending'], + 'protected enum method' => ['tag'], +]); + +it('throws for a check shared by two cases', function () { + AmbiguousStatus::Done->isInProgress(); +})->throws( + BadMethodCallException::class, + 'Call to ambiguous method ' . AmbiguousStatus::class . '::isInProgress(): matches cases IN_PROGRESS, InProgress.', +); diff --git a/tests/Unit/InstanceMethodsTest.php b/tests/Unit/InstanceMethodsTest.php new file mode 100644 index 0000000..13e89c9 --- /dev/null +++ b/tests/Unit/InstanceMethodsTest.php @@ -0,0 +1,79 @@ +label())->toBe($case->name); + } + } +}); + +it('compares cases strictly with eq()', function () { + expect(StringStatus::Active->eq(StringStatus::Active))->toBeTrue() + ->and(StringStatus::Active->eq(StringStatus::Disabled))->toBeFalse() + ->and(StringStatus::Active->eq(UnitStatus::Active))->toBeFalse() + ->and(IntStatus::Active->eq(UnitStatus::Active))->toBeFalse(); +}); + +it('matches a case, name or value with is() and isNot()', function (UnitEnum $case, UnitEnum|int|string $value, bool $expected) { + /** @var UnitStatus|StringStatus|IntStatus|CrossedStatus $case */ + expect($case->is($value))->toBe($expected) + ->and($case->isNot($value))->toBe(! $expected); +})->with([ + 'same case' => [StringStatus::Active, StringStatus::Active, true], + 'other case' => [StringStatus::Active, StringStatus::Disabled, false], + 'same name in another enum' => [StringStatus::Active, UnitStatus::Active, false], + 'case name' => [StringStatus::Active, 'Active', true], + 'backing value' => [StringStatus::Active, 'active', true], + 'other case name' => [StringStatus::Active, 'Disabled', false], + 'other backing value' => [StringStatus::Active, 'disabled', false], + 'upper-case value' => [StringStatus::Active, 'ACTIVE', false], + 'int value' => [IntStatus::Active, 1, true], + 'int value as string' => [IntStatus::Active, '1', false], + 'int case name' => [IntStatus::Active, 'Active', true], + 'int other value' => [IntStatus::Active, 2, false], + 'zero is not a name' => [IntStatus::Pending, 'Pending', true], + 'zero is not an empty string' => [IntStatus::Pending, '', false], + 'unit case name' => [UnitStatus::Active, 'Active', true], + 'unit lower case' => [UnitStatus::Active, 'active', false], + 'unit int' => [UnitStatus::Active, 1, false], + 'own name over other value' => [CrossedStatus::Open, 'Open', true], + 'own value over other name' => [CrossedStatus::Open, 'Closed', true], + 'other own name' => [CrossedStatus::Closed, 'Closed', true], + 'other own value' => [CrossedStatus::Closed, 'Open', true], +]); + +it('matches any of the given values with in() and notIn()', function (array $values, bool $expected) { + expect(StringStatus::Active->in($values))->toBe($expected) + ->and(StringStatus::Active->notIn($values))->toBe(! $expected); +})->with([ + 'empty list' => [[], false], + 'matching case' => [[StringStatus::Pending, StringStatus::Active], true], + 'no matching case' => [[StringStatus::Pending, StringStatus::Disabled], false], + 'matching value' => [['pending', 'active'], true], + 'matching name' => [['Pending', 'Active'], true], + 'mixed kinds' => [[StringStatus::Pending, 'Disabled', 'active'], true], + 'nothing matches' => [[StringStatus::Pending, 'Disabled', 'archived', 1], false], + 'same name in another enum' => [[UnitStatus::Active], false], +]); + +it('accepts an associative array in in()', function () { + expect(StringStatus::Active->in(['first' => 'pending', 'second' => 'active']))->toBeTrue(); +}); + +it('describes a case with info()', function (UnitEnum $case, array $expected) { + /** @var UnitStatus|StringStatus|IntStatus $case */ + expect($case->info())->toBe($expected); +})->with([ + 'string-backed' => [StringStatus::Active, ['name' => 'Active', 'value' => 'active', 'label' => 'Active']], + 'int-backed' => [IntStatus::Pending, ['name' => 'Pending', 'value' => 0, 'label' => 'Pending']], + 'unit' => [UnitStatus::Active, ['name' => 'Active', 'value' => 'Active', 'label' => 'Active']], +]); diff --git a/tests/Unit/LabelHookTest.php b/tests/Unit/LabelHookTest.php new file mode 100644 index 0000000..da004aa --- /dev/null +++ b/tests/Unit/LabelHookTest.php @@ -0,0 +1,35 @@ + + */ +function labelsWithHook(): array +{ + $script = dirname(__DIR__) . '/Fixtures/label-hook-run.php'; + exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($script), $output, $status); + + expect($status)->toBe(0); + + return json_decode(implode("\n", $output), true, 512, JSON_THROW_ON_ERROR); +} + +it('uses the global smart_enum_label() hook', function () { + expect(labelsWithHook())->toMatchArray([ + 'label' => 'ACTIVE', + 'labels' => ['PENDING', 'ACTIVE', 'DISABLED'], + 'options' => ['pending' => 'PENDING', 'active' => 'ACTIVE', 'disabled' => 'DISABLED'], + 'info' => 'ACTIVE', + ]); +}); + +it('falls back to the case name when the hook returns no string', function () { + expect(labelsWithHook())->toMatchArray(['unit' => 'Active', 'int' => 'Active']); +}); + +it('does not define the hook outside its own process', function () { + expect(function_exists('smart_enum_label'))->toBeFalse(); +}); diff --git a/tests/Unit/LocaleTest.php b/tests/Unit/LocaleTest.php new file mode 100644 index 0000000..6075296 --- /dev/null +++ b/tests/Unit/LocaleTest.php @@ -0,0 +1,49 @@ +markTestSkipped('No Turkish locale is installed.'); + } + + try { + $callback(); + } finally { + setlocale(LC_CTYPE, $previous === false ? 'C' : $previous); + } +} + +it('builds check names from ASCII letters only', function (string $case, string $method) { + expect(CaseMethods::methodName($case))->toBe($method); +})->with([ + 'upper-case word' => ['PENDING', 'isPending'], + 'upper-case words' => ['IN_REVIEW', 'isInReview'], + 'only I' => ['I', 'isI'], + 'leading I' => ['IDLE', 'isIdle'], + 'acronym word kept' => ['HTTPError', 'isHTTPError'], + 'lower-case first letter' => ['onHold', 'isOnHold'], + 'digits' => ['LEVEL_2', 'isLevel2'], + 'non-ASCII bytes kept' => ['ÉTÉ', 'isÉtÉ'], +]); + +it('builds check names the same way under a Turkish locale', function () { + withTurkishLocale(function () { + expect(CaseMethods::methodName('PENDING'))->toBe('isPending') + ->and(CaseMethods::methodName('IN_REVIEW'))->toBe('isInReview') + ->and(LocaleStatus::PENDING->isPending())->toBeTrue() + ->and(LocaleStatus::IN_REVIEW->isInReview())->toBeTrue() + ->and(LocaleStatus::IDLE->isPending())->toBeFalse() + ->and(LocaleStatus::IDLE->isIdle())->toBeTrue(); + }); +}); diff --git a/tests/Unit/StaticMethodsTest.php b/tests/Unit/StaticMethodsTest.php new file mode 100644 index 0000000..d9c3f52 --- /dev/null +++ b/tests/Unit/StaticMethodsTest.php @@ -0,0 +1,78 @@ + [UnitStatus::class, ['Pending', 'Active', 'Disabled']], + 'string-backed' => [StringStatus::class, ['pending', 'active', 'disabled']], + 'int-backed' => [IntStatus::class, [0, 1, 2]], +]); + +dataset('unknown names', [ + 'unknown name' => ['Archived'], + 'different case' => ['active'], + 'backing value' => ['pending'], + 'empty string' => [''], +]); + +it('lists the case names', function (string $enum) { + expect($enum::names())->toBe(['Pending', 'Active', 'Disabled']); +})->with('enums'); + +it('keeps case names as declared', function () { + expect(MixedCaseStatus::names())->toBe(['PENDING', 'IN_COOKING', 'InProgress', 'onHold', 'HTTPError', 'Level2']); +}); + +it('lists the case labels', function (string $enum) { + expect($enum::labels())->toBe(['Pending', 'Active', 'Disabled']); +})->with('enums'); + +it('lists backing values, or case names on unit enums', function (string $enum, array $values) { + expect($enum::values())->toBe($values); +})->with('enums'); + +it('keys the labels by value in options()', function (string $enum, array $values) { + expect($enum::options())->toBe(array_combine($values, ['Pending', 'Active', 'Disabled'])); +})->with('enums'); + +it('finds a case by name', function (string $enum) { + foreach ($enum::cases() as $case) { + expect($enum::fromName($case->name))->toBe($case) + ->and($enum::tryFromName($case->name))->toBe($case); + } +})->with('enums'); + +it('returns null for an unknown name', function (string $name) { + expect(StringStatus::tryFromName($name))->toBeNull() + ->and(StringStatus::hasName($name))->toBeFalse(); +})->with('unknown names'); + +it('throws for an unknown name', function (string $name) { + expect(fn() => StringStatus::fromName($name)) + ->toThrow(ValueError::class, "No case with name {$name} in enum " . StringStatus::class . '.'); +})->with('unknown names'); + +it('checks case names exactly with hasName()', function (string $enum) { + expect($enum::hasName('Active'))->toBeTrue() + ->and($enum::hasName('ACTIVE'))->toBeFalse() + ->and($enum::hasName('Archived'))->toBeFalse(); +})->with('enums'); + +it('checks values strictly with hasValue()', function (string $enum, int|string $value, bool $expected) { + expect($enum::hasValue($value))->toBe($expected); +})->with([ + 'string value' => [StringStatus::class, 'active', true], + 'string case name' => [StringStatus::class, 'Active', false], + 'string unknown' => [StringStatus::class, 'archived', false], + 'int value' => [IntStatus::class, 1, true], + 'int value as string' => [IntStatus::class, '1', false], + 'int unknown' => [IntStatus::class, 3, false], + 'unit case name' => [UnitStatus::class, 'Active', true], + 'unit lower case' => [UnitStatus::class, 'active', false], + 'unit int' => [UnitStatus::class, 1, false], +]); diff --git a/tests/Unit/StructureTest.php b/tests/Unit/StructureTest.php new file mode 100644 index 0000000..9fe50b0 --- /dev/null +++ b/tests/Unit/StructureTest.php @@ -0,0 +1,146 @@ + [static, [parameter name => type], return type]. + * + * @return array, string}> + */ +function smartEnumApi(): array +{ + return [ + 'names' => [true, [], 'array'], + 'labels' => [true, [], 'array'], + 'values' => [true, [], 'array'], + 'options' => [true, [], 'array'], + 'fromName' => [true, ['name' => 'string'], 'static'], + 'tryFromName' => [true, ['name' => 'string'], '?static'], + 'hasName' => [true, ['name' => 'string'], 'bool'], + 'hasValue' => [true, ['value' => 'int|string'], 'bool'], + 'label' => [false, [], 'string'], + 'eq' => [false, ['enum' => 'UnitEnum'], 'bool'], + '__call' => [false, ['name' => 'string', 'arguments' => 'array'], 'mixed'], + 'is' => [false, ['value' => 'UnitEnum|int|string'], 'bool'], + 'isNot' => [false, ['value' => 'UnitEnum|int|string'], 'bool'], + 'in' => [false, ['values' => 'array'], 'bool'], + 'notIn' => [false, ['values' => 'array'], 'bool'], + 'info' => [false, [], 'array'], + ]; +} + +/** + * Normalises a type to a string; union members are sorted (classes first) so declaration order does not matter. + */ +function describeType(?ReflectionType $type): string +{ + if ($type instanceof ReflectionUnionType) { + $names = array_map(static fn(ReflectionType $member): string => describeType($member), $type->getTypes()); + usort($names, static fn(string $a, string $b): int => [ctype_lower($a[0]), $a] <=> [ctype_lower($b[0]), $b]); + + return implode('|', $names); + } + + if ($type instanceof ReflectionNamedType) { + return ($type->allowsNull() && $type->getName() !== 'mixed' ? '?' : '') . $type->getName(); + } + + return 'none'; +} + +it('is a trait', function () { + expect(trait_exists(SmartEnum::class))->toBeTrue() + ->and((new ReflectionClass(SmartEnum::class))->isTrait())->toBeTrue(); +}); + +it('declares exactly the agreed API', function () { + $declared = array_map( + static fn(ReflectionMethod $method): string => $method->getName(), + (new ReflectionClass(SmartEnum::class))->getMethods(), + ); + $expected = array_keys(smartEnumApi()); + + sort($declared); + sort($expected); + + expect($declared)->toBe($expected); +}); + +it('has no state or nested traits', function () { + $trait = new ReflectionClass(SmartEnum::class); + + expect($trait->getProperties())->toBe([]) + ->and($trait->getReflectionConstants())->toBe([]) + ->and($trait->getTraitNames())->toBe([]); +}); + +it('declares each method with its agreed signature', function (string $method) { + [$static, $parameters, $return] = smartEnumApi()[$method]; + $reflection = new ReflectionMethod(SmartEnum::class, $method); + + expect($reflection->isPublic())->toBeTrue() + ->and($reflection->isStatic())->toBe($static) + ->and($reflection->isAbstract())->toBeFalse() + ->and($reflection->getNumberOfParameters())->toBe(count($parameters)) + ->and($reflection->getNumberOfRequiredParameters())->toBe(count($parameters)); + + foreach ($reflection->getParameters() as $index => $parameter) { + $name = array_keys($parameters)[$index]; + + expect($parameter->getName())->toBe($name) + ->and($parameter->isVariadic())->toBeFalse() + ->and($parameter->isPassedByReference())->toBeFalse() + ->and(describeType($parameter->getType()))->toBe($parameters[$name]); + } + + expect(describeType($reflection->getReturnType()))->toBe($return); +})->with(array_keys(smartEnumApi())); + +it('uses no magic method besides __call()', function () { + $trait = new ReflectionClass(SmartEnum::class); + + foreach (['__callStatic', '__get', '__set', '__isset', '__invoke'] as $magic) { + expect($trait->hasMethod($magic))->toBeFalse(); + } +}); + +it('does not redefine native enum methods', function () { + $trait = new ReflectionClass(SmartEnum::class); + + foreach (['cases', 'from', 'tryFrom'] as $native) { + expect($trait->hasMethod($native))->toBeFalse(); + } +}); + +it('exposes the API on every fixture', function (string $enum) { + $reflection = new ReflectionEnum($enum); + + expect($reflection->getTraitNames())->toContain(SmartEnum::class); + + foreach (smartEnumApi() as $method => [$static]) { + expect($reflection->hasMethod($method))->toBeTrue() + ->and($reflection->getMethod($method)->isStatic())->toBe($static); + } +})->with([ + 'unit' => [UnitStatus::class], + 'string-backed' => [StringStatus::class], + 'int-backed' => [IntStatus::class], + 'mixed-case' => [MixedCaseStatus::class], +]); + +it('covers unit and backed enums in the fixtures', function () { + foreach ([UnitStatus::class => null, StringStatus::class => 'string', IntStatus::class => 'int'] as $enum => $type) { + $reflection = new ReflectionEnum($enum); + + expect($reflection->isBacked())->toBe($type !== null) + ->and((string) $reflection->getBackingType())->toBe((string) $type) + ->and(array_map(static fn(UnitEnum $case): string => $case->name, $enum::cases())) + ->toBe(['Pending', 'Active', 'Disabled']); + } +});