diff --git a/.gitattributes b/.gitattributes index c18657a..68d9168 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,8 +1,13 @@ -.gitattributes export-ignore -.gitignore export-ignore -.scrutinizer.yml export-ignore -.travis.coverage.sh export-ignore -.travis.yml export-ignore -phpcs.xml.dist export-ignore -phpunit.xml.dist export-ignore -phpstan.xml.dist export-ignore +# Keep the distributed package small: development files are not exported +/.github export-ignore +/demo export-ignore +/tests export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.php-cs-fixer.dist.php export-ignore +/phpstan.neon.dist export-ignore +/phpunit.xml.dist export-ignore +/CONTRIBUTING.md export-ignore +/AGENTS.md export-ignore + +*.php diff=php diff --git a/.github/dependabot.yml b/.github/dependabot.yml index a04daea..7182100 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,13 +1,13 @@ version: 2 updates: -- package-ecosystem: composer - directory: "/" - schedule: - interval: daily - open-pull-requests-limit: 10 - ignore: - - dependency-name: phpstan/phpstan - versions: - - 0.12.82 - - 0.12.83 - - 0.12.84 + - package-ecosystem: composer + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 10 + versioning-strategy: increase-if-necessary + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..41b96fe --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,80 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + tests: + name: Tests (PHP ${{ matrix.php }}, ${{ matrix.dependencies }} deps) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ['8.4', '8.5'] + dependencies: [highest] + include: + - php: '8.4' + dependencies: lowest + steps: + - uses: actions/checkout@v5 + + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: pcov + tools: composer:v2 + + - uses: ramsey/composer-install@v3 + with: + dependency-versions: ${{ matrix.dependencies }} + + - name: Run test suite + run: vendor/bin/phpunit --coverage-text --coverage-clover=coverage.xml + + - name: Run demo + run: composer demo + + static-analysis: + name: PHPStan (level 10) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.4' + coverage: none + + - uses: ramsey/composer-install@v3 + + - name: Run PHPStan + run: composer phpstan -- --error-format=github + + coding-style: + name: Coding style + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.4' + coverage: none + + - uses: ramsey/composer-install@v3 + + - name: Run PHP-CS-Fixer + run: composer cs + + - name: Check for vulnerable dependencies + run: composer audit diff --git a/.gitignore b/.gitignore index 69f917b..c059a2a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,19 @@ # Composer -vendor/ -composer.lock +/vendor/ +/composer.lock -# Cache +# Caches /tests/cache/ /demo/cache/ +/.phpunit.cache/ +/.phpstan.cache/ +/.php-cs-fixer.cache -# Code quality +# Local overrides of the distributed configuration /phpunit.xml -/phpcs.xml /phpstan.neon +/.php-cs-fixer.php - - +# Coverage reports +/coverage/ +/coverage.xml diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..7a12a6e --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,32 @@ +in([__DIR__ . '/src', __DIR__ . '/tests', __DIR__ . '/demo']) + ->exclude(['cache']) + ->append([__FILE__]); + +return new Config() + ->setParallelConfig(ParallelConfigFactory::detect()) + ->setRiskyAllowed(true) + ->setRules([ + '@PER-CS2x0' => true, + '@PER-CS2x0:risky' => true, + 'declare_strict_types' => true, + 'native_function_invocation' => ['include' => ['@all'], 'scope' => 'all', 'strict' => true], + 'no_unused_imports' => true, + 'ordered_imports' => ['imports_order' => ['class', 'function', 'const'], 'sort_algorithm' => 'alpha'], + 'global_namespace_import' => ['import_classes' => true, 'import_constants' => false, 'import_functions' => false], + 'phpdoc_align' => ['align' => 'vertical'], + 'phpdoc_trim' => true, + 'single_quote' => true, + 'trailing_comma_in_multiline' => ['elements' => ['arguments', 'arrays', 'match', 'parameters']], + 'binary_operator_spaces' => ['default' => 'single_space', 'operators' => ['=>' => 'align_single_space_minimal', '=' => 'align_single_space_minimal']], + ]) + ->setFinder($finder) + ->setCacheFile(__DIR__ . '/.php-cs-fixer.cache'); diff --git a/.scrutinizer.yml b/.scrutinizer.yml deleted file mode 100644 index 0dd1d45..0000000 --- a/.scrutinizer.yml +++ /dev/null @@ -1,34 +0,0 @@ -before_commands: - - "composer install --no-dev --prefer-source" - -tools: - external_code_coverage: - timeout: 1200 - php_code_coverage: - enabled: true - php_code_sniffer: - enabled: true - config: - standard: PSR12 - filter: - paths: ["src/*"] - php_cpd: - enabled: true - excluded_dirs: ["docs", "demo", "tests", "vendor"] - php_cs_fixer: - enabled: true - config: - level: all - filter: - paths: ["src/*"] - php_loc: - enabled: true - excluded_dirs: ["docs", "demo", "tests", "vendor"] - php_pdepend: - enabled: true - excluded_dirs: ["docs", "demo", "tests", "vendor"] - php_analyzer: - enabled: true - filter: - paths: ["src/*"] - sensiolabs_security_checker: true diff --git a/.travis.coverage.sh b/.travis.coverage.sh deleted file mode 100755 index 1053a00..0000000 --- a/.travis.coverage.sh +++ /dev/null @@ -1,5 +0,0 @@ -set -x -if [ "$TRAVIS_PHP_VERSION" = '7.2' ] ; then - wget https://scrutinizer-ci.com/ocular.phar - php ocular.phar code-coverage:upload --format=php-clover ./clover.xml -fi diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 9d8ff85..0000000 --- a/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: php - -php: - - 7.1 - - 7.2 - - 7.3 - - 7.4 - -before_script: - - composer install - -script: - - vendor/bin/phpunit --verbose --coverage-text --coverage-clover=clover.xml --colors - - vendor/bin/phpcs src/ tests/ - - vendor/bin/phpstan analyze - -after_script: - - sh .travis.coverage.sh diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..e680191 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,103 @@ +# AGENTS.md + +Guidance for AI coding agents working on this repository. Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md). + +## Project + +`php-deal/framework` is a Design by Contract library for PHP. Contracts are native attributes +(`#[Verify]`, `#[Ensure]`, `#[Invariant]`, `#[Inherit]`) whose string arguments are PHP expressions. Aspects of +[Go! AOP 4](https://github.com/goaop/framework) weave the annotated classes and evaluate the expressions on every +call. + +- PHP **8.4+** (CI runs 8.4 and 8.5). Do not use PHP 8.5-only features; PHPStan analyses for the 8.4โ€“8.5 range. +- Runtime dependency: `goaop/framework ^4.0` only. Do not add runtime dependencies without a strong reason. +- Version 2.x is a major rewrite of 1.x (Doctrine annotations). Keep [UPGRADE-2.0.md](UPGRADE-2.0.md) and + [CHANGELOG.md](CHANGELOG.md) in sync with behaviour changes. + +## Commands + +```bash +composer install +composer test # everything below, in this order +composer cs # PHP-CS-Fixer check (composer cs:fix to fix) +composer phpstan # PHPStan level 10 + strict rules + phpunit extension +composer phpunit # unit and functional test suites +composer demo # runs demo/run.php, a smoke test of real weaving +``` + +Run `composer test` before you commit. All three checks must pass. CI (`.github/workflows/ci.yml`) also runs a +lowest-dependencies job and `composer audit`. + +## Layout + +| Path | Contents | +|------------------------------|----------| +| `src/Attribute/` | The attributes. `Verify`, `Ensure`, `Invariant` implement the `Contract` interface (`$expression`). | +| `src/Aspect/` | One Go! AOP aspect per contract kind. The pointcuts are in their advice attributes. | +| `src/Contract/ContractFetcher.php` | Collects contracts from the method/class and its parents and interfaces, with caching. | +| `src/Contract/ContractEvaluator.php` | Compiles expressions to closures (once), binds them to the object/scope, evaluates them. | +| `src/Contract/BoundContract.php` | A contract plus the class scope its expression runs in. | +| `src/Contract/ContractKind.php` | Enum that maps a check to its violation exception. | +| `src/Exception/` | `ContractViolation` and its subclasses, `InvalidContractException`, `ExceptionInterface`. | +| `src/PHPStan/` | PHPStan extension (registered by `extension.neon`): members used only by contracts count as used. | +| `src/ContractApplication.php`| The aspect kernel; `registerAspects()` for apps that have their own kernel. | +| `tests/Fixtures/` | Classes **woven** by the test bootstrap. Only this directory is in `includePaths`. | +| `tests/Functional/` | Tests that call fixtures through real weaving. | +| `tests/Unit/` | Tests without weaving; `tests/Unit/Stub/FakeInvocation.php` is a hand-made `MethodInvocation`. | +| `demo/` | Runnable example, also run in CI. | + +## How it works (read before changing behaviour) + +- **Pointcuts.** Preconditions use `#[Before]`; postconditions and invariants use `#[Around]`. Go! AOP 4 requires + advice methods to be `public`, with one advice attribute per method. +- **Inheritance rules.** These are deliberate and documented in the README: + - `Ensure` and `Invariant` always include the contracts of parent classes and interfaces. + - `Verify` includes them only with `#[Inherit]` (on the method or class) or an `{@inheritdoc}` tag. + - A class whose own methods carry no contract attribute and that has no `#[Inherit]` is not woven. +- **Scope.** A contract runs in the scope of the class that declares it (`BoundContract::$scope`), so parent + contracts can read the parent's private state. Interface contracts run in the scope of the implementing class. +- **Variables.** + - Arguments are available by parameter name, with defaults filled in; variadics become a list. + - `$__result` holds the return value (postconditions and invariants). + - `$__old` is a clone taken before the call. It is cloned only if an expression contains `$__old`. +- **Results.** + - `false` means the contract is violated. + - `true` or `null` means it holds (`null` exists for assertion libraries). + - Any other result, a `ParseError`, or `$this` in a static method throws `InvalidContractException`. + - A `Throwable` thrown by the expression becomes the `previous` exception of a violation. +- **Recursion guard.** While an expression is evaluated, `ContractEvaluator::isEvaluating()` is true and every aspect + skips its checks. This lets an invariant call public methods of its own class. +- **Woven classes.** Go! AOP 4 turns the original class body into a `OriginalTrait`, and the proxy keeps the + original class name. `ContractViolation` reports the location of the `...OriginalAlias` method, so file and line + point to the user's source. + +## Conventions + +- `declare(strict_types=1);` everywhere, and the license header from existing `src/` files on new `src/` files. +- Coding style is PER-CS 2.0 plus the rules in `.php-cs-fixer.dist.php`: + - Global functions are fully qualified (`\count()`). + - Imports are sorted. + - `=>` and `=` are aligned. +- Prefer `final` / `final readonly` classes and constructor promotion. Use typed constants and properties. +- PHPStan is at level 10. **Never** add `@phpstan-ignore`, baseline entries or `assert()`/`@var` casts to silence + errors. Fix the types instead. Give generics explicit types (e.g. `ReflectionClass`). +- Contract expressions in fixtures, the README and the demo are single-quoted strings: `#[Verify('$amount > 0')]`. + Global functions in expressions are written `\is_numeric(...)`, and class names fully qualified, because `use` + imports do not apply inside expressions. +- Keep comments short and useful. Public API classes need a class docblock that explains their purpose. + +## Testing tips + +- Woven code is cached in `tests/cache/` (and in `demo/cache/` for the demo). If results look stale, delete it. +- A new class that must be woven goes in `tests/Fixtures//`, namespace + `PhpDeal\Tests\Fixtures\`, and is loaded through Composer. Classes loaded any other way are not woven. +- Use PHPUnit 13 attributes (`#[DataProvider]`, `#[TestWith]`, `#[CoversClass]`); data providers are `static`. +- PHPUnit fails on warnings, notices, deprecations and risky tests. +- The fixtures also test the PHPStan extension. If you remove a contract that reads a private property, PHPStan + starts to report that property, which is the extension working as intended. + +## Before you finish + +1. `composer test` passes. +2. Behaviour changes are reflected in `README.md`, `CHANGELOG.md` and, if they break BC, `UPGRADE-2.0.md`. +3. README code examples still work: they are meant to be copy-paste runnable. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..536fd00 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,52 @@ +Changelog +========= + +All notable changes to this project are documented in this file. The format is based on +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to +[Semantic Versioning](https://semver.org/). + +2.0.0 - unreleased +------------------ + +A rewrite for modern PHP. See [UPGRADE-2.0.md](UPGRADE-2.0.md) for the migration steps. + +### Added + +- Native PHP attributes `#[Verify]`, `#[Ensure]`, `#[Invariant]` and `#[Inherit]` in `PhpDeal\Attribute`; contracts + are repeatable and implement the `PhpDeal\Attribute\Contract` interface. +- Dedicated exceptions `PreconditionViolation`, `PostconditionViolation` and `InvariantViolation`, the + `ExceptionInterface` marker and `InvalidContractException` for broken contracts. +- `ContractViolation` exposes the violated `$contract`, the `$className` and the `$methodName`. +- `ContractApplication::registerAspects()` to enable contracts from an existing Go! AOP kernel. +- Contracts on static methods. +- Class-level `#[Inherit]` enables the contracts of parents for every public method. +- Invariants are checked after the constructor. +- PHPStan extension: properties and methods used only by contracts are not reported as unused. +- GitHub Actions CI on PHP 8.4 and 8.5, PHPStan level 10 with strict rules, PHP-CS-Fixer. + +### Changed + +- Requires PHP 8.4+ and Go! AOP 4. +- Each contract expression is compiled once and cached; contracts are read once per method and class. +- Contracts of parent classes are evaluated in the scope of the declaring class. +- Inherited preconditions are checked before the method body. +- The object is cloned for `$__old` only when a postcondition uses it. +- Violations point to the line of the method that declares the contract. + +### Fixed + +- An invariant calling a public method of its own class no longer recurses endlessly. +- Arrays and objects among the arguments no longer break the violation message. +- Variadic arguments are passed to contracts as a list. +- A trailing `//` comment in an expression no longer breaks it. + +### Removed + +- Doctrine annotations (`PhpDeal\Annotation`) and the dependency on `doctrine/annotations`. +- `AbstractContractAspect`, `InheritCheckerAspect` and the `PhpDeal\Contract\Fetcher\Parent` classes. +- Travis CI and Scrutinizer configuration. + +1.x +--- + +See the [GitHub releases](https://github.com/php-deal/framework/releases) for the history of the 1.x line. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index db779d4..eed937f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -43,7 +43,30 @@ Making Changes - Make sure you have added the necessary tests for your changes. -- Run *all* the tests to assure nothing else was accidentally broken. +- Run *all* the checks to assure nothing else was accidentally broken. + +Development +----------- + +PHP 8.4 or newer is required. Install the dependencies and run every check with Composer: + +```bash +composer install +composer test # coding style, PHPStan (level 10) and PHPUnit +``` + +The checks can also be run one by one: + +| Command | What it does | +|----------------------|------------------------------------------------------| +| `composer phpunit` | Runs the unit and functional test suites | +| `composer phpstan` | Runs static analysis at PHPStan level 10 | +| `composer cs` | Checks the coding style (PER-CS 2.0) | +| `composer cs:fix` | Fixes the coding style | +| `composer demo` | Runs the demo application from the `demo/` directory | + +Functional tests weave the classes in `tests/Fixtures` with Go! AOP. The woven code is cached in `tests/cache`; +delete that directory if you ever see stale results. Submitting Changes ------------------ diff --git a/README.md b/README.md index 4346a32..8311fe1 100644 --- a/README.md +++ b/README.md @@ -1,379 +1,418 @@ -PhpDeal -------- +
-Design by Contract framework for PHP +# PhpDeal -What is Design by Contract? ---------------------------- +**Design by Contract for modern PHP** -The specification of a class or interface is the collection of non-private items provided as services to the -caller, along with instructions for their use, as stated in phpDoc. [Design By Contract](http://en.wikipedia.org/wiki/Design_by_contract) is an effective technology -for creating a specification. +Declare preconditions, postconditions and invariants with native attributes.
+PhpDeal checks them on every call, powered by [Go! AOP](https://github.com/goaop/framework). -The fundamental idea of Design By Contract is to treat the services offered by a class or interface as a -contract between the class (or interface) and its caller. Here, the word "contract" is meant to convey a kind -of formal, unambiguous agreement between two parties: +[![CI](https://github.com/php-deal/framework/actions/workflows/ci.yml/badge.svg)](https://github.com/php-deal/framework/actions/workflows/ci.yml) +[![Latest Version](https://img.shields.io/packagist/v/php-deal/framework.svg?label=release)](https://packagist.org/packages/php-deal/framework) +[![Total Downloads](https://img.shields.io/packagist/dt/php-deal/framework.svg)](https://packagist.org/packages/php-deal/framework) +[![PHP Version](https://img.shields.io/badge/php-%E2%89%A5%208.4-777BB4.svg?logo=php&logoColor=white)](https://www.php.net/releases/8.4/) +[![Go! AOP](https://img.shields.io/badge/Go!%20AOP-4.x-1f6feb.svg)](https://github.com/goaop/framework) +[![PHPStan](https://img.shields.io/badge/PHPStan-level%2010-2a5ea7.svg)](https://phpstan.org/user-guide/rule-levels) +[![License](https://img.shields.io/packagist/l/php-deal/framework.svg)](LICENSE) -* requirements upon the caller made by the class -* promises made by the class to the caller +
-If the caller fulfills the requirements, then the class promises to deliver some well-defined service. Some -changes to a specification/contract will break the caller, and some won't. For determining if a change will -break a caller, C++ FAQs uses the memorable phrase "require no more, promise no less": if the new specification -does not require more from the caller than before, and if it does not promise to deliver less than before, -then the new specification is compatible with the old, and will not break the caller. - -[![Build Status](https://api.travis-ci.org/php-deal/framework.png?branch=1.x)](https://travis-ci.org/php-deal/framework) -[![GitHub release](https://img.shields.io/github/release/php-deal/framework.svg)](https://github.com/php-deal/framework/releases/latest) -[![Code Coverage](https://scrutinizer-ci.com/g/php-deal/framework/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/php-deal/framework/?branch=1.x) -[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/php-deal/framework/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/php-deal/framework/?branch=1.x) -[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D7.1-blue.svg)](https://php.net/) -[![License](https://img.shields.io/packagist/l/php-deal/framework.svg)](https://packagist.org/packages/php-deal/framework) +```php +use PhpDeal\Attribute\{Ensure, Invariant, Verify}; -Installation ------------- +#[Invariant('$this->balance >= 0')] +class Account +{ + private float $balance = 0.0; -PhpDeal framework can be installed with composer. Installation is quite easy, just ask composer to download -the framework with its dependencies by running the command: + #[Verify('$amount > 0')] + #[Ensure('$this->balance === $__old->balance + $amount')] + public function deposit(float $amount): void + { + $this->balance += $amount; + } +} -``` bash -$ composer require php-deal/framework +new Account()->deposit(-10); +// PhpDeal\Exception\PreconditionViolation: +// Precondition "$amount > 0" violated in Account->deposit(-10.0) ``` -Setup ------ - -Put the following code at the beginning of your -application entry point or require it from an external file. - -```php - -$instance = ContractApplication::getInstance(); -$instance->init(array( - 'debug' => true, - 'appDir' => __DIR__, - 'excludePaths' => [ - __DIR__ . '/vendor' - ], - 'includePaths' => [ - - ], - 'cacheDir' => __DIR__.'/cache/', -)); +## Contents + +- [Why Design by Contract?](#why-design-by-contract) +- [Features](#features) +- [Installation](#installation) +- [Setup](#setup) +- [Contracts](#contracts) + - [Preconditions: `#[Verify]`](#preconditions-verify) + - [Postconditions: `#[Ensure]`](#postconditions-ensure) + - [Invariants: `#[Invariant]`](#invariants-invariant) + - [Inheritance: `#[Inherit]`](#inheritance-inherit) +- [Writing expressions](#writing-expressions) +- [Handling violations](#handling-violations) +- [PHPStan integration](#phpstan-integration) +- [Production](#production) +- [Upgrading from 1.x](#upgrading-from-1x) +- [Contributing](#contributing) + +## Why Design by Contract? + +[Design by Contract](https://en.wikipedia.org/wiki/Design_by_contract) treats the public API of a class as a formal +agreement between the class and its callers: + +- **Preconditions** are the requirements upon the caller: what must be true before a method is called. +- **Postconditions** are the promises of the method: what is true after it returns. +- **Invariants** are the properties of an object that always hold between calls. + +If the caller meets the requirements, the class delivers the promised service. A broken contract is a bug, and +PhpDeal reports it at the exact place where it happens instead of letting a corrupt state travel through the +application. The contracts live next to the code they describe, so they double as precise, executable +documentation. + +## Features + +- โœ… **Native PHP attributes**: `#[Verify]`, `#[Ensure]`, `#[Invariant]` and `#[Inherit]`, repeatable where it makes sense. +- ๐Ÿงฌ **Contract inheritance** from parent classes and interfaces, with clear and predictable rules. +- ๐Ÿ”’ **Full access to the object**: expressions run in the scope of the class and can read private state. +- ๐Ÿ•ฐ๏ธ **`$__old` and `$__result`** to compare the state before and after a call, and to check return values. +- ๐ŸŽฏ **Precise exceptions**: `PreconditionViolation`, `PostconditionViolation` and `InvariantViolation`, pointing to + the method that declares the contract. +- โšก **Fast**: each expression is compiled once, contracts are read once per class, and the object is cloned only when + a contract uses `$__old`. +- ๐Ÿ” **Recursion-safe**: an invariant may call public methods of its own class. +- ๐Ÿงฉ **Works with assertion libraries** such as [beberlei/assert](https://github.com/beberlei/assert). +- ๐Ÿ” **PHPStan extension** included: properties and methods used only by contracts are not reported as unused. +- ๐Ÿงช **Thoroughly tested**, analysed with PHPStan at level 10 with strict rules. + +## Installation + +```bash +composer require php-deal/framework ``` -Symfony setup -------------- +PhpDeal 2 requires **PHP 8.4** or newer and is built on **Go! AOP 4**. -Put the following code in app_dev.php and adapt it to match -your folder structure. The appDir must point to the folder containing -the src files, not the document root folder ! +## Setup -```php +Initialize the contract kernel once, as early as possible in your front controller or test bootstrap, before the +classes with contracts are loaded: -$instance = ContractApplication::getInstance(); -$instance->init(array( - 'debug' => true, - 'appDir' => __DIR__ . '/../src', - 'excludePaths' => [ +```php +use PhpDeal\ContractApplication; - ], - 'includePaths' => [ +require __DIR__ . '/../vendor/autoload.php'; - ], - 'cacheDir' => __DIR__.'/var/cache/', -)); +ContractApplication::getInstance()->init([ + 'debug' => true, + 'appDir' => __DIR__ . '/..', + 'cacheDir' => __DIR__ . '/../var/cache/contracts', + 'includePaths' => [__DIR__ . '/../src'], +]); ``` +| Option | Purpose | +|----------------|---------------------------------------------------------------------------------------------| +| `debug` | `true` during development: changed classes are woven again automatically. | +| `appDir` | Root directory of the application, usually the directory that contains `vendor/`. | +| `cacheDir` | Writable directory for the woven classes. | +| `includePaths` | Directories with the classes that declare contracts. Keep it narrow, it speeds up weaving. | +| `excludePaths` | Directories that are never woven. | -Pre and Post Contracts ----------------------- +All [Go! AOP kernel options](https://github.com/goaop/framework/blob/master/docs/configuration.md) are supported. -The pre contracts specify the preconditions (requirements) before a statement is executed. The most typical use -of this would be in validating the parameters to a function. The post contracts (promises) validate the result -of the statement. The most typical use of this would be in validating the return value of a method and of -any side effects it has. The syntax is: +### Already using Go! AOP? -```php -0 && is_numeric($amount)") - * @Contract\Ensure("$this->balance == $__old->balance+$amount") - */ - public function deposit($amount) + protected function configureAop(AspectContainer $container): void { - $this->balance += $amount; + ContractApplication::registerAspects($container); + // ...your own aspects } } ``` -By definition, if a pre contract fails, then the body received bad parameters. A ContractViolation exception -is thrown. -If a post contract fails, then there is a bug in the body. A ContractViolation exception is thrown. +### Symfony -Invariants ----------- +Initialize the kernel in `public/index.php` (and in `tests/bootstrap.php`) right after the Composer autoloader, and +point `includePaths` to the `src` directory, not to the document root: -Invariants are used to specify characteristics of a class that always must be true (except while executing a -protected or private member function). +```php +ContractApplication::getInstance()->init([ + 'debug' => $_SERVER['APP_DEBUG'] ?? false, + 'appDir' => dirname(__DIR__), + 'cacheDir' => dirname(__DIR__) . '/var/cache/contracts', + 'includePaths' => [dirname(__DIR__) . '/src'], +]); +``` -The invariant is a contract saying that the asserts must hold true. The invariant is checked when a class constructor - completes and at the end of the class public methods: +## Contracts -```php -balance > 0") - */ -class Account -{ +### Preconditions: `#[Verify]` - /** - * Current balance - * - * @var float - */ - protected $balance = 0.0; - - /** - * Deposits fixed amount of money to the account - * - * @param float $amount - */ - public function deposit($amount) - { - $this->balance += $amount; - } -} -``` -Invariants contain assert expressions, and so when they fail, they throw a ContractViolation exception. - -__NOTE__: The code in the invariant may not call any public non-static members of the class, either directly or -indirectly. Doing so will result in a stack overflow, as the invariant will wind up being called in an -infinitely recursive manner. - -Contract propagation ----------- - -There a some differences in inheritance of the contracts: - -1. Ensure - - if provided `Ensure` will automatically inherit all contracts from parent class or interface -2. Verify - - if provided `Verify` will _not_ inherit contracts from parent class or interface - - to inherit contracts you will need to provide `@inheritdoc` or the `Inherit` contract -3. Invariant - - if provided `Invariant` will inherit all contracts from parent class or interface -4. Inherit - - if provided `Inherit` will inherit all contracts from the given level (class, method) without the - need to provide a contract on your current class or method - -__Notes__: -- The parsing of a contract only happens __IF__ you provide any given annotation from this package. -Without it, your contracts won't work! -- The annotation __must not__ have curly braces (`{}`) otherwise the annotation reader can't find them. +A precondition is a requirement upon the caller. It is checked before the method body runs, so the body never sees +invalid arguments: ```php +use PhpDeal\Attribute\Verify; -class Foo extends FooParent +class Wallet { - /** - * @param int $amount - * @Contract\Verify("$amount != 1") - */ - public function bar($amount) + private const array SUPPORTED = ['EUR', 'USD']; + + private float $balance = 100.0; + + #[Verify('$amount > 0')] + #[Verify('$amount <= $this->balance')] + public function withdraw(float $amount): void { - ... + $this->balance -= $amount; } -} - -class FooParent -{ - /** - * @param int $amount - * @Contract\Verify("$amount != 2") - */ - public function bar($amount) + + #[Verify('\in_array($currency, self::SUPPORTED, true)')] + public static function convert(float $amount, string $currency = 'EUR'): float { - ... + return $amount; // static methods are supported as well } } - ``` -`Foo::bar` accepts `2` literal as a parameter and does not accept `1`. +The attribute is repeatable: every expression must hold. + +### Postconditions: `#[Ensure]` + +A postcondition is a promise of the method. It is checked after the method returns. Two extra variables are +available: -With @inheritdoc: +- `$__result` holds the value returned by the method; +- `$__old` is a clone of the object taken right before the call, to compare the state before and after. ```php +use PhpDeal\Attribute\Ensure; -class Foo extends FooParent +class Counter { - /** - * @param int $amount - * @Contract\Verify("$amount != 1") - * {@inheritdoc} - */ - public function bar($amount) + private int $value = 0; + + #[Ensure('$this->value === $__old->value + 1')] + public function increment(): void { - ... + ++$this->value; } -} - -class FooParent -{ - /** - * @param int $amount - * @Contract\Verify("$amount != 2") - */ - public function bar($amount) + + #[Ensure('$__result >= 0')] + public function getValue(): int { - ... + return $this->value; } } - ``` -`Foo::bar` does not accept `1` and `2` literals as a parameter. +The object is cloned only when a contract of the method mentions `$__old`, and only when the class can be cloned. +### Invariants: `#[Invariant]` -For postconditions (Ensure and Invariants contracts) subclasses inherit contracts and they don't need `@inheritdoc`. Example: +An invariant describes a property of the object that holds whenever it is observed from the outside. It is checked +after the constructor and after every public method: ```php - -/** - * @Contract\Invariant("$this->amount != 1") - */ -class Foo extends FooParent -{ - -} +use PhpDeal\Attribute\Invariant; -/** - * @Contract\Invariant("$this->amount != 2") - */ -class FooParent +#[Invariant('$this->speed >= 0')] +#[Invariant('$this->speed < 299_792_458')] // not faster than light +class Particle { - /** - * @var int - */ - protected $amount; - - /** - * @param int $amount - */ - protected function setBar($amount) + public function __construct(private float $speed = 0) {} + + public function accelerate(float $acceleration, float $time): void { - $this->amount = $amount; + $this->speed += $acceleration * $time; } } - ``` -`Foo::setBar` does not accept `1` and `2` literals as a parameter. +Invariants of parent classes and interfaces always apply. An invariant can call public methods of its own class +without checking the invariant again. + +### Inheritance: `#[Inherit]` -If you don't want to provide a contract on your curent method/class you can use the `Inherit` annotation: +Contracts follow the class hierarchy, so an implementation can not quietly break the promises of its interface: + +| Contract | Inherited from parent classes and interfaces | +|----------------|-----------------------------------------------------------------------------------------| +| `#[Ensure]` | Always, when the method declares a postcondition itself or uses `#[Inherit]` | +| `#[Invariant]` | Always, when the class declares an invariant itself or uses `#[Inherit]` | +| `#[Verify]` | Only on request: with `#[Inherit]`, or with an `{@inheritdoc}` tag in the doc comment | + +Preconditions are opt-in because a subclass may accept more than its parent (Liskov: *require no more, promise no +less*). + +Use `#[Inherit]` to take over the contracts of the parents without declaring any of your own. On a method it enables +the preconditions and postconditions of the same method in every parent class and interface. On a class it does the +same for every public method and enables the invariants of the parents: ```php -class Foo extends FooParent +use PhpDeal\Attribute\{Ensure, Inherit, Invariant, Verify}; + +#[Invariant('$this->getBalance() >= 0')] +interface AccountContract { - /** - * @param int $amount - * @Contract\Inherit - */ - public function bar($amount) - { - ... - } + #[Verify('$amount > 0')] + #[Ensure('$this->getBalance() === $__old->getBalance() + $amount')] + public function deposit(float $amount): void; + + public function getBalance(): float; } - -class FooParent + +#[Inherit] // every contract of AccountContract applies to this class +class Account implements AccountContract { - /** - * @param int $amount - * @Contract\Verify("$amount != 2") - */ - public function bar($amount) + private float $balance = 0.0; + + public function deposit(float $amount): void + { + $this->balance += $amount; + } + + public function getBalance(): float { - ... + return $this->balance; } } ``` -`Foo:bar()` does accept eveything, except: `2` +All the contracts that apply to a call must hold. A class without any contract attribute, and without +`#[Inherit]`, is not checked even if its interfaces declare contracts. + +## Writing expressions -Integration with assertion library ----------- +A contract is a PHP expression in a string. It must return `true` when the contract holds and `false` when it is +violated. Returning `null` is accepted too, for assertion helpers that return nothing. + +- **Scope.** The expression runs in the scope of the class that declares it, so it can read private and protected + members with `$this->`, `self::` and `static::`. Contracts of an interface run in the scope of the implementing + class. Static methods have no `$this`. +- **Names.** The expression is compiled outside of your file, so `use` imports do not apply: write class and function + names fully qualified, e.g. `'\App\Money::isValid($amount)'` or `'Assert\Assertion::email($email)'`. +- **Errors.** An error or exception thrown by the expression is reported as a violation of the contract, with the + original error as the previous exception. Assertion libraries can be used that way: -To enhance capabilities of contracts, it's possible to use [assertion library](https://github.com/beberlei/assert). ```php - /** - * Deposits fixed amount of money to the account - * - * @param float $amount - * - * @Contract\Ensure("Assert\Assertion::integer($this->balance)") - */ - public function deposit($amount) - { - $this->balance += $amount; - } +#[Verify('Assert\Assertion::between($percent, 0, 100)')] +public function setDiscount(int $percent): void {} ``` -[More assertions](https://github.com/beberlei/assert#list-of-assertions) +- **Mistakes in contracts.** A syntax error, a `$this` in a static method or a result that is neither a boolean nor + `null` throws an `InvalidContractException`: this is a bug in the contract itself, not a violation of it. -IDE Integration ---------------- -To improve your productivity with PhpStorm, you should definitely install a [Go! AOP Framework](https://plugins.jetbrains.com/plugin/7785) plugin (>=1.0.1) to have a PHP syntax highlighting for defining contracts and navigation to AOP advices. -PhpStorm example +## Handling violations +Every exception of PhpDeal implements `PhpDeal\Exception\ExceptionInterface`: -Common issues ------------ +``` +ExceptionInterface +โ”œโ”€โ”€ ContractViolation (LogicException) a contract does not hold +โ”‚ โ”œโ”€โ”€ PreconditionViolation #[Verify]: the caller passed invalid arguments +โ”‚ โ”œโ”€โ”€ PostconditionViolation #[Ensure]: the method did not keep its promise +โ”‚ โ””โ”€โ”€ InvariantViolation #[Invariant]: the object is in an invalid state +โ””โ”€โ”€ InvalidContractException (DomainException) the contract itself is broken +``` + +A violation tells exactly what went wrong and where. Its file and line point to the method that declares the contract: -##### Fatal error: Uncaught Error: Class 'Go\ParserReflection\Instrument\PathResolver' ```php -Fatal error: Uncaught Error: Class 'Go\ParserReflection\Instrument\PathResolver' -not found in .../vendor/goaop/parser-reflection/src/ReflectionEngine.php on line XXX +try { + $account->withdraw(70); +} catch (PreconditionViolation $violation) { + $violation->getMessage(); // Precondition "$amount > 0 && $amount <= 50" violated in Demo\Account->withdraw(70.0) + $violation->contract; // '$amount > 0 && $amount <= 50' + $violation->className; // 'Demo\Account' + $violation->methodName; // 'withdraw' + $violation->getPrevious(); // the assertion exception or error raised by the expression, if any +} ``` -This happens if your `appDir` configuration points at the same level as your `vendor` directory. -To solve this issue try adding your `vendor` folder into the `excludePaths` configuration. +Arguments in the message are rendered safely: long strings are truncated, and arrays and objects are reduced to their +size and class. + +## PHPStan integration + +Contract expressions are strings, so PHPStan can not see that a private property or method is used by a contract and +reports it as unused. PhpDeal ships a PHPStan extension that fixes this. With +[phpstan/extension-installer](https://github.com/phpstan/extension-installer) it is enabled automatically, otherwise +include it in your `phpstan.neon`: + +```neon +includes: + - vendor/php-deal/framework/extension.neon +``` + +## Production + +Contracts are a development and testing tool: every checked call costs an expression evaluation. The usual setup is +to initialize `ContractApplication` only in development and test environments: ```php -ContractApplication::getInstance()->init(array( - 'debug' => true, - 'appDir' => __DIR__,, - 'excludePaths' => [ - __DIR__ . '/vendor' - ], - 'cacheDir' => __DIR__.'/cache/', -)); +if (($_SERVER['APP_ENV'] ?? 'prod') !== 'prod') { + ContractApplication::getInstance()->init([/* ... */]); +} +``` + +Without the kernel the attributes are plain metadata, and your classes run untouched. If you keep contracts in +production, set `'debug' => false` and warm up the cache at deploy time, see the +[Go! AOP deployment guide](https://github.com/goaop/framework/blob/master/docs/configuration.md). + +## Upgrading from 1.x + +PhpDeal 2 replaces Doctrine annotations with native attributes. In short: + +```diff +-use PhpDeal\Annotation as Contract; ++use PhpDeal\Attribute as Contract; + +-/** +- * @Contract\Verify("$amount > 0 && is_numeric($amount)") +- * @Contract\Ensure("$this->balance == $__old->balance + $amount") +- */ ++#[Contract\Verify('$amount > 0 && is_numeric($amount)')] ++#[Contract\Ensure('$this->balance == $__old->balance + $amount')] + public function deposit($amount) ``` + +See [UPGRADE-2.0.md](UPGRADE-2.0.md) for every change, and the [CHANGELOG](CHANGELOG.md) for the new features. + +## Demo + +A small runnable example lives in [`demo/`](demo): + +```bash +composer demo +``` + +## Contributing + +Pull requests are welcome! Run `composer test` before submitting: it checks the coding style, runs PHPStan at +level 10 and the test suite. See [CONTRIBUTING.md](CONTRIBUTING.md) for details. + +## License + +PhpDeal is open-source software licensed under the [MIT license](LICENSE). diff --git a/UPGRADE-2.0.md b/UPGRADE-2.0.md new file mode 100644 index 0000000..35d9751 --- /dev/null +++ b/UPGRADE-2.0.md @@ -0,0 +1,101 @@ +Upgrading from 1.x to 2.0 +========================= + +PhpDeal 2.0 moves to native PHP attributes and Go! AOP 4. Most applications only need the steps of the +quick checklist. + +Quick checklist +--------------- + +1. Run on PHP 8.4 or newer, require `php-deal/framework:^2.0` and update the dependencies. +2. Replace the annotations with attributes (see below). `doctrine/annotations` is not used any more. +3. Delete the old cache directory: the Go! AOP 4 cache format is different. +4. If you catch `DomainException` for broken contracts, catch `PhpDeal\Exception\InvalidContractException` instead. + +Requirements +------------ + +| 1.x | 2.0 | +|-----------------------------|-------------------------| +| PHP 7.1 โ€“ 7.4 | PHP 8.4+ | +| goaop/framework ^2.3 | goaop/framework ^4.0 | +| doctrine/annotations | native attributes | + +Annotations become attributes +----------------------------- + +The `PhpDeal\Annotation` namespace is replaced by `PhpDeal\Attribute`. Every contract is a single-quoted string +argument, so `$variables` need no escaping: + +```diff +-use PhpDeal\Annotation as Contract; ++use PhpDeal\Attribute as Contract; + +-/** +- * @Contract\Invariant("$this->balance >= 0") +- */ ++#[Contract\Invariant('$this->balance >= 0')] + class Account + { +- /** +- * @Contract\Verify("$amount > 0") +- * @Contract\Ensure("$this->balance == $__old->balance + $amount") +- */ ++ #[Contract\Verify('$amount > 0')] ++ #[Contract\Ensure('$this->balance == $__old->balance + $amount')] + public function deposit(float $amount): void {} + +- /** +- * @Contract\Inherit +- */ ++ #[Contract\Inherit] + public function withdraw(float $amount): void {} + } +``` + +The old restriction on curly braces in annotations is gone: an attribute argument can contain any PHP expression. + +The attribute classes are `final readonly` and expose the expression as `$expression` (it was `$value`). +`__toString()` is removed. + +Kernel +------ + +`ContractApplication` is initialized as before. To combine contracts with your own aspects, call +`ContractApplication::registerAspects($container)` from `configureAop()` of your own Go! AOP kernel instead of +extending `ContractApplication`. + +The aspects are now `final readonly` services built from `ContractFetcher` and `ContractEvaluator`, and are +registered lazily. `AbstractContractAspect`, `InheritCheckerAspect` and the classes of +`PhpDeal\Contract\Fetcher\Parent` are removed: their behaviour lives in `PhpDeal\Contract\ContractFetcher`. + +Behaviour changes +----------------- + +- **Dedicated exceptions.** Violations are reported with `PreconditionViolation`, `PostconditionViolation` and + `InvariantViolation`. All of them extend `ContractViolation`, so existing `catch (ContractViolation $e)` blocks keep + working. The message format changed, e.g. `Precondition "$amount > 0" violated in App\Account->deposit(-1.0)`. +- **Broken contracts.** A contract with a syntax error, a contract that returns something else than a boolean or + `null`, and a contract that uses `$this` in a static method throw `InvalidContractException` (a + `DomainException`). In 1.x such problems were wrapped into a `ContractViolation`. +- **`#[Inherit]` checks preconditions first.** Inherited preconditions are checked before the method body runs; 1.x + ran the body first and checked every inherited contract afterwards. +- **`#[Inherit]` on a class** now also inherits the preconditions and postconditions of every public method, as the + documentation always described; 1.x inherited the invariants only. +- **Scope of parent contracts.** A contract declared on a parent class is evaluated in the scope of that class, so it + can read the private state of the parent. Contracts of interfaces are evaluated in the scope of the implementing + class, as before. +- **Invariants of the object.** The invariants of the runtime class of the object are checked, together with those of + its parents and interfaces, also for methods inherited from a parent. +- **No recursion in invariants.** An invariant may call public methods of its own class; contracts of calls made while + a contract is evaluated are not checked. +- **`$__old` is cloned on demand.** The object is cloned only for postconditions that use `$__old`, so `__clone()` is + no longer called for every call of a method with a postcondition. +- **Arguments.** Variadic parameters are available as a list of values. Arguments are rendered safely in messages: + arrays and objects no longer break the message (1.x used `implode()`). + +Tooling +------- + +The development tools moved to PHPUnit 13, PHPStan 2 (level 10) and PHP-CS-Fixer (PER-CS 2.0); Travis CI and +Scrutinizer are replaced by GitHub Actions. The package ships a PHPStan extension (see the README). diff --git a/composer.json b/composer.json index e757cd2..49a80cf 100644 --- a/composer.json +++ b/composer.json @@ -1,19 +1,18 @@ { "name": "php-deal/framework", - "description": "Design by Contract framework for PHP", - "require": { - "php": "~7.1", - "goaop/framework": "^2.3" - }, - "require-dev": { - "beberlei/assert": "~3.0", - "phpstan/phpstan": "^0.12.88", - "phpunit/phpunit": "^7.5", - "roave/security-advisories": "dev-master", - "slevomat/coding-standard": "^6.1", - "squizlabs/php_codesniffer": "^3.4", - "symfony/console": "~3.0|~4.0" - }, + "description": "Design by Contract framework for PHP: preconditions, postconditions and invariants declared with native attributes", + "type": "library", + "keywords": [ + "dbc", + "design-by-contract", + "contract", + "precondition", + "postcondition", + "invariant", + "attributes", + "aop", + "goaop" + ], "license": "MIT", "authors": [ { @@ -29,34 +28,68 @@ "email": "blubb0r05+github@gmail.com" } ], + "require": { + "php": "^8.4", + "goaop/framework": "^4.0" + }, + "require-dev": { + "beberlei/assert": "^3.3.3", + "friendsofphp/php-cs-fixer": "^3.95", + "phpstan/extension-installer": "^1.4", + "phpstan/phpstan": "^2.3", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^13.0" + }, + "suggest": { + "beberlei/assert": "Thin assertion library that can be used inside contract expressions" + }, "autoload": { "psr-4": { "PhpDeal\\": "src/" } }, "autoload-dev": { - "psr-0": { - "Demo\\": "demo/" - }, "psr-4": { - "PhpDeal\\": "tests/" + "Demo\\": "demo/", + "PhpDeal\\Tests\\": "tests/" } }, "scripts": { - "phpstan": "phpstan analyze", - "phpcs": "phpcs src tests -sp --colors", - "phpunit": "phpunit --verbose --colors=always", + "cs": "php-cs-fixer check --diff", + "cs:fix": "php-cs-fixer fix", + "phpstan": "phpstan analyse --memory-limit=1G", + "phpunit": "phpunit", + "demo": "php demo/run.php", "test": [ + "@cs", "@phpstan", - "@phpcs", "@phpunit" ] }, + "scripts-descriptions": { + "cs": "Check the coding style", + "cs:fix": "Fix the coding style", + "phpstan": "Run static analysis (PHPStan level 10)", + "phpunit": "Run the test suite", + "demo": "Run the demo application", + "test": "Run every quality check" + }, "config": { - "sort-packages": true + "sort-packages": true, + "allow-plugins": { + "phpstan/extension-installer": true + } }, - "suggest": { - "beberlei/assert": "Thin assertion library for input validation in business models. Used for tests." + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + }, + "phpstan": { + "includes": [ + "extension.neon" + ] + } }, "support": { "issues": "https://github.com/php-deal/framework/issues", diff --git a/demo/Account.php b/demo/Account.php new file mode 100644 index 0000000..93c61c9 --- /dev/null +++ b/demo/Account.php @@ -0,0 +1,42 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace Demo; + +use PhpDeal\Attribute\Ensure; +use PhpDeal\Attribute\Inherit; + +/** + * Simple trade account: `#[Inherit]` enables every contract of {@see AccountContract} + */ +#[Inherit] +class Account implements AccountContract +{ + private float $balance = 0.0; + + public function deposit(float $amount): void + { + $this->balance += $amount; + } + + public function withdraw(float $amount): void + { + $this->balance -= $amount; + } + + #[Ensure('$__result === $this->balance')] + public function getBalance(): float + { + return $this->balance; + } +} diff --git a/demo/AccountContract.php b/demo/AccountContract.php new file mode 100644 index 0000000..3f7802c --- /dev/null +++ b/demo/AccountContract.php @@ -0,0 +1,45 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace Demo; + +use PhpDeal\Attribute\Ensure; +use PhpDeal\Attribute\Invariant; +use PhpDeal\Attribute\Verify; + +/** + * Contract of a simple trade account: every implementation must honour it + */ +#[Invariant('$this->getBalance() >= 0')] +interface AccountContract +{ + /** + * Deposits a positive amount of money to the account + */ + #[Verify('$amount > 0')] + #[Ensure('$this->getBalance() === $__old->getBalance() + $amount')] + public function deposit(float $amount): void; + + /** + * Withdraws money from the account, at most 50 at once and never more than the balance + */ + #[Verify('$amount > 0 && $amount <= 50')] + #[Verify('$amount <= $this->getBalance()')] + #[Ensure('$this->getBalance() === $__old->getBalance() - $amount')] + public function withdraw(float $amount): void; + + /** + * Returns the current balance + */ + public function getBalance(): float; +} diff --git a/demo/README.md b/demo/README.md deleted file mode 100644 index 45cc643..0000000 --- a/demo/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# simple example - -composer require php-deal/framewor - -php src/demo.php - -To make the contract fail simply -change 50 to 200 in demo.php. diff --git a/demo/composer.json b/demo/composer.json deleted file mode 100644 index c417a32..0000000 --- a/demo/composer.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "phpdeal/framework", - "require": { - "php-deal/framework": "^1.0" - }, - "autoload": { - "psr-4": { - "Demo\\":"src/Demo" - } - } -} diff --git a/demo/run.php b/demo/run.php new file mode 100644 index 0000000..3383ebb --- /dev/null +++ b/demo/run.php @@ -0,0 +1,43 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +use Demo\Account; +use PhpDeal\ContractApplication; +use PhpDeal\Exception\ContractViolation; + +require \dirname(__DIR__) . '/vendor/autoload.php'; + +ContractApplication::getInstance()->init([ + 'debug' => true, + 'appDir' => \dirname(__DIR__), + 'cacheDir' => __DIR__ . '/cache', + 'includePaths' => [__DIR__], + 'excludePaths' => [__DIR__ . '/cache'], +]); + +$account = new Account(); + +echo 'Deposit 200', \PHP_EOL; +$account->deposit(200); +echo 'Withdraw 50', \PHP_EOL; +$account->withdraw(50); +echo 'Balance: ', $account->getBalance(), \PHP_EOL, \PHP_EOL; + +echo 'Withdraw 70, but the contract allows at most 50 at once...', \PHP_EOL; +try { + $account->withdraw(70); +} catch (ContractViolation $violation) { + echo \get_class($violation), ': ', $violation->getMessage(), \PHP_EOL; + echo ' declared at ', $violation->getFile(), ':', $violation->getLine(), \PHP_EOL; +} +echo 'Balance is still: ', $account->getBalance(), \PHP_EOL; diff --git a/demo/src/Demo/Account.php b/demo/src/Demo/Account.php deleted file mode 100644 index bd1a6e8..0000000 --- a/demo/src/Demo/Account.php +++ /dev/null @@ -1,64 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Demo; - -use PhpDeal\Annotation as Contract; - -/** - * Simple trade account class - * @Contract\Invariant("$this->balance >= 0") - */ -class Account implements AccountContractInterface -{ - - /** - * Current balance - * - * @var float - */ - protected $balance = 0.0; - - /** - * Deposits fixed amount of money to the account - * - * @param float $amount - * - * @Contract\Verify("$amount>0 && is_numeric($amount)") - * @Contract\Ensure("$this->balance == $__old->balance+$amount") - */ - public function deposit($amount) - { - $this->balance += $amount; - } - - /** - * @Contract\Inherit() - * @param float $amount - */ - public function withdraw($amount) - { - $this->balance -= $amount; - } - - /** - * Returns current balance - * - * @Contract\Ensure("$__result == $this->balance") - * - * @return float - */ - public function getBalance() - { - return $this->balance; - } -} diff --git a/demo/src/Demo/AccountContractInterface.php b/demo/src/Demo/AccountContractInterface.php deleted file mode 100644 index db9d0fc..0000000 --- a/demo/src/Demo/AccountContractInterface.php +++ /dev/null @@ -1,51 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Demo; - -use PhpDeal\Annotation as Contract; - -/** - * Simple trade account contract - */ -interface AccountContractInterface -{ - /** - * Deposits fixed amount of money to the account - * - * @param float $amount - * - * @Contract\Verify("$amount>0 && is_numeric($amount)") - * @Contract\Ensure("$this->balance == $__old->balance+$amount") - */ - public function deposit($amount); - - /** - * Withdraw amount of money from account. - * - * We don't allow withdrawal of more than 50 - * @Contract\Verify("$amount <= $this->balance") - * @Contract\Verify("$amount <= 50") - * @Contract\Ensure("$this->balance == $__old->balance-$amount") - * @param float $amount - */ - public function withdraw($amount); - - /** - * Returns current balance - * - * @Contract\Ensure("$__result == $this->balance") - * - * @return float - */ - public function getBalance(); -} diff --git a/demo/src/aspect_bootstrap.php b/demo/src/aspect_bootstrap.php deleted file mode 100644 index 10ebd1d..0000000 --- a/demo/src/aspect_bootstrap.php +++ /dev/null @@ -1,19 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -use PhpDeal\ContractApplication; - -ContractApplication::getInstance()->init(array( - 'debug' => true, - 'appDir' => __DIR__, - 'cacheDir' => __DIR__.'/../cache/', -)); diff --git a/demo/src/demo.php b/demo/src/demo.php deleted file mode 100644 index 437910b..0000000 --- a/demo/src/demo.php +++ /dev/null @@ -1,30 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -include __DIR__.'/../vendor/autoload.php'; - -include_once __DIR__.'/aspect_bootstrap.php'; - -$account = new Demo\Account(); - -echo 'Deposit: 200' . PHP_EOL; -$account->deposit(200); -echo 'Current balance: ' . $account->getBalance(); -echo PHP_EOL; -echo 'Withdraw: 50' . PHP_EOL; -$account->withdraw(50); -echo 'Current balance: ' . $account->getBalance(), PHP_EOL; - -echo 'current contract allows withdrawing amount less than 50' . PHP_EOL; - -echo 'trying withdrawing 70 should fail' . PHP_EOL; -$account->withdraw(70); diff --git a/extension.neon b/extension.neon new file mode 100644 index 0000000..b1cfa3f --- /dev/null +++ b/extension.neon @@ -0,0 +1,9 @@ +# PHPStan extension of php-deal/framework, registered automatically by phpstan/extension-installer. +# Without the installer, add it to the "includes" section of your phpstan.neon: +# - vendor/php-deal/framework/extension.neon +services: + - + class: PhpDeal\PHPStan\ContractUsageExtension + tags: + - phpstan.properties.readWriteExtension + - phpstan.methods.alwaysUsedMethodExtension diff --git a/phpcs.xml.dist b/phpcs.xml.dist deleted file mode 100644 index f5db631..0000000 --- a/phpcs.xml.dist +++ /dev/null @@ -1,11 +0,0 @@ - - - PSR-12 with native function invocation - - - - */cache - - - - diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 3c2c552..d88373e 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -1,7 +1,17 @@ +includes: + - extension.neon + parameters: - excludes_analyse: - - %rootDir%/../../../tests/cache - level: max + level: 10 + phpVersion: + min: 80400 + max: 80599 paths: - - src/ - - tests/ + - src + - tests + - demo + excludePaths: + - tests/cache (?) + - demo/cache (?) + tmpDir: .phpstan.cache + treatPhpDocTypesAsCertain: false diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 8a8605d..840e4a0 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,35 +1,32 @@ - - - - - - - + executionOrder="defects" + beStrictAboutOutputDuringTests="true" + displayDetailsOnPhpunitDeprecations="true" + displayDetailsOnTestsThatTriggerDeprecations="true" + displayDetailsOnTestsThatTriggerErrors="true" + displayDetailsOnTestsThatTriggerNotices="true" + displayDetailsOnTestsThatTriggerWarnings="true" + failOnDeprecation="true" + failOnNotice="true" + failOnWarning="true" + failOnRisky="true"> - - ./tests/ + + tests/Unit + + + tests/Functional - - - ./src/ - - - - - - performance - - + + + src + + diff --git a/src/Annotation/Ensure.php b/src/Annotation/Ensure.php deleted file mode 100644 index 2fb24ab..0000000 --- a/src/Annotation/Ensure.php +++ /dev/null @@ -1,30 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Annotation; - -use Doctrine\Common\Annotations\Annotation as BaseAnnotation; - -/** - * This annotation defines a Post-condition check, applied to the method - * - * @Annotation - * @Target("METHOD") - */ -class Ensure extends BaseAnnotation -{ - public function __toString(): string - { - return $this->value; - } -} diff --git a/src/Annotation/Inherit.php b/src/Annotation/Inherit.php deleted file mode 100644 index 002afa0..0000000 --- a/src/Annotation/Inherit.php +++ /dev/null @@ -1,28 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -namespace PhpDeal\Annotation; - -use Doctrine\Common\Annotations\Annotation as BaseAnnotation; - -/** - * This annotation defines a contract inheritance check, applied to the method or class - * - * @Annotation - * @Target({"METHOD", "CLASS"}) - */ -class Inherit extends BaseAnnotation -{ - public function __toString() - { - return $this->value; - } -} diff --git a/src/Annotation/Invariant.php b/src/Annotation/Invariant.php deleted file mode 100644 index 6533bf3..0000000 --- a/src/Annotation/Invariant.php +++ /dev/null @@ -1,30 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Annotation; - -use Doctrine\Common\Annotations\Annotation as BaseAnnotation; - -/** - * This annotation defines an Invariant check - * - * @Annotation - * @Target("CLASS") - */ -class Invariant extends BaseAnnotation -{ - public function __toString(): string - { - return $this->value; - } -} diff --git a/src/Annotation/Verify.php b/src/Annotation/Verify.php deleted file mode 100644 index ad49566..0000000 --- a/src/Annotation/Verify.php +++ /dev/null @@ -1,30 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Annotation; - -use Doctrine\Common\Annotations\Annotation as BaseAnnotation; - -/** - * This annotation defines a Pre-condition check, applied to the method - * - * @Annotation - * @Target("METHOD") - */ -class Verify extends BaseAnnotation -{ - public function __toString() - { - return $this->value; - } -} diff --git a/src/Aspect/AbstractContractAspect.php b/src/Aspect/AbstractContractAspect.php deleted file mode 100644 index 89f466e..0000000 --- a/src/Aspect/AbstractContractAspect.php +++ /dev/null @@ -1,119 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Aspect; - -use Doctrine\Common\Annotations\Annotation; -use Doctrine\Common\Annotations\Reader; -use DomainException; -use Go\Aop\Intercept\MethodInvocation; -use PhpDeal\Exception\ContractViolation; - -abstract class AbstractContractAspect -{ - /** - * @var Reader - */ - protected $reader; - - /** - * @param Reader $reader Annotation reader - */ - public function __construct(Reader $reader) - { - $this->reader = $reader; - } - - /** - * Returns an associative list of arguments for the method invocation - * - * @param MethodInvocation $invocation - * @return array - * @throws \ReflectionException - */ - protected function fetchMethodArguments(MethodInvocation $invocation): array - { - $result = []; - $parameters = $invocation->getMethod()->getParameters(); - $argumentValues = $invocation->getArguments(); - - // Number of arguments can be less than number of parameters because of default values - foreach ($parameters as $parameterIndex => $reflectionParameter) { - $hasArgumentValue = \array_key_exists($parameterIndex, $argumentValues); - $argumentValue = $hasArgumentValue ? $argumentValues[$parameterIndex] : null; - if (!$hasArgumentValue && $reflectionParameter->isDefaultValueAvailable()) { - $argumentValue = $reflectionParameter->getDefaultValue(); - } - $result[$reflectionParameter->name] = $argumentValue; - } - - return $result; - } - - /** - * Performs verification of contracts for given invocation - * - * @param MethodInvocation $invocation Current invocation - * @param array|Annotation[] $contracts Contract annotation - * @param object|string $instance Invocation instance or string for static class - * @param string $scope Scope of method - * @param array $args List of arguments for the method - * - * @throws DomainException - * @throws ContractViolation - */ - protected function ensureContracts( - MethodInvocation $invocation, - array $contracts, - $instance, - string $scope, - array $args - ): void { - static $invoker = null; - if (!$invoker) { - $invoker = function () { - $args = \func_get_arg(0); - \extract($args, EXTR_OVERWRITE); - - return eval('return ' . \func_get_arg(1) . '; ?>'); - }; - } - - $instance = \is_object($instance) ? $instance : null; - $boundInvoker = $invoker->bindTo($instance, $scope); - - foreach ($contracts as $contract) { - $contractExpression = $contract->value; - try { - $invocationResult = $boundInvoker->__invoke($args, $contractExpression); - - if ($invocationResult === false) { - throw new ContractViolation($invocation, $contractExpression); - } - - // we accept as a result only true or null - // null may be a result of assertions from beberlei/assert which passed - if ($invocationResult !== null && $invocationResult !== true) { - $errorMessage = 'Invalid return value received from the assertion body,' - . ' only boolean or void can be returned'; - throw new DomainException($errorMessage); - } - } catch (\Error $internalError) { - // PHP-7 friendly interceptor for fatal errors - throw new ContractViolation($invocation, $contractExpression, $internalError); - } catch (\Exception $internalException) { - throw new ContractViolation($invocation, $contractExpression, $internalException); - } - } - } -} diff --git a/src/Aspect/InheritCheckerAspect.php b/src/Aspect/InheritCheckerAspect.php deleted file mode 100644 index 7508363..0000000 --- a/src/Aspect/InheritCheckerAspect.php +++ /dev/null @@ -1,142 +0,0 @@ -methodConditionFetcher = new MethodConditionFetcher([ - Ensure::class, - Verify::class, - Invariant::class - ], $reader); - $this->invariantFetcher = new InvariantFetcher([Invariant::class], $reader); - } - - /** - * Verifies inherit contracts for the method - * - * @Around("@execution(PhpDeal\Annotation\Inherit)") - * @param MethodInvocation $invocation - * - * @throws ContractViolation - * @throws \ReflectionException - * @return mixed - */ - public function inheritMethodContracts(MethodInvocation $invocation) - { - $object = $invocation->getThis(); - $args = $this->fetchMethodArguments($invocation); - $class = $invocation->getMethod()->getDeclaringClass(); - if (\is_object($object) && $class->isCloneable()) { - $args['__old'] = clone $object; - } - - $result = $invocation->proceed(); - $args['__result'] = $result; - $allContracts = $this->fetchMethodContracts($invocation); - - $this->ensureContracts($invocation, $allContracts, $object, $class->name, $args); - - return $result; - } - - /** - * @Around("@within(PhpDeal\Annotation\Inherit) && execution(public **->*(*))") - * @param MethodInvocation $invocation - * @return mixed - * @throws \ReflectionException - */ - public function inheritClassContracts(MethodInvocation $invocation) - { - $object = $invocation->getThis(); - $args = $this->fetchMethodArguments($invocation); - $class = $invocation->getMethod()->getDeclaringClass(); - if (\is_object($object) && $class->isCloneable()) { - $args['__old'] = clone $object; - } - - $result = $invocation->proceed(); - $args['__result'] = $result; - - $allContracts = $this->fetchClassContracts($class); - $this->ensureContracts($invocation, $allContracts, $object, $class->name, $args); - - return $result; - } - - /** - * @param MethodInvocation $invocation - * @return array - * @throws \ReflectionException - */ - private function fetchMethodContracts(MethodInvocation $invocation): array - { - $allContracts = $this->fetchParentsMethodContracts($invocation); - /** @var ReflectionMethod&AnnotatedReflectionMethod $reflectionMethod */ - $reflectionMethod = $invocation->getMethod(); - - foreach ($reflectionMethod->getAnnotations() as $annotation) { - $annotationClass = \get_class($annotation); - - if (\in_array($annotationClass, [Ensure::class, Verify::class, Invariant::class], true)) { - $allContracts[] = $annotation; - } - } - - return \array_unique($allContracts); - } - - /** - * @param MethodInvocation $invocation - * @return array - * @throws \ReflectionException - */ - private function fetchParentsMethodContracts(MethodInvocation $invocation): array - { - return $this->methodConditionFetcher->getConditions( - $invocation->getMethod()->getDeclaringClass(), - $invocation->getMethod()->name - ); - } - - /** - * @param ReflectionClass $class - * @return array - */ - private function fetchClassContracts(ReflectionClass $class): array - { - $allContracts = $this->invariantFetcher->getConditions($class); - foreach ($this->reader->getClassAnnotations($class) as $annotation) { - if ($annotation instanceof Invariant) { - $allContracts[] = $annotation; - } - } - - return \array_unique($allContracts); - } -} diff --git a/src/Aspect/InvariantCheckerAspect.php b/src/Aspect/InvariantCheckerAspect.php index a5a0c12..a01e4c6 100644 --- a/src/Aspect/InvariantCheckerAspect.php +++ b/src/Aspect/InvariantCheckerAspect.php @@ -3,7 +3,7 @@ /** * PHP Deal framework * - * @copyright Copyright 2019, Lisachenko Alexander + * @copyright Copyright 2014-2026, Lisachenko Alexander * * This source file is subject to the license that is bundled * with this source code in the file LICENSE. @@ -13,69 +13,50 @@ namespace PhpDeal\Aspect; -use Doctrine\Common\Annotations\Reader; use Go\Aop\Aspect; use Go\Aop\Intercept\MethodInvocation; -use PhpDeal\Annotation\Invariant; -use PhpDeal\Contract\Fetcher\Parent\InvariantFetcher; -use PhpDeal\Exception\ContractViolation; -use Go\Lang\Annotation\Around; -use ReflectionClass; +use Go\Lang\Attribute\Around; +use PhpDeal\Contract\ContractEvaluator; +use PhpDeal\Contract\ContractFetcher; +use PhpDeal\Contract\ContractKind; +use PhpDeal\Exception\InvariantViolation; +use ReflectionObject; -class InvariantCheckerAspect extends AbstractContractAspect implements Aspect +/** + * Checks `#[Invariant]` class invariants after the constructor and after every public method + * + * The invariants of the object's own class, its parent classes and its interfaces are checked. + */ +final readonly class InvariantCheckerAspect implements Aspect { - /** - * @var InvariantFetcher - */ - private $invariantFetcher; - - public function __construct(Reader $reader) - { - parent::__construct($reader); - $this->invariantFetcher = new InvariantFetcher([Invariant::class], $reader); - } + public function __construct( + private ContractFetcher $fetcher, + private ContractEvaluator $evaluator, + ) {} /** - * Verifies invariants for contract class - * - * @Around("@within(PhpDeal\Annotation\Invariant) && execution(public **->*(*))") - * @param MethodInvocation $invocation - * - * @throws ContractViolation - * @throws \ReflectionException - * @return mixed + * @throws InvariantViolation */ - public function invariantContract(MethodInvocation $invocation) + #[Around( + '(@within(PhpDeal\Attribute\Invariant) || @within(PhpDeal\Attribute\Inherit))' + . ' && execution(public **->*(*))', + )] + public function checkInvariants(MethodInvocation $invocation): mixed { - $object = $invocation->getThis(); - $args = $this->fetchMethodArguments($invocation); - $class = $invocation->getMethod()->getDeclaringClass(); - if (\is_object($object) && $class->isCloneable()) { - $args['__old'] = clone $object; + $result = $invocation->proceed(); + $instance = $invocation->getThis(); + if ($instance === null || $this->evaluator->isEvaluating()) { + return $result; + } + $contracts = $this->fetcher->getInvariants(new ReflectionObject($instance)); + if ($contracts === []) { + return $result; } - $result = $invocation->proceed(); - $args['__result'] = $result; - - $allContracts = $this->fetchAllContracts($class); - $this->ensureContracts($invocation, $allContracts, $object, $class->name, $args); + $variables = $this->evaluator->getArguments($invocation); + $variables['__result'] = $result; + $this->evaluator->check($invocation, $contracts, $variables, ContractKind::Invariant); return $result; } - - /** - * @param ReflectionClass $class - * @return array - */ - private function fetchAllContracts(ReflectionClass $class): array - { - $allContracts = $this->invariantFetcher->getConditions($class); - foreach ($this->reader->getClassAnnotations($class) as $annotation) { - if ($annotation instanceof Invariant) { - $allContracts[] = $annotation; - } - } - - return \array_unique($allContracts); - } } diff --git a/src/Aspect/PostconditionCheckerAspect.php b/src/Aspect/PostconditionCheckerAspect.php index b605264..9eb2f72 100644 --- a/src/Aspect/PostconditionCheckerAspect.php +++ b/src/Aspect/PostconditionCheckerAspect.php @@ -3,7 +3,7 @@ /** * PHP Deal framework * - * @copyright Copyright 2019, Lisachenko Alexander + * @copyright Copyright 2014-2026, Lisachenko Alexander * * This source file is subject to the license that is bundled * with this source code in the file LICENSE. @@ -13,87 +13,71 @@ namespace PhpDeal\Aspect; -use Doctrine\Common\Annotations\Reader; use Go\Aop\Aspect; use Go\Aop\Intercept\MethodInvocation; -use Go\Aop\Support\AnnotatedReflectionMethod; -use PhpDeal\Annotation\Ensure; -use PhpDeal\Contract\Fetcher\Parent\MethodConditionFetcher; -use PhpDeal\Exception\ContractViolation; -use Go\Lang\Annotation\Around; -use ReflectionMethod; +use Go\Lang\Attribute\Around; +use PhpDeal\Contract\BoundContract; +use PhpDeal\Contract\ContractEvaluator; +use PhpDeal\Contract\ContractFetcher; +use PhpDeal\Contract\ContractKind; +use PhpDeal\Exception\PostconditionViolation; +use ReflectionObject; -class PostconditionCheckerAspect extends AbstractContractAspect implements Aspect +/** + * Checks `#[Ensure]` post-conditions after the method body has returned + * + * Expressions can use `$__result` (the return value) and `$__old` (a clone of the object taken before the call). + */ +final readonly class PostconditionCheckerAspect implements Aspect { - /** - * @var MethodConditionFetcher - */ - private $methodConditionFetcher; - - public function __construct(Reader $reader) - { - parent::__construct($reader); - $this->methodConditionFetcher = new MethodConditionFetcher([Ensure::class], $reader); - } + public function __construct( + private ContractFetcher $fetcher, + private ContractEvaluator $evaluator, + ) {} /** - * Verifies post-condition contract for the method - * - * @Around("@execution(PhpDeal\Annotation\Ensure)") - * @param MethodInvocation $invocation - * - * @throws ContractViolation - * @throws \ReflectionException - * @return mixed + * @throws PostconditionViolation */ - public function postConditionContract(MethodInvocation $invocation) + #[Around( + '@execution(PhpDeal\Attribute\Ensure)' + . ' || @execution(PhpDeal\Attribute\Inherit)' + . ' || (@within(PhpDeal\Attribute\Inherit) && (execution(public **->*(*)) || execution(public **::*(*))))', + )] + public function checkPostconditions(MethodInvocation $invocation): mixed { - $object = $invocation->getThis(); - $args = $this->fetchMethodArguments($invocation); - $class = $invocation->getMethod()->getDeclaringClass(); - if (\is_object($object) && $class->isCloneable()) { - $args['__old'] = clone $object; + if ($this->evaluator->isEvaluating()) { + return $invocation->proceed(); + } + $contracts = $this->fetcher->getPostconditions($invocation->getMethod()); + if ($contracts === []) { + return $invocation->proceed(); } - $result = $invocation->proceed(); - $args['__result'] = $result; - $allContracts = $this->fetchAllContracts($invocation); + $variables = $this->evaluator->getArguments($invocation); + $instance = $invocation->getThis(); + // Cloning is skipped when no contract needs the previous state + if ($instance !== null && self::usesOldState($contracts) && new ReflectionObject($instance)->isCloneable()) { + $variables['__old'] = clone $instance; + } - $this->ensureContracts($invocation, $allContracts, $object, $class->name, $args); + $result = $invocation->proceed(); + $variables['__result'] = $result; + $this->evaluator->check($invocation, $contracts, $variables, ContractKind::Postcondition); return $result; } /** - * @param MethodInvocation $invocation - * @return array - * @throws \ReflectionException + * @param list $contracts */ - private function fetchAllContracts(MethodInvocation $invocation): array + private static function usesOldState(array $contracts): bool { - $allContracts = $this->fetchParentsContracts($invocation); - /** @var ReflectionMethod&AnnotatedReflectionMethod $reflectionMethod */ - $reflectionMethod = $invocation->getMethod(); - - foreach ($reflectionMethod->getAnnotations() as $annotation) { - if ($annotation instanceof Ensure) { - $allContracts[] = $annotation; + foreach ($contracts as $boundContract) { + if (\str_contains($boundContract->contract->expression, '$__old')) { + return true; } } - return \array_unique($allContracts); - } - - /** - * @param MethodInvocation $invocation - * @return array - * @throws \ReflectionException - */ - private function fetchParentsContracts(MethodInvocation $invocation): array - { - return $this->methodConditionFetcher->getConditions( - $invocation->getMethod()->getDeclaringClass(), - $invocation->getMethod()->name - ); + return false; } } diff --git a/src/Aspect/PreconditionCheckerAspect.php b/src/Aspect/PreconditionCheckerAspect.php index dff94dc..ba233b3 100644 --- a/src/Aspect/PreconditionCheckerAspect.php +++ b/src/Aspect/PreconditionCheckerAspect.php @@ -3,7 +3,7 @@ /** * PHP Deal framework * - * @copyright Copyright 2019, Lisachenko Alexander + * @copyright Copyright 2014-2026, Lisachenko Alexander * * This source file is subject to the license that is bundled * with this source code in the file LICENSE. @@ -13,79 +13,43 @@ namespace PhpDeal\Aspect; -use Doctrine\Common\Annotations\Reader; use Go\Aop\Aspect; use Go\Aop\Intercept\MethodInvocation; -use Go\Aop\Support\AnnotatedReflectionMethod; -use PhpDeal\Annotation\Verify; -use PhpDeal\Contract\Fetcher\Parent\MethodConditionWithInheritDocFetcher; -use PhpDeal\Exception\ContractViolation; -use Go\Lang\Annotation\Before; -use ReflectionException; -use ReflectionMethod; +use Go\Lang\Attribute\Before; +use PhpDeal\Contract\ContractEvaluator; +use PhpDeal\Contract\ContractFetcher; +use PhpDeal\Contract\ContractKind; +use PhpDeal\Exception\PreconditionViolation; -class PreconditionCheckerAspect extends AbstractContractAspect implements Aspect +/** + * Checks `#[Verify]` pre-conditions before the method body runs + */ +final readonly class PreconditionCheckerAspect implements Aspect { - /** - * @var MethodConditionWithInheritDocFetcher - */ - private $methodConditionFetcher; - - public function __construct(Reader $reader) - { - parent::__construct($reader); - $this->methodConditionFetcher = new MethodConditionWithInheritDocFetcher([Verify::class], $reader); - } - - /** - * Verifies pre-condition contract for the method - * - * @param MethodInvocation $invocation - * @Before("@execution(PhpDeal\Annotation\Verify)") - * - * @throws ContractViolation - * @throws ReflectionException - */ - public function preConditionContract(MethodInvocation $invocation): void - { - $object = $invocation->getThis(); - $args = $this->fetchMethodArguments($invocation); - $scope = $invocation->getMethod()->getDeclaringClass()->name; - - $allContracts = $this->fetchAllContracts($invocation); - $this->ensureContracts($invocation, $allContracts, $object, $scope, $args); - } + public function __construct( + private ContractFetcher $fetcher, + private ContractEvaluator $evaluator, + ) {} /** - * @param MethodInvocation $invocation - * @return array - * @throws ReflectionException + * @throws PreconditionViolation */ - private function fetchAllContracts(MethodInvocation $invocation): array + #[Before( + '@execution(PhpDeal\Attribute\Verify)' + . ' || @execution(PhpDeal\Attribute\Inherit)' + . ' || (@within(PhpDeal\Attribute\Inherit) && (execution(public **->*(*)) || execution(public **::*(*))))', + )] + public function checkPreconditions(MethodInvocation $invocation): void { - $allContracts = $this->fetchParentsContracts($invocation); - /** @var ReflectionMethod&AnnotatedReflectionMethod $reflectionMethod */ - $reflectionMethod = $invocation->getMethod(); - - foreach ($reflectionMethod->getAnnotations() as $annotation) { - if ($annotation instanceof Verify) { - $allContracts[] = $annotation; - } + if ($this->evaluator->isEvaluating()) { + return; + } + $contracts = $this->fetcher->getPreconditions($invocation->getMethod()); + if ($contracts === []) { + return; } - return \array_unique($allContracts); - } - - /** - * @param MethodInvocation $invocation - * @return array - * @throws ReflectionException - */ - private function fetchParentsContracts(MethodInvocation $invocation): array - { - return $this->methodConditionFetcher->getConditions( - $invocation->getMethod()->getDeclaringClass(), - $invocation->getMethod()->name - ); + $variables = $this->evaluator->getArguments($invocation); + $this->evaluator->check($invocation, $contracts, $variables, ContractKind::Precondition); } } diff --git a/src/Attribute/Contract.php b/src/Attribute/Contract.php new file mode 100644 index 0000000..f35efde --- /dev/null +++ b/src/Attribute/Contract.php @@ -0,0 +1,28 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Attribute; + +/** + * Common interface of every contract attribute that carries a PHP expression + * + * The expression is evaluated in the scope of the class that declares the method, so it can read private and + * protected members through `$this` or `self::`. Method arguments are available by their names. + */ +interface Contract +{ + /** + * PHP expression that must evaluate to `true` (or `null`, for assertion libraries) for the contract to hold + */ + public string $expression { get; } +} diff --git a/src/Attribute/Ensure.php b/src/Attribute/Ensure.php new file mode 100644 index 0000000..8e6d914 --- /dev/null +++ b/src/Attribute/Ensure.php @@ -0,0 +1,33 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Attribute; + +use Attribute; + +/** + * Post-condition: a promise of the method, checked after the method body has returned. + * + * Besides the arguments, the expression can use `$__result` (the returned value) and `$__old` (a clone of + * the object taken before the call): `#[Ensure('$this->balance === $__old->balance + $amount')]` + * + * The attribute is repeatable, every expression must hold. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +final readonly class Ensure implements Contract +{ + /** + * @param string $expression PHP expression that must evaluate to true + */ + public function __construct(public string $expression) {} +} diff --git a/src/Attribute/Inherit.php b/src/Attribute/Inherit.php new file mode 100644 index 0000000..ef086c1 --- /dev/null +++ b/src/Attribute/Inherit.php @@ -0,0 +1,25 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Attribute; + +use Attribute; + +/** + * Inherits the contracts of parent classes and interfaces without declaring own ones + * + * On a method it enables the pre- and post-conditions of the same method in every parent class and interface. + * On a class it does the same for every public method, and enables the invariants of the parents. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)] +final readonly class Inherit {} diff --git a/src/Attribute/Invariant.php b/src/Attribute/Invariant.php new file mode 100644 index 0000000..05d7931 --- /dev/null +++ b/src/Attribute/Invariant.php @@ -0,0 +1,32 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Attribute; + +use Attribute; + +/** + * Class invariant: a condition that holds after the constructor and after every public method call. + * + * Invariants are inherited from parent classes and interfaces: `#[Invariant('$this->balance >= 0')]` + * + * The attribute is repeatable, every expression must hold. + */ +#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)] +final readonly class Invariant implements Contract +{ + /** + * @param string $expression PHP expression that must evaluate to true + */ + public function __construct(public string $expression) {} +} diff --git a/src/Attribute/Verify.php b/src/Attribute/Verify.php new file mode 100644 index 0000000..8a6a4ee --- /dev/null +++ b/src/Attribute/Verify.php @@ -0,0 +1,32 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Attribute; + +use Attribute; + +/** + * Pre-condition: a requirement upon the caller, checked before the method body runs. + * + * Arguments of the method are available by their names: `#[Verify('$amount > 0')]` + * + * The attribute is repeatable, every expression must hold. + */ +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] +final readonly class Verify implements Contract +{ + /** + * @param string $expression PHP expression that must evaluate to true + */ + public function __construct(public string $expression) {} +} diff --git a/src/Contract/BoundContract.php b/src/Contract/BoundContract.php new file mode 100644 index 0000000..07ca539 --- /dev/null +++ b/src/Contract/BoundContract.php @@ -0,0 +1,34 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Contract; + +use PhpDeal\Attribute\Contract; + +/** + * A contract together with the class scope its expression is evaluated in + * + * Contracts of a class are evaluated in the scope of that class, so they can read its private members even when the + * method is called on a subclass. Contracts of an interface are evaluated in the scope of the implementing class. + */ +final readonly class BoundContract +{ + /** + * @param Contract $contract Contract attribute + * @param class-string $scope Class scope for the expression + */ + public function __construct( + public Contract $contract, + public string $scope, + ) {} +} diff --git a/src/Contract/ContractEvaluator.php b/src/Contract/ContractEvaluator.php new file mode 100644 index 0000000..02c0975 --- /dev/null +++ b/src/Contract/ContractEvaluator.php @@ -0,0 +1,145 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Contract; + +use Closure; +use Go\Aop\Intercept\MethodInvocation; +use ParseError; +use PhpDeal\Exception\ContractViolation; +use PhpDeal\Exception\InvalidContractException; +use Throwable; + +/** + * Compiles contract expressions into closures and evaluates them for a method invocation + * + * Every expression is compiled once per process. While a contract is evaluated, contracts of nested calls are not + * checked, so an invariant may call public methods of its own class without recursing endlessly. + */ +final class ContractEvaluator +{ + /** + * @var array): mixed> + */ + private array $compiled = []; + + private int $depth = 0; + + /** + * Tells whether a contract is being evaluated right now + */ + public function isEvaluating(): bool + { + return $this->depth > 0; + } + + /** + * Returns the arguments of the invocation keyed by parameter name, with default values filled in + * + * @return array + */ + public function getArguments(MethodInvocation $invocation): array + { + $values = $invocation->getArguments(); + $variables = []; + foreach ($invocation->getMethod()->getParameters() as $index => $parameter) { + if ($parameter->isVariadic()) { + $variables[$parameter->name] = \array_slice($values, $index); + break; + } + $variables[$parameter->name] = match (true) { + \array_key_exists($index, $values) => $values[$index], + $parameter->isDefaultValueAvailable() => $parameter->getDefaultValue(), + default => null, + }; + } + + return $variables; + } + + /** + * Evaluates every contract and throws on the first one that does not hold + * + * @param list $contracts Contracts to check + * @param array $variables Variables available to the expressions + * + * @throws ContractViolation When a contract does not hold + * @throws InvalidContractException When a contract can not be compiled or returns a non-boolean value + */ + public function check(MethodInvocation $invocation, array $contracts, array $variables, ContractKind $kind): void + { + $instance = $invocation->getThis(); + $location = $invocation->getMethod()->class . '::' . $invocation->getMethod()->name . '()'; + foreach ($contracts as $boundContract) { + $expression = $boundContract->contract->expression; + $isStatic = $instance === null; + if ($isStatic && \preg_match('/\$this\b/', $expression) === 1) { + throw InvalidContractException::forStaticContext($expression, $location); + } + try { + $closure = $this->compile($expression, $isStatic); + } catch (ParseError $error) { + throw InvalidContractException::forSyntaxError($expression, $location, $error); + } + $evaluator = Closure::bind($closure, $instance, $boundContract->scope); + if ($evaluator === null) { + throw InvalidContractException::forStaticContext($expression, $location); + } + + ++$this->depth; + try { + $result = $evaluator($variables); + } catch (Throwable $error) { + // Assertion libraries signal failures with exceptions, broken expressions with errors + throw $kind->createViolation($invocation, $expression, $error); + } finally { + --$this->depth; + } + + if ($result === false) { + throw $kind->createViolation($invocation, $expression); + } + // null is accepted for assertion helpers that return nothing + if ($result !== true && $result !== null) { + throw InvalidContractException::forInvalidResult($expression, $location, $result); + } + } + } + + /** + * @return Closure(array): mixed + * + * @throws ParseError When the expression is not valid PHP + */ + private function compile(string $expression, bool $isStatic): Closure + { + $cacheKey = ($isStatic ? 'static:' : 'dynamic:') . $expression; + if (isset($this->compiled[$cacheKey])) { + return $this->compiled[$cacheKey]; + } + // The closing parenthesis is on its own line, so a trailing "//" comment can not swallow it + $code = 'return ' . ($isStatic ? 'static ' : '') + . 'function (array $__contractVariables): mixed {' + . ' \extract($__contractVariables, \EXTR_SKIP);' + . ' return (' . $expression . "\n);" + . ' };'; + + $closure = eval($code); + if (!$closure instanceof Closure) { + throw new ParseError('The expression did not compile into a closure'); + } + + /** @var Closure(array): mixed $closure */ + return $this->compiled[$cacheKey] = $closure; + } +} diff --git a/src/Contract/ContractFetcher.php b/src/Contract/ContractFetcher.php new file mode 100644 index 0000000..48369ee --- /dev/null +++ b/src/Contract/ContractFetcher.php @@ -0,0 +1,183 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Contract; + +use Go\Aop\Proxy; +use PhpDeal\Attribute\Contract; +use PhpDeal\Attribute\Ensure; +use PhpDeal\Attribute\Inherit; +use PhpDeal\Attribute\Invariant; +use PhpDeal\Attribute\Verify; +use ReflectionAttribute; +use ReflectionClass; +use ReflectionMethod; + +/** + * Collects the contracts of methods and classes, including the ones inherited from parents and interfaces + * + * Results are cached per class and method, attributes are read only once per process. + */ +final class ContractFetcher +{ + /** + * @var array> + */ + private array $cache = []; + + /** + * Returns the pre-conditions of a method + * + * Pre-conditions of parent classes and interfaces are included only when the method opts in, with + * `#[Inherit]` on the method or its class, or with an `{@inheritdoc}` tag in its doc comment. + * + * @return list + */ + public function getPreconditions(ReflectionMethod $method): array + { + return $this->getMethodContracts($method, Verify::class, $this->inheritsPreconditions($method)); + } + + /** + * Returns the post-conditions of a method, together with the ones of parent classes and interfaces + * + * @return list + */ + public function getPostconditions(ReflectionMethod $method): array + { + return $this->getMethodContracts($method, Ensure::class, true); + } + + /** + * Returns the invariants of a class, together with the ones of parent classes and interfaces + * + * @param ReflectionClass $class + * + * @return list + */ + public function getInvariants(ReflectionClass $class): array + { + $cacheKey = $class->name . '#' . Invariant::class; + if (isset($this->cache[$cacheKey])) { + return $this->cache[$cacheKey]; + } + + $contracts = self::readContracts($class, Invariant::class, $class->name); + foreach (self::getAncestors($class) as $ancestor) { + $scope = $ancestor->isInterface() ? $class->name : $ancestor->name; + \array_push($contracts, ...self::readContracts($ancestor, Invariant::class, $scope)); + } + + return $this->cache[$cacheKey] = self::unique($contracts); + } + + /** + * @param class-string $type Contract attribute to collect + * + * @return list + */ + private function getMethodContracts(ReflectionMethod $method, string $type, bool $withAncestors): array + { + $class = $method->getDeclaringClass(); + $cacheKey = $class->name . '::' . $method->name . '#' . $type . ($withAncestors ? '+' : ''); + if (isset($this->cache[$cacheKey])) { + return $this->cache[$cacheKey]; + } + + $contracts = self::readContracts($method, $type, $class->name); + if ($withAncestors) { + foreach (self::getAncestors($class) as $ancestor) { + if (!$ancestor->hasMethod($method->name)) { + continue; + } + $ancestorMethod = $ancestor->getMethod($method->name); + // A method declared higher in the hierarchy is read when that ancestor is visited + if ($ancestorMethod->isPrivate() || $ancestorMethod->getDeclaringClass()->name !== $ancestor->name) { + continue; + } + $scope = $ancestor->isInterface() ? $class->name : $ancestor->name; + \array_push($contracts, ...self::readContracts($ancestorMethod, $type, $scope)); + } + } + + return $this->cache[$cacheKey] = self::unique($contracts); + } + + private function inheritsPreconditions(ReflectionMethod $method): bool + { + if ($method->getAttributes(Inherit::class) !== []) { + return true; + } + if ($method->getDeclaringClass()->getAttributes(Inherit::class) !== []) { + return true; + } + $docComment = $method->getDocComment(); + + return $docComment !== false && \preg_match('/@inheritdoc\b/i', $docComment) === 1; + } + + /** + * Returns parent classes (closest first) and then every implemented interface + * + * @param ReflectionClass $class + * + * @return list> + */ + private static function getAncestors(ReflectionClass $class): array + { + $ancestors = []; + $parent = $class; + while (($parent = $parent->getParentClass()) !== false) { + $ancestors[] = $parent; + } + foreach ($class->getInterfaces() as $interface) { + if ($interface->name !== Proxy::class) { + $ancestors[] = $interface; + } + } + + return $ancestors; + } + + /** + * @param ReflectionClass|ReflectionMethod $reflector + * @param class-string $type + * @param class-string $scope + * + * @return list + */ + private static function readContracts(ReflectionClass|ReflectionMethod $reflector, string $type, string $scope): array + { + return \array_map( + static fn(ReflectionAttribute $attribute): BoundContract => new BoundContract($attribute->newInstance(), $scope), + $reflector->getAttributes($type, ReflectionAttribute::IS_INSTANCEOF), + ); + } + + /** + * Removes repeated expressions, the first (most specific) occurrence wins + * + * @param list $contracts + * + * @return list + */ + private static function unique(array $contracts): array + { + $unique = []; + foreach ($contracts as $boundContract) { + $unique[$boundContract->contract::class . "\0" . $boundContract->contract->expression] ??= $boundContract; + } + + return \array_values($unique); + } +} diff --git a/src/Contract/ContractKind.php b/src/Contract/ContractKind.php new file mode 100644 index 0000000..edce8dc --- /dev/null +++ b/src/Contract/ContractKind.php @@ -0,0 +1,43 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Contract; + +use Go\Aop\Intercept\MethodInvocation; +use PhpDeal\Exception\ContractViolation; +use PhpDeal\Exception\InvariantViolation; +use PhpDeal\Exception\PostconditionViolation; +use PhpDeal\Exception\PreconditionViolation; +use Throwable; + +/** + * Kind of a contract check, decides which exception reports a violation + */ +enum ContractKind +{ + case Precondition; + case Postcondition; + case Invariant; + + public function createViolation( + MethodInvocation $invocation, + string $expression, + ?Throwable $previous = null, + ): ContractViolation { + return match ($this) { + self::Precondition => new PreconditionViolation($invocation, $expression, $previous), + self::Postcondition => new PostconditionViolation($invocation, $expression, $previous), + self::Invariant => new InvariantViolation($invocation, $expression, $previous), + }; + } +} diff --git a/src/Contract/Fetcher/Parent/AbstractFetcher.php b/src/Contract/Fetcher/Parent/AbstractFetcher.php deleted file mode 100644 index 8604572..0000000 --- a/src/Contract/Fetcher/Parent/AbstractFetcher.php +++ /dev/null @@ -1,60 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Contract\Fetcher\Parent; - -use Doctrine\Common\Annotations\Reader; - -abstract class AbstractFetcher -{ - /** - * @var string[] - */ - protected $expectedAnnotationTypes; - - /** - * @var Reader - */ - protected $annotationReader; - - /** - * @param string[] $expectedAnnotationTypes - * @param Reader $reader - */ - public function __construct(array $expectedAnnotationTypes, Reader $reader) - { - $this->expectedAnnotationTypes = $expectedAnnotationTypes; - $this->annotationReader = $reader; - } - - /** - * Performs filtering of annotations by the requested class name - * - * @param array $annotations - * @return array - */ - protected function filterContractAnnotation(array $annotations): array - { - $contractAnnotations = []; - - foreach ($annotations as $annotation) { - $annotationClass = \get_class($annotation); - - if (\in_array($annotationClass, $this->expectedAnnotationTypes, true)) { - $contractAnnotations[] = $annotation; - } - } - - return $contractAnnotations; - } -} diff --git a/src/Contract/Fetcher/Parent/InvariantFetcher.php b/src/Contract/Fetcher/Parent/InvariantFetcher.php deleted file mode 100644 index 82b9a8d..0000000 --- a/src/Contract/Fetcher/Parent/InvariantFetcher.php +++ /dev/null @@ -1,67 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Contract\Fetcher\Parent; - -use ReflectionClass; - -class InvariantFetcher extends AbstractFetcher -{ - /** - * Fetches conditions from all parent classes recursively - * - * @param ReflectionClass $class - * - * @return array - */ - public function getConditions(ReflectionClass $class): array - { - $annotations = []; - $parents = []; - - $this->getParentClasses($class, $parents); - $this->getInterfaces($class, $parents); - - foreach ($parents as $parent) { - $annotations[] = $this->annotationReader->getClassAnnotations($parent); - } - - if (\count($annotations)) { - $annotations = \array_merge(...$annotations); - } - - return $this->filterContractAnnotation($annotations); - } - - /** - * @param ReflectionClass $class - * @param array $parents - */ - private function getParentClasses(ReflectionClass $class, array &$parents): void - { - while ($class = $class->getParentClass()) { - $parents[] = $class; - } - } - - /** - * @param ReflectionClass $class - * @param array $parents - */ - private function getInterfaces(ReflectionClass $class, array &$parents): void - { - foreach ($class->getInterfaces() as $interface) { - $parents[] = $interface; - } - } -} diff --git a/src/Contract/Fetcher/Parent/MethodConditionFetcher.php b/src/Contract/Fetcher/Parent/MethodConditionFetcher.php deleted file mode 100644 index d16bb09..0000000 --- a/src/Contract/Fetcher/Parent/MethodConditionFetcher.php +++ /dev/null @@ -1,83 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Contract\Fetcher\Parent; - -use ReflectionClass; - -class MethodConditionFetcher extends AbstractFetcher -{ - /** - * Fetches conditions from all parent method prototypes recursively - * - * @param ReflectionClass $class - * @param string $methodName - * - * @return array - * @throws \ReflectionException - */ - public function getConditions(ReflectionClass $class, string $methodName): array - { - $annotations = []; - $parentMethods = []; - - $this->getParentClassesMethods($class, $methodName, $parentMethods); - $this->getInterfacesMethods($class, $methodName, $parentMethods); - - foreach ($parentMethods as $parentMethod) { - $annotations[] = $this->annotationReader->getMethodAnnotations($parentMethod); - } - - if (\count($annotations) > 0) { - $annotations = \array_merge(...$annotations); - } - - return $this->filterContractAnnotation($annotations); - } - - /** - * @param ReflectionClass $class - * @param string $methodName - * @param array $parentMethods - * @throws \ReflectionException - */ - private function getParentClassesMethods(ReflectionClass $class, string $methodName, array &$parentMethods): void - { - $parent = $class->getParentClass(); - - if ($parent === false) { - return; - } - - if ($parent->hasMethod($methodName)) { - $parentMethods[] = $parent->getMethod($methodName); - } - - $this->getParentClassesMethods($parent, $methodName, $parentMethods); - } - - /** - * @param ReflectionClass $class - * @param string $methodName - * @param array $parentMethods - * @throws \ReflectionException - */ - private function getInterfacesMethods(ReflectionClass $class, $methodName, &$parentMethods): void - { - foreach ($class->getInterfaces() as $interface) { - if ($interface->hasMethod($methodName)) { - $parentMethods[] = $interface->getMethod($methodName); - } - } - } -} diff --git a/src/Contract/Fetcher/Parent/MethodConditionWithInheritDocFetcher.php b/src/Contract/Fetcher/Parent/MethodConditionWithInheritDocFetcher.php deleted file mode 100644 index e5bb125..0000000 --- a/src/Contract/Fetcher/Parent/MethodConditionWithInheritDocFetcher.php +++ /dev/null @@ -1,91 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Contract\Fetcher\Parent; - -use ReflectionClass; -use ReflectionException; - -class MethodConditionWithInheritDocFetcher extends AbstractFetcher -{ - /** - * Fetches conditions from all parent method prototypes recursively - * - * @param ReflectionClass $class - * @param string $methodName - * - * @return array - * @throws ReflectionException - */ - public function getConditions(ReflectionClass $class, string $methodName): array - { - $annotations = []; - $parentMethods = []; - $docComment = $class->getMethod($methodName)->getDocComment(); - - if ($docComment === false) { - return $annotations; - } - - if (\preg_match('/\@inheritdoc/i', $docComment)) { - $this->getParentClassesMethods($class, $methodName, $parentMethods); - $this->getInterfacesMethods($class, $methodName, $parentMethods); - } - - foreach ($parentMethods as $parentMethod) { - $annotations[] = $this->annotationReader->getMethodAnnotations($parentMethod); - } - - if (\count($annotations)) { - $annotations = \array_merge(...$annotations); - } - - return $this->filterContractAnnotation($annotations); - } - - /** - * @param ReflectionClass $class - * @param string $methodName - * @param array $parentMethods - * @throws ReflectionException - */ - private function getParentClassesMethods(ReflectionClass $class, string $methodName, array &$parentMethods): void - { - $parent = $class->getParentClass(); - - if ($parent === false) { - return; - } - - if ($parent->hasMethod($methodName)) { - $parentMethods[] = $parent->getMethod($methodName); - } - - $this->getParentClassesMethods($parent, $methodName, $parentMethods); - } - - /** - * @param ReflectionClass $class - * @param string $methodName - * @param array $parentMethods - * @throws ReflectionException - */ - private function getInterfacesMethods(ReflectionClass $class, $methodName, &$parentMethods): void - { - foreach ($class->getInterfaces() as $interface) { - if ($interface->hasMethod($methodName)) { - $parentMethods[] = $interface->getMethod($methodName); - } - } - } -} diff --git a/src/ContractApplication.php b/src/ContractApplication.php index 7068950..41aacf0 100644 --- a/src/ContractApplication.php +++ b/src/ContractApplication.php @@ -3,7 +3,7 @@ /** * PHP Deal framework * - * @copyright Copyright 2019, Lisachenko Alexander + * @copyright Copyright 2014-2026, Lisachenko Alexander * * This source file is subject to the license that is bundled * with this source code in the file LICENSE. @@ -13,36 +13,56 @@ namespace PhpDeal; -use Doctrine\Common\Annotations\AnnotationReader; use Go\Core\AspectContainer; use Go\Core\AspectKernel; -use PhpDeal\Aspect\InheritCheckerAspect; -use Go\Core\GoAspectContainer; use PhpDeal\Aspect\InvariantCheckerAspect; use PhpDeal\Aspect\PostconditionCheckerAspect; use PhpDeal\Aspect\PreconditionCheckerAspect; +use PhpDeal\Contract\ContractEvaluator; +use PhpDeal\Contract\ContractFetcher; /** - * Main kernel class for enabling "design by contract" paradigm + * Aspect kernel that enables Design by Contract checks + * + * Initialize it once, as early as possible in the front controller: + * + * ContractApplication::getInstance()->init([ + * 'debug' => true, + * 'appDir' => __DIR__ . '/..', + * 'cacheDir' => __DIR__ . '/../var/cache/contracts', + * 'includePaths' => [__DIR__ . '/../src'], + * ]); + * + * Applications that already have a Go! AOP kernel call {@see registerAspects()} from it instead. */ class ContractApplication extends AspectKernel { - /** - * Configures an AspectContainer with advisors, aspects and pointcuts - * - * @param AspectContainer&GoAspectContainer $container + * Registers the contract aspects in an aspect container * - * @return void + * Call it from `configureAop()` of your own aspect kernel to combine contracts with other aspects. */ - protected function configureAop(AspectContainer $container): void + public static function registerAspects(AspectContainer $container): void { - /** @var AnnotationReader $reader */ - $reader = $container->get('aspect.annotation.reader'); + $fetcher = new ContractFetcher(); + $evaluator = new ContractEvaluator(); + + $container->addLazyService( + PreconditionCheckerAspect::class, + static fn(): PreconditionCheckerAspect => new PreconditionCheckerAspect($fetcher, $evaluator), + ); + $container->addLazyService( + PostconditionCheckerAspect::class, + static fn(): PostconditionCheckerAspect => new PostconditionCheckerAspect($fetcher, $evaluator), + ); + $container->addLazyService( + InvariantCheckerAspect::class, + static fn(): InvariantCheckerAspect => new InvariantCheckerAspect($fetcher, $evaluator), + ); + } - $container->registerAspect(new InvariantCheckerAspect($reader)); - $container->registerAspect(new PostconditionCheckerAspect($reader)); - $container->registerAspect(new PreconditionCheckerAspect($reader)); - $container->registerAspect(new InheritCheckerAspect($reader)); + protected function configureAop(AspectContainer $container): void + { + self::registerAspects($container); } } diff --git a/src/Exception/ContractViolation.php b/src/Exception/ContractViolation.php index 10e3f96..9b3f5f0 100644 --- a/src/Exception/ContractViolation.php +++ b/src/Exception/ContractViolation.php @@ -3,7 +3,7 @@ /** * PHP Deal framework * - * @copyright Copyright 2019, Lisachenko Alexander + * @copyright Copyright 2014-2026, Lisachenko Alexander * * This source file is subject to the license that is bundled * with this source code in the file LICENSE. @@ -13,33 +13,120 @@ namespace PhpDeal\Exception; +use Go\Aop\Framework\AbstractMethodInvocation; use Go\Aop\Intercept\MethodInvocation; +use LogicException; +use ReflectionMethod; use Throwable; +use UnitEnum; /** - * Specific contract violation exception to point to the file and line of invocation + * Base exception for every broken contract + * + * Catch {@see PreconditionViolation}, {@see PostconditionViolation} or {@see InvariantViolation} to handle a single + * kind of contract. The file and line of the exception point to the method that declares the contract. */ -class ContractViolation extends \LogicException +class ContractViolation extends LogicException implements ExceptionInterface { + protected const string KIND = 'Contract'; + + /** + * Longest rendered argument, longer ones are truncated + */ + private const int MAX_ARGUMENT_LENGTH = 40; + + /** + * Expression of the violated contract + */ + public readonly string $contract; /** - * Violation constructor + * Name of the class whose method was called * - * @param MethodInvocation $invocation Current method invocation - * @param string $contract Violated contract code - * @param Throwable $previous + * @var class-string */ - public function __construct(MethodInvocation $invocation, $contract, Throwable $previous = null) + public readonly string $className; + + /** + * Name of the called method + */ + public readonly string $methodName; + + /** + * @param MethodInvocation $invocation Invocation that violated the contract + * @param string $contract Expression of the violated contract + * @param Throwable|null $previous Error or assertion failure raised by the expression, if any + */ + public function __construct(MethodInvocation $invocation, string $contract, ?Throwable $previous = null) { - $obj = $invocation->getThis(); - $objName = \is_object($obj) ? \get_class($obj) : $obj; - $method = $invocation->getMethod(); - $args = \implode(', ', $invocation->getArguments()); + $method = $invocation->getMethod(); + $instance = $invocation->getThis(); + + $this->contract = $contract; + $this->className = $instance !== null ? $instance::class : $invocation->getScope(); + $this->methodName = $method->name; - $message = "Contract {$contract} violated with argument set {{$args}} for {$objName}->{$method->name}"; + $message = \sprintf( + '%s "%s" violated in %s%s%s(%s)', + static::KIND, + $contract, + $this->className, + $instance !== null ? '->' : '::', + $method->name, + \implode(', ', \array_map(self::renderValue(...), $invocation->getArguments())), + ); + if ($previous !== null) { + $message .= ': ' . $previous->getMessage(); + } parent::__construct($message, 0, $previous); - $this->file = $method->getFileName(); - $this->line = $method->getStartLine() + 1; + $this->pointToDeclaration($method); + } + + /** + * Moves the reported location to the method that declares the contract + * + * Woven classes run the original method body from a trait alias, so the alias holds the real source location. + */ + private function pointToDeclaration(ReflectionMethod $method): void + { + $class = $method->getDeclaringClass(); + $aliasName = $method->name . AbstractMethodInvocation::TRAIT_ALIAS_SUFFIX; + $original = $class->hasMethod($aliasName) ? $class->getMethod($aliasName) : $method; + $fileName = $original->getFileName(); + $line = $original->getStartLine(); + + if ($fileName !== false && $line !== false) { + $this->file = $fileName; + $this->line = $line; + } + } + + /** + * Renders an argument for the exception message without exposing large or sensitive structures + */ + private static function renderValue(mixed $value): string + { + $rendered = match (true) { + $value === null => 'null', + \is_bool($value) => $value ? 'true' : 'false', + \is_int($value) || \is_float($value) => \var_export($value, true), + \is_string($value) => "'" . \addcslashes($value, "'\\") . "'", + \is_array($value) => 'array(' . \count($value) . ')', + $value instanceof UnitEnum => $value::class . '::' . $value->name, + \is_object($value) => $value::class, + default => \get_debug_type($value), + }; + + if (\strlen($rendered) <= self::MAX_ARGUMENT_LENGTH) { + return $rendered; + } + // Cut at a character boundary when the value is valid UTF-8 + $limit = self::MAX_ARGUMENT_LENGTH - 3; + if (\preg_match('/^.{0,' . $limit . '}/us', $rendered, $matches) === 1) { + return $matches[0] . '...'; + } + + return \substr($rendered, 0, $limit) . '...'; } } diff --git a/src/Exception/ExceptionInterface.php b/src/Exception/ExceptionInterface.php new file mode 100644 index 0000000..62e5113 --- /dev/null +++ b/src/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Exception; + +use Throwable; + +/** + * Marker interface of every exception thrown by the framework + */ +interface ExceptionInterface extends Throwable {} diff --git a/src/Exception/InvalidContractException.php b/src/Exception/InvalidContractException.php new file mode 100644 index 0000000..2094181 --- /dev/null +++ b/src/Exception/InvalidContractException.php @@ -0,0 +1,59 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Exception; + +use DomainException; +use Throwable; + +/** + * Thrown when a contract is written incorrectly: its expression can not be compiled, or it returns + * something else than a boolean or null + * + * This is a bug in the contract itself, not a violation of it. + */ +final class InvalidContractException extends DomainException implements ExceptionInterface +{ + /** + * @param string $location Method that declares the contract, e.g. "App\Account::deposit()" + */ + public static function forSyntaxError(string $expression, string $location, Throwable $previous): self + { + return new self( + \sprintf('Contract "%s" of %s can not be compiled: %s', $expression, $location, $previous->getMessage()), + 0, + $previous, + ); + } + + /** + * @param string $location Method that declares the contract, e.g. "App\Account::deposit()" + */ + public static function forInvalidResult(string $expression, string $location, mixed $result): self + { + return new self(\sprintf( + 'Contract "%s" of %s must return a boolean or null (for assertions), %s returned', + $expression, + $location, + \get_debug_type($result), + )); + } + + /** + * @param string $location Method that declares the contract, e.g. "App\Account::deposit()" + */ + public static function forStaticContext(string $expression, string $location): self + { + return new self(\sprintf('Contract "%s" of %s uses $this, but the method is static', $expression, $location)); + } +} diff --git a/src/Exception/InvariantViolation.php b/src/Exception/InvariantViolation.php new file mode 100644 index 0000000..36f072e --- /dev/null +++ b/src/Exception/InvariantViolation.php @@ -0,0 +1,22 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Exception; + +/** + * Thrown when a class invariant (#[Invariant]) does not hold after a public method call + */ +final class InvariantViolation extends ContractViolation +{ + protected const string KIND = 'Invariant'; +} diff --git a/src/Exception/PostconditionViolation.php b/src/Exception/PostconditionViolation.php new file mode 100644 index 0000000..41f86cd --- /dev/null +++ b/src/Exception/PostconditionViolation.php @@ -0,0 +1,22 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Exception; + +/** + * Thrown when a post-condition (#[Ensure]) does not hold: the method did not keep its promise + */ +final class PostconditionViolation extends ContractViolation +{ + protected const string KIND = 'Postcondition'; +} diff --git a/src/Exception/PreconditionViolation.php b/src/Exception/PreconditionViolation.php new file mode 100644 index 0000000..202ad82 --- /dev/null +++ b/src/Exception/PreconditionViolation.php @@ -0,0 +1,22 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Exception; + +/** + * Thrown when a pre-condition (#[Verify]) does not hold: the caller passed invalid arguments + */ +final class PreconditionViolation extends ContractViolation +{ + protected const string KIND = 'Precondition'; +} diff --git a/src/PHPStan/ContractUsageExtension.php b/src/PHPStan/ContractUsageExtension.php new file mode 100644 index 0000000..2441d6b --- /dev/null +++ b/src/PHPStan/ContractUsageExtension.php @@ -0,0 +1,111 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\PHPStan; + +use PhpDeal\Attribute\Ensure; +use PhpDeal\Attribute\Invariant; +use PhpDeal\Attribute\Verify; +use PHPStan\Reflection\AttributeReflection; +use PHPStan\Reflection\ClassReflection; +use PHPStan\Reflection\ExtendedPropertyReflection; +use PHPStan\Reflection\MethodReflection; +use PHPStan\Rules\Methods\AlwaysUsedMethodExtension; +use PHPStan\Rules\Properties\ReadWritePropertiesExtension; + +/** + * Tells PHPStan that private members used by contract expressions are used + * + * Contract expressions are strings, so without this extension PHPStan reports a private property that is only read + * by `#[Invariant('$this->balance >= 0')]` as never read. Registered automatically by phpstan/extension-installer. + */ +final class ContractUsageExtension implements ReadWritePropertiesExtension, AlwaysUsedMethodExtension +{ + private const array CONTRACT_ATTRIBUTES = [Verify::class, Ensure::class, Invariant::class]; + + /** + * Contract expressions of each class, joined into one string + * + * @var array + */ + private array $contractCode = []; + + public function isAlwaysRead(ExtendedPropertyReflection $property, string $propertyName): bool + { + $name = \preg_quote($propertyName, '/'); + $pattern = '/(?:\$this|\$__old)\s*\??->\s*' . $name . '\b|(?:self|static)::\$' . $name . '\b/'; + + return \preg_match($pattern, $this->getContractCode($property->getDeclaringClass())) === 1; + } + + public function isAlwaysWritten(ExtendedPropertyReflection $property, string $propertyName): bool + { + return false; + } + + public function isInitialized(ExtendedPropertyReflection $property, string $propertyName): bool + { + return false; + } + + public function isAlwaysUsed(MethodReflection $methodReflection): bool + { + $name = \preg_quote($methodReflection->getName(), '/'); + $pattern = '/(?:\$this|\$__old)\s*\??->\s*' . $name . '\s*\(|(?:self|static)::' . $name . '\s*\(/i'; + + return \preg_match($pattern, $this->getContractCode($methodReflection->getDeclaringClass())) === 1; + } + + /** + * Returns the contracts evaluated in the scope of the class: its own ones and the ones of its interfaces + */ + private function getContractCode(ClassReflection $class): string + { + if (isset($this->contractCode[$class->getName()])) { + return $this->contractCode[$class->getName()]; + } + + $expressions = []; + foreach ([$class, ...\array_values($class->getInterfaces())] as $reflection) { + \array_push($expressions, ...self::readExpressions($reflection->getAttributes())); + foreach ($reflection->getNativeReflection()->getMethods() as $method) { + $methodAttributes = $reflection->getNativeMethod($method->getName())->getAttributes(); + \array_push($expressions, ...self::readExpressions($methodAttributes)); + } + } + + return $this->contractCode[$class->getName()] = \implode("\n", $expressions); + } + + /** + * @param list $attributes + * + * @return list + */ + private static function readExpressions(array $attributes): array + { + $expressions = []; + foreach ($attributes as $attribute) { + if (!\in_array($attribute->getName(), self::CONTRACT_ATTRIBUTES, true)) { + continue; + } + foreach ($attribute->getArgumentTypes() as $argumentType) { + foreach ($argumentType->getConstantStrings() as $expression) { + $expressions[] = $expression->getValue(); + } + } + } + + return $expressions; + } +} diff --git a/tests/Fixtures/Ensure/ChildCounter.php b/tests/Fixtures/Ensure/ChildCounter.php new file mode 100644 index 0000000..eab99e3 --- /dev/null +++ b/tests/Fixtures/Ensure/ChildCounter.php @@ -0,0 +1,16 @@ +value !== 1')] + public function add(int $value): void + { + $this->value += $value; + } +} diff --git a/tests/Fixtures/Ensure/Counter.php b/tests/Fixtures/Ensure/Counter.php new file mode 100644 index 0000000..c8dda92 --- /dev/null +++ b/tests/Fixtures/Ensure/Counter.php @@ -0,0 +1,56 @@ +value === $__old->value + $amount')] + #[Ensure('$this->value > 0')] + public function increment(float $amount): void + { + $this->value += $amount; + } + + #[Ensure('$this->value === $__old->value + $amount')] + public function badIncrement(float $amount): void + { + $this->value += ($amount - 0.1); // Dirty hacker wants to earn money! + } + + #[Ensure('$__result === $this->value')] + public function getValue(): float + { + return $this->value; + } + + #[Ensure('$__result === $this->value')] + public function cheatingGetter(): float + { + return $this->value + 1; + } + + #[Ensure('$__result > 0')] + public function withoutOldState(): int + { + return 1; + } + + #[Ensure('\is_string($__result)')] + public static function staticFactory(): string + { + return 'value'; + } + + public function __clone() + { + ++$this->clones; + } +} diff --git a/tests/Fixtures/Ensure/Grandparent.php b/tests/Fixtures/Ensure/Grandparent.php new file mode 100644 index 0000000..f14fed0 --- /dev/null +++ b/tests/Fixtures/Ensure/Grandparent.php @@ -0,0 +1,15 @@ +value !== -1')] + public function add(int $value): void {} +} diff --git a/tests/Fixtures/Ensure/InterfaceCounter.php b/tests/Fixtures/Ensure/InterfaceCounter.php new file mode 100644 index 0000000..5bbab84 --- /dev/null +++ b/tests/Fixtures/Ensure/InterfaceCounter.php @@ -0,0 +1,21 @@ +value !== 0')] + public function add(int $value): void + { + $this->value += $value; + } +} diff --git a/tests/Fixtures/Ensure/ParentCounter.php b/tests/Fixtures/Ensure/ParentCounter.php new file mode 100644 index 0000000..68adc9e --- /dev/null +++ b/tests/Fixtures/Ensure/ParentCounter.php @@ -0,0 +1,16 @@ +value !== 2')] + public function add(int $value): void + { + $this->value += $value; + } +} diff --git a/tests/Fixtures/Ensure/PositiveA.php b/tests/Fixtures/Ensure/PositiveA.php new file mode 100644 index 0000000..4b50511 --- /dev/null +++ b/tests/Fixtures/Ensure/PositiveA.php @@ -0,0 +1,13 @@ +value !== -1')] + public function add(int $value): void; +} diff --git a/tests/Fixtures/Ensure/PositiveB.php b/tests/Fixtures/Ensure/PositiveB.php new file mode 100644 index 0000000..4c5a9cd --- /dev/null +++ b/tests/Fixtures/Ensure/PositiveB.php @@ -0,0 +1,13 @@ +value !== -2')] + public function add(int $value): void; +} diff --git a/tests/Fixtures/Inherit/BuggyWallet.php b/tests/Fixtures/Inherit/BuggyWallet.php new file mode 100644 index 0000000..e1d45ce --- /dev/null +++ b/tests/Fixtures/Inherit/BuggyWallet.php @@ -0,0 +1,23 @@ +amount += $amount * 2; + } + + public function getAmount(): int + { + return $this->amount; + } +} diff --git a/tests/Fixtures/Inherit/Wallet.php b/tests/Fixtures/Inherit/Wallet.php new file mode 100644 index 0000000..69c6bea --- /dev/null +++ b/tests/Fixtures/Inherit/Wallet.php @@ -0,0 +1,20 @@ +getAmount() >= 0')] +interface Wallet +{ + #[Verify('$amount > 0')] + #[Ensure('$this->getAmount() === $__old->getAmount() + $amount')] + public function add(int $amount): void; + + #[Ensure('$__result >= 0')] + public function getAmount(): int; +} diff --git a/tests/Fixtures/Inherit/WalletWithClassInheritance.php b/tests/Fixtures/Inherit/WalletWithClassInheritance.php new file mode 100644 index 0000000..0265936 --- /dev/null +++ b/tests/Fixtures/Inherit/WalletWithClassInheritance.php @@ -0,0 +1,28 @@ +amount += $amount; + } + + public function getAmount(): int + { + return $this->amount; + } + + public function forceAmount(int $amount): void + { + $this->amount = $amount; + } +} diff --git a/tests/Fixtures/Inherit/WalletWithMethodInheritance.php b/tests/Fixtures/Inherit/WalletWithMethodInheritance.php new file mode 100644 index 0000000..b066b36 --- /dev/null +++ b/tests/Fixtures/Inherit/WalletWithMethodInheritance.php @@ -0,0 +1,31 @@ +bodyCalls; + $this->amount += $amount; + } + + public function getAmount(): int + { + return $this->amount; + } + + public function forceAmount(int $amount): void + { + $this->amount = $amount; + } +} diff --git a/tests/Fixtures/Inherit/WalletWithoutInheritance.php b/tests/Fixtures/Inherit/WalletWithoutInheritance.php new file mode 100644 index 0000000..5d764cd --- /dev/null +++ b/tests/Fixtures/Inherit/WalletWithoutInheritance.php @@ -0,0 +1,20 @@ +amount = $amount; + } + + public function getAmount(): int + { + return $this->amount; + } +} diff --git a/tests/Fixtures/Invariant/ChildValue.php b/tests/Fixtures/Invariant/ChildValue.php new file mode 100644 index 0000000..48b302c --- /dev/null +++ b/tests/Fixtures/Invariant/ChildValue.php @@ -0,0 +1,16 @@ +value !== 1')] +class ChildValue extends ParentValue +{ + public function setValue(int $value): void + { + $this->value = $value; + } +} diff --git a/tests/Fixtures/Invariant/Grandparent.php b/tests/Fixtures/Invariant/Grandparent.php new file mode 100644 index 0000000..04d6990 --- /dev/null +++ b/tests/Fixtures/Invariant/Grandparent.php @@ -0,0 +1,13 @@ +value !== 3')] +abstract class Grandparent +{ + public int $value = 0; +} diff --git a/tests/Fixtures/Invariant/InterfaceValue.php b/tests/Fixtures/Invariant/InterfaceValue.php new file mode 100644 index 0000000..9b50dd8 --- /dev/null +++ b/tests/Fixtures/Invariant/InterfaceValue.php @@ -0,0 +1,18 @@ +value !== 1')] +class InterfaceValue implements NotTwo, NotThree +{ + private int $value = 0; + + public function setValue(int $value): void + { + $this->value = $value; + } +} diff --git a/tests/Fixtures/Invariant/NotThree.php b/tests/Fixtures/Invariant/NotThree.php new file mode 100644 index 0000000..1f67091 --- /dev/null +++ b/tests/Fixtures/Invariant/NotThree.php @@ -0,0 +1,10 @@ +value !== 3')] +interface NotThree {} diff --git a/tests/Fixtures/Invariant/NotTwo.php b/tests/Fixtures/Invariant/NotTwo.php new file mode 100644 index 0000000..c00d521 --- /dev/null +++ b/tests/Fixtures/Invariant/NotTwo.php @@ -0,0 +1,10 @@ +value !== 2')] +interface NotTwo {} diff --git a/tests/Fixtures/Invariant/ParentValue.php b/tests/Fixtures/Invariant/ParentValue.php new file mode 100644 index 0000000..e9232c4 --- /dev/null +++ b/tests/Fixtures/Invariant/ParentValue.php @@ -0,0 +1,10 @@ +value !== 2')] +abstract class ParentValue extends Grandparent {} diff --git a/tests/Fixtures/Invariant/Particle.php b/tests/Fixtures/Invariant/Particle.php new file mode 100644 index 0000000..655a151 --- /dev/null +++ b/tests/Fixtures/Invariant/Particle.php @@ -0,0 +1,36 @@ +speed < 299792458 && $this->speed >= 0')] +class Particle +{ + private float $speed; + + public function __construct(float $speed = 0) + { + $this->speed = $speed; + } + + public function accelerate(float $acceleration, float $time): void + { + $this->speed += ($acceleration * $time); + } + + public function decelerate(float $deceleration, float $time): void + { + $this->speed -= ($deceleration * $time); + } + + public function getSpeed(): float + { + return $this->speed; + } +} diff --git a/tests/Fixtures/Invariant/SelfCheckingParticle.php b/tests/Fixtures/Invariant/SelfCheckingParticle.php new file mode 100644 index 0000000..b2cad59 --- /dev/null +++ b/tests/Fixtures/Invariant/SelfCheckingParticle.php @@ -0,0 +1,26 @@ +getSpeed() >= 0')] +class SelfCheckingParticle +{ + private float $speed = 0; + + public function setSpeed(float $speed): void + { + $this->speed = $speed; + } + + public function getSpeed(): float + { + return $this->speed; + } +} diff --git a/tests/Fixtures/Verify/Account.php b/tests/Fixtures/Verify/Account.php new file mode 100644 index 0000000..041a28f --- /dev/null +++ b/tests/Fixtures/Verify/Account.php @@ -0,0 +1,69 @@ + $this->limit')] + public function aboveLimit(int $amount): void {} + + #[Verify('Assert\Assertion::greaterThan($amount, 5)')] + public function withAssertion(int $amount): bool + { + return Assertion::integer($amount); + } + + #[Verify('$amount < 10')] + #[Verify('$amount > 5')] + public function between(int $amount): void {} + + #[Verify('$currency === "EUR"')] + public function withDefault(int $amount, string $currency = 'EUR'): void {} + + #[Verify('\count($amounts) > 0 && \min($amounts) > 0')] + public function variadic(int ...$amounts): void {} + + #[Verify('$amount > self::$fee')] + public static function staticMethod(int $amount): void {} + + #[Verify('$amount > $this->limit')] + public static function staticWithThis(int $amount): void {} + + #[Verify('$amount >')] + public function syntaxError(int $amount): void {} + + #[Verify('$amount')] + public function notBoolean(int $amount): void {} + + #[Verify('$this->undefinedMethod()')] + public function brokenExpression(): void {} + + #[Verify('$amount > 0 // must be positive')] + public function withComment(int $amount): void {} + + #[Verify('$this->isAllowed($amount)')] + public function guarded(int $amount): void {} + + /** + * Used only by a contract: the PHPStan extension of php-deal must not report it as unused + */ + private function isAllowed(int $amount): bool + { + return $amount % 2 === 0; + } +} diff --git a/tests/Fixtures/Verify/ChildWithInheritDoc.php b/tests/Fixtures/Verify/ChildWithInheritDoc.php new file mode 100644 index 0000000..46897f7 --- /dev/null +++ b/tests/Fixtures/Verify/ChildWithInheritDoc.php @@ -0,0 +1,16 @@ += $this->minimum')] + public function set(int $value): void {} +} diff --git a/tests/Fixtures/Verify/RangeA.php b/tests/Fixtures/Verify/RangeA.php new file mode 100644 index 0000000..84edaf3 --- /dev/null +++ b/tests/Fixtures/Verify/RangeA.php @@ -0,0 +1,13 @@ + - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure\ClassPropagation; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -/** - * @group propagation - */ -class ContractTest extends TestCase -{ - /** - * @var Stub - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new Stub(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function providerEnsureValid(): array - { - return [ - [ - 'variable' => 50, - ] - ]; - } - - /** - * @param int $variable - * @dataProvider providerEnsureValid - */ - public function testEnsureValid(int $variable): void - { - $this->expectNotToPerformAssertions(); - $this->stub->add($variable); - } - - public function providerEnsureInvalid(): array - { - return [ - [ - // invalid for Stub - 'variable' => 1 - ], - [ - // invalid for StubParent - 'variable' => 2 - ], - [ - // invalid for StubGrandparent - 'variable' => -1 - ], - ]; - } - - /** - * @param int $variable - * @dataProvider providerEnsureInvalid - */ - public function testEnsureInvalid(int $variable): void - { - $this->expectException(ContractViolation::class); - $this->stub->add($variable); - } -} diff --git a/tests/Functional/Ensure/ClassPropagation/Stub.php b/tests/Functional/Ensure/ClassPropagation/Stub.php deleted file mode 100644 index 2a848e4..0000000 --- a/tests/Functional/Ensure/ClassPropagation/Stub.php +++ /dev/null @@ -1,28 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -class Stub extends StubParent -{ - /** - * @Contract\Ensure("$this->value !== 1") - * @param int $variable - */ - public function add(int $variable): void - { - $this->value += $variable; - } -} diff --git a/tests/Functional/Ensure/ClassPropagation/StubGrandparent.php b/tests/Functional/Ensure/ClassPropagation/StubGrandparent.php deleted file mode 100644 index a4ea0bc..0000000 --- a/tests/Functional/Ensure/ClassPropagation/StubGrandparent.php +++ /dev/null @@ -1,32 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -class StubGrandparent -{ - /** - * @var int - */ - protected $value; - - /** - * @Contract\Ensure("$this->value !== -1") - * @param int $variable - */ - public function add(int $variable): void - { - } -} diff --git a/tests/Functional/Ensure/ClassPropagation/StubParent.php b/tests/Functional/Ensure/ClassPropagation/StubParent.php deleted file mode 100644 index cfacf2e..0000000 --- a/tests/Functional/Ensure/ClassPropagation/StubParent.php +++ /dev/null @@ -1,28 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -abstract class StubParent extends StubGrandparent -{ - /** - * @Contract\Ensure("$this->value !== 2") - * @param int $variable - */ - public function add(int $variable): void - { - $this->value += $variable; - } -} diff --git a/tests/Functional/Ensure/ContractTest.php b/tests/Functional/Ensure/ContractTest.php deleted file mode 100644 index d9fadab..0000000 --- a/tests/Functional/Ensure/ContractTest.php +++ /dev/null @@ -1,61 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -class ContractTest extends TestCase -{ - /** - * @var Stub - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new Stub(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function testEnsureValid(): void - { - $this->expectNotToPerformAssertions(); - $this->stub->increment(50); - } - - public function testEnsureManyContractsInvalid(): void - { - $this->expectException(ContractViolation::class); - $this->stub->increment(-50); - } - - public function testEnsureInvalid(): void - { - $this->expectException(ContractViolation::class); - $this->stub->badIncrement(40); - } - - public function testEnsureCanHandleResult(): void - { - $this->expectNotToPerformAssertions(); - $this->stub->returnPrivateValue(); - } -} diff --git a/tests/Functional/Ensure/InterfacePropagation/ContractTest.php b/tests/Functional/Ensure/InterfacePropagation/ContractTest.php deleted file mode 100644 index d37e911..0000000 --- a/tests/Functional/Ensure/InterfacePropagation/ContractTest.php +++ /dev/null @@ -1,87 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure\InterfacePropagation; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -/** - * @group propagation - */ -class ContractTest extends TestCase -{ - /** - * @var Stub - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new Stub(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function providerEnsureValid(): array - { - return [ - [ - 'variable' => 50, - ] - ]; - } - - /** - * @param int $variable - * @dataProvider providerEnsureValid - */ - public function testEnsureValid(int $variable): void - { - $this->expectNotToPerformAssertions(); - $this->stub->add($variable); - } - - public function providerEnsureInvalid(): array - { - return [ - [ - // invalid for Stub - 'variable' => 0 - ], - [ - // invalid for StubInterfaceA - 'variable' => -1 - ], - [ - // invalid for StubInterfaceB - 'variable' => -2 - ], - ]; - } - - /** - * @param int $variable - * @dataProvider providerEnsureInvalid - */ - public function testEnsureInvalid(int $variable): void - { - $this->expectException(ContractViolation::class); - $this->stub->add($variable); - } -} diff --git a/tests/Functional/Ensure/InterfacePropagation/Stub.php b/tests/Functional/Ensure/InterfacePropagation/Stub.php deleted file mode 100644 index 1c5e2f5..0000000 --- a/tests/Functional/Ensure/InterfacePropagation/Stub.php +++ /dev/null @@ -1,33 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -class Stub implements StubInterfaceA, StubInterfaceB -{ - /** - * @var int - */ - private $value; - - /** - * @Contract\Ensure("$this->value !== 0") - * @param int $variable - */ - public function add(int $variable): void - { - $this->value += $variable; - } -} diff --git a/tests/Functional/Ensure/InterfacePropagation/StubInterfaceA.php b/tests/Functional/Ensure/InterfacePropagation/StubInterfaceA.php deleted file mode 100644 index df5fec9..0000000 --- a/tests/Functional/Ensure/InterfacePropagation/StubInterfaceA.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -interface StubInterfaceA -{ - /** - * @Contract\Ensure("$this->value !== -1") - * @param int $variable - */ - public function add(int $variable): void; -} diff --git a/tests/Functional/Ensure/InterfacePropagation/StubInterfaceB.php b/tests/Functional/Ensure/InterfacePropagation/StubInterfaceB.php deleted file mode 100644 index a9e1a5a..0000000 --- a/tests/Functional/Ensure/InterfacePropagation/StubInterfaceB.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -interface StubInterfaceB -{ - /** - * @Contract\Ensure("$this->value !== -2") - * @param int $variable - */ - public function add(int $variable): void; -} diff --git a/tests/Functional/Ensure/Stub.php b/tests/Functional/Ensure/Stub.php deleted file mode 100644 index e2ebbee..0000000 --- a/tests/Functional/Ensure/Stub.php +++ /dev/null @@ -1,65 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Ensure; - -use PhpDeal\Annotation as Contract; -use Go\Lang\Annotation\Pointcut; - -class Stub -{ - private $privateValue = 42; - - /** - * Method that changes internal state and ensures a contract for this - * @param float $amount - * - * @Contract\Ensure("$this->privateValue === $__old->privateValue + $amount") - * @Contract\Ensure("$this->privateValue > 0") - */ - public function increment(float $amount): void - { - $this->privateValue += $amount; - } - - /** - * BAD Method that changes internal state and ensures a contract for this - * @param float $amount - * - * @Contract\Ensure("$this->privateValue === $__old->privateValue + $amount") - */ - public function badIncrement(float $amount): void - { - $this->privateValue += ($amount - 0.1); // Dirty hacker wants to earn money! - } - - /** - * Let's check that this getter is not cheating - * - * @Contract\Ensure("$__result === $this->privateValue") - */ - public function returnPrivateValue(): int - { - return $this->privateValue; - } - - /** - * Let's check that aspect doesn't pay an attention to unknown annotations - * - * @Contract\Ensure("$__result === $this->privateValue") - * @Pointcut("") - */ - public function unknown(): void - { - } -} diff --git a/tests/Functional/EnsureTest.php b/tests/Functional/EnsureTest.php new file mode 100644 index 0000000..331d1a0 --- /dev/null +++ b/tests/Functional/EnsureTest.php @@ -0,0 +1,92 @@ +counter = new Counter(); + } + + public function testPostconditionsHold(): void + { + $this->counter->increment(50); + + self::assertSame(92.0, $this->counter->getValue()); + } + + public function testEveryPostconditionIsChecked(): void + { + $this->expectException(PostconditionViolation::class); + $this->expectExceptionMessage('Postcondition "$this->value > 0" violated'); + $this->counter->increment(-50); + } + + public function testOldStateIsAvailable(): void + { + $this->expectException(PostconditionViolation::class); + $this->expectExceptionMessage('$this->value === $__old->value + $amount'); + $this->counter->badIncrement(40); + } + + public function testResultIsAvailable(): void + { + $this->expectException(PostconditionViolation::class); + $this->expectExceptionMessage('$__result === $this->value'); + $this->counter->cheatingGetter(); + } + + public function testObjectIsClonedOnlyWhenOldStateIsUsed(): void + { + $this->counter->withoutOldState(); + self::assertSame(0, $this->counter->clones); + + $this->counter->increment(1); + self::assertSame(0, $this->counter->clones, 'The clone is taken, the original is not changed'); + } + + public function testStaticMethodsAreChecked(): void + { + self::assertSame('value', Counter::staticFactory()); + } + + #[TestWith([50])] + public function testPostconditionsOfTheHierarchyHold(int $value): void + { + $counter = new ChildCounter(); + $counter->add($value); + + $this->addToAssertionCount(1); + } + + #[TestWith([1], 'own contract')] + #[TestWith([2], 'parent contract')] + #[TestWith([-1], 'grandparent contract')] + public function testPostconditionsAreInheritedFromParents(int $value): void + { + $this->expectException(PostconditionViolation::class); + new ChildCounter()->add($value); + } + + #[TestWith([-1], 'contract of the first interface')] + #[TestWith([-2], 'contract of the second interface')] + public function testPostconditionsAreInheritedFromInterfaces(int $value): void + { + $this->expectException(PostconditionViolation::class); + new InterfaceCounter()->add($value); + } +} diff --git a/tests/Functional/Inherit/ContractTest.php b/tests/Functional/Inherit/ContractTest.php deleted file mode 100644 index 578724c..0000000 --- a/tests/Functional/Inherit/ContractTest.php +++ /dev/null @@ -1,45 +0,0 @@ -stubWithoutInherit = new StubWithoutInherit(); - $this->stubWithInherit = new StubWithInherit(); - } - - protected function tearDown(): void - { - unset($this->stubWithoutInherit, $this->stubWithInherit); - } - - public function testWithoutInheritIsValid(): void - { - $this->stubWithoutInherit->add(0); - $this->assertEquals(10, $this->stubWithoutInherit->getAmount()); - } - - /** - * @expectedException \PhpDeal\Exception\ContractViolation - * @return void - */ - public function testWithInheritInvalid(): void - { - $this->stubWithInherit->add(0); - } - - public function testWithInheritValid(): void - { - $this->stubWithInherit->add(10); - $this->assertEquals(10, $this->stubWithInherit->getAmount()); - } -} diff --git a/tests/Functional/Inherit/StubInterface.php b/tests/Functional/Inherit/StubInterface.php deleted file mode 100644 index 6266e25..0000000 --- a/tests/Functional/Inherit/StubInterface.php +++ /dev/null @@ -1,20 +0,0 @@ - 0 && is_numeric($amount)") - * @param integer $amount - * @return void - */ - public function add($amount); - - /** - * @Contract\Ensure("$__result === $this->amount") - */ - public function getAmount(); -} diff --git a/tests/Functional/Inherit/StubWithInherit.php b/tests/Functional/Inherit/StubWithInherit.php deleted file mode 100644 index f6157bf..0000000 --- a/tests/Functional/Inherit/StubWithInherit.php +++ /dev/null @@ -1,29 +0,0 @@ -amount += $amount; - } - - /** - * @Contract\Inherit() - * @return integer - */ - public function getAmount() - { - return $this->amount; - } -} diff --git a/tests/Functional/Inherit/StubWithoutInherit.php b/tests/Functional/Inherit/StubWithoutInherit.php deleted file mode 100644 index 8df7f7e..0000000 --- a/tests/Functional/Inherit/StubWithoutInherit.php +++ /dev/null @@ -1,18 +0,0 @@ -amount = $amount; - } - - public function getAmount() - { - return 10; - } -} diff --git a/tests/Functional/InheritTest.php b/tests/Functional/InheritTest.php new file mode 100644 index 0000000..fedaa6a --- /dev/null +++ b/tests/Functional/InheritTest.php @@ -0,0 +1,75 @@ +add(-10); + + self::assertSame(-10, $wallet->getAmount()); + } + + public function testMethodInheritsContracts(): void + { + $wallet = new WalletWithMethodInheritance(); + $wallet->add(10); + + self::assertSame(10, $wallet->getAmount()); + } + + public function testInheritedPreconditionIsCheckedBeforeTheBody(): void + { + $wallet = new WalletWithMethodInheritance(); + try { + $wallet->add(0); + self::fail('A violation was expected'); + } catch (PreconditionViolation) { + self::assertSame(0, $wallet->bodyCalls, 'The method body must not run'); + } + } + + public function testInheritedPostconditionIsChecked(): void + { + $this->expectException(PostconditionViolation::class); + new BuggyWallet()->add(5); + } + + public function testMethodInheritanceDoesNotEnableInvariants(): void + { + $wallet = new WalletWithMethodInheritance(); + $wallet->forceAmount(-1); + + self::assertSame(-1, $wallet->getAmount()); + } + + public function testClassInheritsContractsOfEveryMethod(): void + { + $wallet = new WalletWithClassInheritance(); + $wallet->add(5); + self::assertSame(5, $wallet->getAmount()); + + $this->expectException(PreconditionViolation::class); + $wallet->add(-5); + } + + public function testClassInheritsInvariants(): void + { + $this->expectException(InvariantViolation::class); + $this->expectExceptionMessage('Invariant "$this->getAmount() >= 0"'); + new WalletWithClassInheritance()->forceAmount(-1); + } +} diff --git a/tests/Functional/Invariant/ClassPropagation/ContractTest.php b/tests/Functional/Invariant/ClassPropagation/ContractTest.php deleted file mode 100644 index 566b1b4..0000000 --- a/tests/Functional/Invariant/ClassPropagation/ContractTest.php +++ /dev/null @@ -1,87 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Invariant\ClassPropagation; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -/** - * @group propagation - */ -class ContractTest extends TestCase -{ - /** - * @var Stub - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new Stub(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function providerInvariantValid(): array - { - return [ - [ - 'variable' => 4 - ] - ]; - } - - /** - * @param int $variable - * @dataProvider providerInvariantValid - */ - public function testInvariantValid(int $variable): void - { - $this->expectNotToPerformAssertions(); - $this->stub->setVariable($variable); - } - - public function providerInvariantInvalid(): array - { - return [ - [ - // restriction of Stub - 'variable' => 1 - ], - [ - // restriction of StubParent - 'variable' => 2 - ], - [ - // restriction of StubGrandparent - 'variable' => 3 - ], - ]; - } - - /** - * @param int $variable - * @dataProvider providerInvariantInvalid - */ - public function testInvariantInvalid(int $variable): void - { - $this->expectException(ContractViolation::class); - $this->stub->setVariable($variable); - } -} diff --git a/tests/Functional/Invariant/ClassPropagation/Stub.php b/tests/Functional/Invariant/ClassPropagation/Stub.php deleted file mode 100644 index 82020ab..0000000 --- a/tests/Functional/Invariant/ClassPropagation/Stub.php +++ /dev/null @@ -1,30 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Invariant\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -/** - * @Contract\Invariant("$this->variable !== 1") - */ -class Stub extends StubParent -{ - /** - * @param int $variable - */ - public function setVariable(int $variable): void - { - $this->variable = $variable; - } -} diff --git a/tests/Functional/Invariant/ClassPropagation/StubGrandparent.php b/tests/Functional/Invariant/ClassPropagation/StubGrandparent.php deleted file mode 100644 index f56a0c7..0000000 --- a/tests/Functional/Invariant/ClassPropagation/StubGrandparent.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -namespace PhpDeal\Functional\Invariant\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -/** - * @Contract\Invariant("$this->variable !== 3") - */ -abstract class StubGrandparent -{ - /** - * @var int - */ - public $variable; -} diff --git a/tests/Functional/Invariant/ClassPropagation/StubParent.php b/tests/Functional/Invariant/ClassPropagation/StubParent.php deleted file mode 100644 index 4f40f89..0000000 --- a/tests/Functional/Invariant/ClassPropagation/StubParent.php +++ /dev/null @@ -1,22 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -namespace PhpDeal\Functional\Invariant\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -/** - * @Contract\Invariant("$this->variable !== 2") - */ -abstract class StubParent extends StubGrandparent -{ - -} diff --git a/tests/Functional/Invariant/ContractTest.php b/tests/Functional/Invariant/ContractTest.php deleted file mode 100644 index 77cc20e..0000000 --- a/tests/Functional/Invariant/ContractTest.php +++ /dev/null @@ -1,56 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Invariant; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -class ContractTest extends TestCase -{ - /** - * @var Stub - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new Stub(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function testInvariantValid(): void - { - $this->expectNotToPerformAssertions(); - $this->stub->accelerate(10, 30); // let's have a speed 300m/s - } - - public function testInvariantViolated(): void - { - $this->expectException(ContractViolation::class); - $this->stub->accelerate(10, 3e7); // let's have a speed 3*1e8 m/s, faster than light! - } - - public function testInvariantViolatedAfterSeveralMethods(): void - { - $this->expectException(ContractViolation::class); - $this->stub->accelerate(10, 30); // let's have a speed 300m/s - $this->stub->decelerate(20, 20); // Negative speed? - } -} diff --git a/tests/Functional/Invariant/InterfacePropagation/ContractTest.php b/tests/Functional/Invariant/InterfacePropagation/ContractTest.php deleted file mode 100644 index 9d81dd8..0000000 --- a/tests/Functional/Invariant/InterfacePropagation/ContractTest.php +++ /dev/null @@ -1,87 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Invariant\InterfacePropagation; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -/** - * @group propagation - */ -class ContractTest extends TestCase -{ - /** - * @var Stub - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new Stub(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function providerInvariantValid(): array - { - return [ - [ - 'variable' => 4 - ] - ]; - } - - /** - * @param int $variable - * @dataProvider providerInvariantValid - */ - public function testInvariantValid(int $variable): void - { - $this->expectNotToPerformAssertions(); - $this->stub->setVariable($variable); - } - - public function providerInvariantInvalid(): array - { - return [ - [ - // restriction of Stub - 'variable' => 1 - ], - [ - // restriction of StubInterfaceA - 'variable' => 2 - ], - [ - // restriction of StubInterfaceB - 'variable' => 3 - ], - ]; - } - - /** - * @param int $variable - * @dataProvider providerInvariantInvalid - */ - public function testInvariantInvalid($variable): void - { - $this->expectException(ContractViolation::class); - $this->stub->setVariable($variable); - } -} diff --git a/tests/Functional/Invariant/InterfacePropagation/Stub.php b/tests/Functional/Invariant/InterfacePropagation/Stub.php deleted file mode 100644 index 0d25f9f..0000000 --- a/tests/Functional/Invariant/InterfacePropagation/Stub.php +++ /dev/null @@ -1,35 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Invariant\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -/** - * @Contract\Invariant("$this->variable !== 1") - */ -class Stub implements StubInterfaceA, StubInterfaceB -{ - /** - * @var int - */ - public $variable; - - /** - * @param int $variable - */ - public function setVariable(int $variable) - { - $this->variable = $variable; - } -} diff --git a/tests/Functional/Invariant/InterfacePropagation/StubInterfaceA.php b/tests/Functional/Invariant/InterfacePropagation/StubInterfaceA.php deleted file mode 100644 index 65a17e2..0000000 --- a/tests/Functional/Invariant/InterfacePropagation/StubInterfaceA.php +++ /dev/null @@ -1,24 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Invariant\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -/** - * @Contract\Invariant("$this->variable !== 2") - */ -interface StubInterfaceA -{ - -} diff --git a/tests/Functional/Invariant/InterfacePropagation/StubInterfaceB.php b/tests/Functional/Invariant/InterfacePropagation/StubInterfaceB.php deleted file mode 100644 index 2bd6054..0000000 --- a/tests/Functional/Invariant/InterfacePropagation/StubInterfaceB.php +++ /dev/null @@ -1,24 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Invariant\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -/** - * @Contract\Invariant("$this->variable !== 3") - */ -interface StubInterfaceB -{ - -} diff --git a/tests/Functional/Invariant/Stub.php b/tests/Functional/Invariant/Stub.php deleted file mode 100644 index 7ea5c51..0000000 --- a/tests/Functional/Invariant/Stub.php +++ /dev/null @@ -1,50 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Invariant; - -use Go\Lang\Annotation\Aspect; -use PhpDeal\Annotation as Contract; - -/** - * Physic invariant - speed of subject, can not be greater than speed of light in vacuum - * - * @Contract\Invariant("$this->speed < 299792458 && $this->speed >= 0") - * @Aspect("") // Just unused annotation - */ -class Stub -{ - private $speed = 0; - - /** - * Accelerate - * - * @param float $acceleration - * @param float $time - */ - public function accelerate(float $acceleration, float $time): void - { - $this->speed += ($acceleration * $time); - } - - /** - * Decelerate - * - * @param float $decelaration - * @param float $time - */ - public function decelerate(float $decelaration, float $time): void - { - $this->speed -= ($decelaration * $time); - } -} diff --git a/tests/Functional/InvariantTest.php b/tests/Functional/InvariantTest.php new file mode 100644 index 0000000..b247026 --- /dev/null +++ b/tests/Functional/InvariantTest.php @@ -0,0 +1,87 @@ +accelerate(10, 30); + + self::assertSame(300.0, $particle->getSpeed()); + } + + public function testInvariantIsCheckedAfterTheConstructor(): void + { + try { + $speed = new Particle(-1)->getSpeed(); + self::fail('A violation was expected, but the speed is ' . $speed); + } catch (InvariantViolation $violation) { + self::assertStringEndsWith('->__construct(-1.0)', $violation->getMessage()); + } + } + + public function testInvariantIsCheckedAfterEveryPublicMethod(): void + { + $this->expectException(InvariantViolation::class); + new Particle()->accelerate(10, 3e7); // faster than light! + } + + public function testInvariantIsCheckedAfterSeveralMethods(): void + { + $particle = new Particle(); + $particle->accelerate(10, 30); + + $this->expectException(InvariantViolation::class); + $particle->decelerate(20, 20); // negative speed + } + + public function testInvariantCanCallPublicMethodsOfItsClass(): void + { + $particle = new SelfCheckingParticle(); + $particle->setSpeed(10); + self::assertSame(10.0, $particle->getSpeed()); + + $this->expectException(InvariantViolation::class); + $particle->setSpeed(-1); + } + + public function testInheritedInvariantsHold(): void + { + $value = new ChildValue(); + $value->setValue(4); + + self::assertSame(4, $value->value); + } + + #[TestWith([1], 'own invariant')] + #[TestWith([2], 'parent invariant')] + #[TestWith([3], 'grandparent invariant')] + public function testInvariantsAreInheritedFromParents(int $value): void + { + $this->expectException(InvariantViolation::class); + new ChildValue()->setValue($value); + } + + #[TestWith([1], 'own invariant')] + #[TestWith([2], 'invariant of the first interface')] + #[TestWith([3], 'invariant of the second interface')] + public function testInvariantsAreInheritedFromInterfaces(int $value): void + { + $this->expectException(InvariantViolation::class); + new InterfaceValue()->setValue($value); + } +} diff --git a/tests/Functional/Verify/ClassPropagation/ContractTest.php b/tests/Functional/Verify/ClassPropagation/ContractTest.php deleted file mode 100644 index 9ef6c3b..0000000 --- a/tests/Functional/Verify/ClassPropagation/ContractTest.php +++ /dev/null @@ -1,80 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\ClassPropagation; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -/** - * @group propagation - */ -class ContractTest extends TestCase -{ - /** - * @var Stub - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new Stub(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function providerVerifyInvalid(): array - { - return [ - [ - // Stub can't accept this value - 'parameter' => 1 - ] - ]; - } - - /** - * @param int $parameter - * @dataProvider providerVerifyInvalid - */ - public function testVerifyInvalid(int $parameter): void - { - $this->expectException(ContractViolation::class); - $this->stub->add($parameter); - } - - public function providerVerifyValid(): array - { - return [ - [ - // StubParent does not accept this parameter, but Stub accepts (and we don't have inheritdoc annotation) - 'parameter' => 2 - ] - ]; - } - - /** - * @param int $parameter - * @dataProvider providerVerifyValid - */ - public function testVerifyValid(int $parameter): void - { - $this->expectNotToPerformAssertions(); - $this->stub->add($parameter); - } -} diff --git a/tests/Functional/Verify/ClassPropagation/ContractWithInheritDocTest.php b/tests/Functional/Verify/ClassPropagation/ContractWithInheritDocTest.php deleted file mode 100644 index a1e6a58..0000000 --- a/tests/Functional/Verify/ClassPropagation/ContractWithInheritDocTest.php +++ /dev/null @@ -1,88 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\ClassPropagation; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -/** - * @group propagation - * @group inheritdoc - */ -class ContractWithInheritDocTest extends TestCase -{ - /** - * @var StubWithInheritDoc - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new StubWithInheritDoc(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function providerVerifyInvalid(): array - { - return [ - [ - // Stub can't accept this value - 'parameter' => 1 - ], - [ - // StubParentWithInheritDoc can't accept this value - 'parameter' => 2 - ], - [ - // StubGrandparent can't accept this value - 'parameter' => 3 - ] - ]; - } - - /** - * @param int $parameter - * @dataProvider providerVerifyInvalid - */ - public function testVerifyInvalid(int $parameter): void - { - $this->expectException(ContractViolation::class); - $this->stub->add($parameter); - } - - public function providerVerifyValid(): array - { - return [ - [ - 'parameter' => 4 - ] - ]; - } - - /** - * @param int $parameter - * @dataProvider providerVerifyValid - */ - public function testVerifyValid(int $parameter): void - { - $this->expectNotToPerformAssertions(); - $this->stub->add($parameter); - } -} diff --git a/tests/Functional/Verify/ClassPropagation/Stub.php b/tests/Functional/Verify/ClassPropagation/Stub.php deleted file mode 100644 index fa319af..0000000 --- a/tests/Functional/Verify/ClassPropagation/Stub.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -class Stub extends StubParent -{ - /** - * @param int $variable - * @Contract\Verify("$variable !== 1") - */ - public function add(int $variable): void - { - } -} diff --git a/tests/Functional/Verify/ClassPropagation/StubGrandparent.php b/tests/Functional/Verify/ClassPropagation/StubGrandparent.php deleted file mode 100644 index e8893c2..0000000 --- a/tests/Functional/Verify/ClassPropagation/StubGrandparent.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -class StubGrandparent -{ - /** - * @param int $variable - * @Contract\Verify("$variable !== 3") - */ - public function add(int $variable): void - { - } -} diff --git a/tests/Functional/Verify/ClassPropagation/StubParent.php b/tests/Functional/Verify/ClassPropagation/StubParent.php deleted file mode 100644 index 6f76129..0000000 --- a/tests/Functional/Verify/ClassPropagation/StubParent.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -abstract class StubParent -{ - /** - * @param int $variable - * @Contract\Verify("$variable !== 2") - */ - public function add(int $variable): void - { - } -} diff --git a/tests/Functional/Verify/ClassPropagation/StubParentWithInheritDoc.php b/tests/Functional/Verify/ClassPropagation/StubParentWithInheritDoc.php deleted file mode 100644 index 03995cc..0000000 --- a/tests/Functional/Verify/ClassPropagation/StubParentWithInheritDoc.php +++ /dev/null @@ -1,28 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -abstract class StubParentWithInheritDoc extends StubGrandparent -{ - /** - * @param int $variable - * @Contract\Verify("$variable !== 2") - * @inheritdoc - */ - public function add(int $variable): void - { - } -} diff --git a/tests/Functional/Verify/ClassPropagation/StubWithInheritDoc.php b/tests/Functional/Verify/ClassPropagation/StubWithInheritDoc.php deleted file mode 100644 index 093c952..0000000 --- a/tests/Functional/Verify/ClassPropagation/StubWithInheritDoc.php +++ /dev/null @@ -1,28 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\ClassPropagation; - -use PhpDeal\Annotation as Contract; - -class StubWithInheritDoc extends StubParentWithInheritDoc -{ - /** - * @param int $variable - * @Contract\Verify("$variable !== 1") - * {@inheritdoc} - */ - public function add(int $variable): void - { - } -} diff --git a/tests/Functional/Verify/ContractTest.php b/tests/Functional/Verify/ContractTest.php deleted file mode 100644 index 95ba6ec..0000000 --- a/tests/Functional/Verify/ContractTest.php +++ /dev/null @@ -1,94 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -class ContractTest extends TestCase -{ - /** - * @var Stub - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new Stub(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function testVerifyValid(): void - { - $this->expectNotToPerformAssertions(); - $this->stub->testNumeric(-200); - } - - public function testAccessToPrivateFields(): void - { - $this->expectNotToPerformAssertions(); - $this->stub->testAccessToPrivateField(50); - } - - public function testVerifyWithAssertValid(): void - { - $this->expectNotToPerformAssertions(); - $this->stub->add(100); - } - - /** - * This test should fail with php TypeError. - */ - public function testVerifyWithAssertInvalid(): void - { - $this->expectException(ContractViolation::class); - $this->stub->add(1); - } - - public function testVerifyManyContractsValid(): void - { - $this->expectNotToPerformAssertions(); - $this->stub->sub(9); - } - - public function providerVerifyManyContractsInvalid(): array - { - return [ - [ - 'value' => 11 - ], - [ - 'value' => 1 - ], - ]; - } - - /** - * This test should fail with php TypeError. - * - * @param mixed $value - * @dataProvider providerVerifyManyContractsInvalid - */ - public function testVerifyManyContractsInvalid($value): void - { - $this->expectException(ContractViolation::class); - $this->stub->sub(1); - } -} diff --git a/tests/Functional/Verify/InterfacePropagation/ContractTest.php b/tests/Functional/Verify/InterfacePropagation/ContractTest.php deleted file mode 100644 index 832ba85..0000000 --- a/tests/Functional/Verify/InterfacePropagation/ContractTest.php +++ /dev/null @@ -1,86 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\InterfacePropagation; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -/** - * @group propagation - */ -class ContractTest extends TestCase -{ - /** - * @var Stub - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new Stub(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function providerVerifyInvalid(): array - { - return [ - [ - // Stub can't accept this value - 'parameter' => 1 - ] - ]; - } - - /** - * @param int $parameter - * @dataProvider providerVerifyInvalid - */ - public function testVerifyInvalid(int $parameter): void - { - $this->expectException(ContractViolation::class); - $this->stub->add($parameter); - } - - public function providerVerifyValid(): array - { - return [ - [ - // StubInterfaceA does not accept this parameter, - // but Stub accepts (and we don't have inheritdoc annotation) - 'parameter' => 2 - ], - [ - // StubInterfaceB does not accept this parameter, - // but Stub accepts (and we don't have inheritdoc annotation) - 'parameter' => 3 - ] - ]; - } - - /** - * @param int $parameter - * @dataProvider providerVerifyValid - */ - public function testVerifyValid(int $parameter): void - { - $this->expectNotToPerformAssertions(); - $this->stub->add($parameter); - } -} diff --git a/tests/Functional/Verify/InterfacePropagation/ContractWithInheritDocTest.php b/tests/Functional/Verify/InterfacePropagation/ContractWithInheritDocTest.php deleted file mode 100644 index b6bbbca..0000000 --- a/tests/Functional/Verify/InterfacePropagation/ContractWithInheritDocTest.php +++ /dev/null @@ -1,88 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\InterfacePropagation; - -use PhpDeal\Exception\ContractViolation; -use PHPUnit\Framework\TestCase; - -/** - * @group propagation - * @group inheritdoc - */ -class ContractWithInheritDocTest extends TestCase -{ - /** - * @var StubWithInheritDoc - */ - private $stub; - - protected function setUp(): void - { - parent::setUp(); - $this->stub = new StubWithInheritDoc(); - } - - protected function tearDown(): void - { - unset($this->stub); - parent::tearDown(); - } - - public function providerVerifyInvalid(): array - { - return [ - [ - // Stub can't accept this value - 'parameter' => 1 - ], - [ - // StubInterfaceA can't accept this value - 'parameter' => 2 - ], - [ - // StubInterfaceB can't accept this value - 'parameter' => 3 - ] - ]; - } - - /** - * @param int $parameter - * @dataProvider providerVerifyInvalid - */ - public function testVerifyInvalid(int $parameter): void - { - $this->expectException(ContractViolation::class); - $this->stub->add($parameter); - } - - public function providerVerifyValid(): array - { - return [ - [ - 'parameter' => 4 - ] - ]; - } - - /** - * @param int $parameter - * @dataProvider providerVerifyValid - */ - public function testVerifyValid(int $parameter): void - { - $this->expectNotToPerformAssertions(); - $this->stub->add($parameter); - } -} diff --git a/tests/Functional/Verify/InterfacePropagation/Stub.php b/tests/Functional/Verify/InterfacePropagation/Stub.php deleted file mode 100644 index f02abc9..0000000 --- a/tests/Functional/Verify/InterfacePropagation/Stub.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -class Stub implements StubInterfaceA, StubInterfaceB -{ - /** - * @param int $variable - * @Contract\Verify("$variable !== 1") - */ - public function add(int $variable): void - { - } -} diff --git a/tests/Functional/Verify/InterfacePropagation/StubInterfaceA.php b/tests/Functional/Verify/InterfacePropagation/StubInterfaceA.php deleted file mode 100644 index 131f10d..0000000 --- a/tests/Functional/Verify/InterfacePropagation/StubInterfaceA.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -interface StubInterfaceA -{ - /** - * @param int $variable - * @Contract\Verify("$variable !== 2") - */ - public function add(int $variable): void; -} diff --git a/tests/Functional/Verify/InterfacePropagation/StubInterfaceB.php b/tests/Functional/Verify/InterfacePropagation/StubInterfaceB.php deleted file mode 100644 index e548657..0000000 --- a/tests/Functional/Verify/InterfacePropagation/StubInterfaceB.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -interface StubInterfaceB -{ - /** - * @param int $variable - * @Contract\Verify("$variable !== 3") - */ - public function add(int $variable): void; -} diff --git a/tests/Functional/Verify/InterfacePropagation/StubWithInheritDoc.php b/tests/Functional/Verify/InterfacePropagation/StubWithInheritDoc.php deleted file mode 100644 index 21ebf8d..0000000 --- a/tests/Functional/Verify/InterfacePropagation/StubWithInheritDoc.php +++ /dev/null @@ -1,28 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify\InterfacePropagation; - -use PhpDeal\Annotation as Contract; - -class StubWithInheritDoc implements StubInterfaceA, StubInterfaceB -{ - /** - * @param int $variable - * @Contract\Verify("$variable !== 1") - * {@inheritdoc} - */ - public function add(int $variable): void - { - } -} diff --git a/tests/Functional/Verify/Stub.php b/tests/Functional/Verify/Stub.php deleted file mode 100644 index 7125cf3..0000000 --- a/tests/Functional/Verify/Stub.php +++ /dev/null @@ -1,71 +0,0 @@ - - * - * This source file is subject to the license that is bundled - * with this source code in the file LICENSE. - */ - -declare(strict_types=1); - -namespace PhpDeal\Functional\Verify; - -use PhpDeal\Annotation as Contract; -use Go\Lang\Annotation\Pointcut; - -class Stub -{ - private $privateValue = 42; - - /** - * Method with numeric parameter requirement - * - * @param float $variable - * @Contract\Verify("\is_numeric($variable)") - * @return float - */ - public function testNumeric(float $variable): float - { - return $variable; - } - - - /** - * Method with contract that access a private variable - * - * @param float $variable - * @Contract\Verify("$variable > $this->privateValue") - * @Pointcut("") - */ - public function testAccessToPrivateField($variable): void - { - } - - /** - * Method with contract integrated with beberlei/assert library - * - * @param int $value - * @return bool - * @Contract\Verify("Assert\Assertion::greaterThan($value, 5)") - */ - public function add(int $value): bool - { - return true; - } - - /** - * Method with many contracts - * - * @param int $value - * @return bool - * @Contract\Verify("$value < 10") - * @Contract\Verify("$value > 5") - */ - public function sub(int $value): bool - { - return true; - } -} diff --git a/tests/Functional/VerifyTest.php b/tests/Functional/VerifyTest.php new file mode 100644 index 0000000..7b49567 --- /dev/null +++ b/tests/Functional/VerifyTest.php @@ -0,0 +1,224 @@ +account = new Account(); + } + + #[DoesNotPerformAssertions] + public function testValidPreconditionLetsTheCallThrough(): void + { + $this->account->numeric(-200); + } + + public function testPreconditionIsCheckedBeforeTheBody(): void + { + $this->expectException(PreconditionViolation::class); + $this->expectExceptionMessage('Precondition "$amount > $this->limit" violated in ' . Account::class . '->aboveLimit(42)'); + + $this->account->aboveLimit(42); + } + + #[DoesNotPerformAssertions] + public function testContractCanReadPrivateState(): void + { + $this->account->aboveLimit(50); + } + + #[DoesNotPerformAssertions] + public function testAssertionLibraryCanBeUsed(): void + { + $this->account->withAssertion(100); + } + + public function testFailedAssertionIsReportedAsViolation(): void + { + try { + $this->account->withAssertion(1); + self::fail('A violation was expected'); + } catch (PreconditionViolation $violation) { + self::assertInstanceOf(\Assert\InvalidArgumentException::class, $violation->getPrevious()); + self::assertStringContainsString('is not greater than', $violation->getMessage()); + } + } + + #[DoesNotPerformAssertions] + public function testEveryRepeatedContractHolds(): void + { + $this->account->between(9); + } + + #[TestWith([11])] + #[TestWith([1])] + public function testEveryRepeatedContractIsChecked(int $amount): void + { + $this->expectException(PreconditionViolation::class); + $this->account->between($amount); + } + + #[DoesNotPerformAssertions] + public function testDefaultValuesAreAvailable(): void + { + $this->account->withDefault(10); + } + + public function testVariadicArgumentsAreCollected(): void + { + $this->account->variadic(1, 2, 3); + + $this->expectException(PreconditionViolation::class); + $this->account->variadic(1, -2); + } + + public function testEmptyVariadicArgumentsAreAnEmptyList(): void + { + $this->expectException(PreconditionViolation::class); + $this->account->variadic(); + } + + public function testStaticMethodContractsUseClassScope(): void + { + Account::staticMethod(10); + + $this->expectException(PreconditionViolation::class); + $this->expectExceptionMessage(Account::class . '::staticMethod(1)'); + Account::staticMethod(1); + } + + public function testThisInStaticMethodIsAnInvalidContract(): void + { + $this->expectException(InvalidContractException::class); + $this->expectExceptionMessage('uses $this, but the method is static'); + Account::staticWithThis(100); + } + + public function testSyntaxErrorIsAnInvalidContract(): void + { + $this->expectException(InvalidContractException::class); + $this->expectExceptionMessage('Contract "$amount >" of ' . Account::class . '::syntaxError() can not be compiled'); + $this->account->syntaxError(1); + } + + public function testNonBooleanResultIsAnInvalidContract(): void + { + $this->expectException(InvalidContractException::class); + $this->expectExceptionMessage('must return a boolean or null (for assertions), int returned'); + $this->account->notBoolean(1); + } + + public function testErrorInsideExpressionIsReportedAsViolation(): void + { + try { + $this->account->brokenExpression(); + self::fail('A violation was expected'); + } catch (PreconditionViolation $violation) { + self::assertInstanceOf(Error::class, $violation->getPrevious()); + } + } + + public function testTrailingCommentDoesNotBreakTheExpression(): void + { + $this->account->withComment(1); + + $this->expectException(PreconditionViolation::class); + $this->account->withComment(0); + } + + public function testContractCanCallPrivateMethods(): void + { + $this->account->guarded(2); + + $this->expectException(PreconditionViolation::class); + $this->account->guarded(3); + } + + public function testViolationPointsToTheMethodDeclaration(): void + { + try { + $this->account->aboveLimit(1); + self::fail('A violation was expected'); + } catch (ContractViolation $violation) { + self::assertSame('aboveLimit', $violation->methodName); + self::assertSame(Account::class, $violation->className); + self::assertSame('$amount > $this->limit', $violation->contract); + self::assertStringEndsWith('Fixtures/Verify/Account.php', $violation->getFile()); + self::assertSame(23, $violation->getLine()); + } + } + + /** + * @return iterable + */ + public static function providerInheritance(): iterable + { + yield 'own contract of a subclass' => [new ChildWithoutInheritance(), 1]; + yield 'own contract with {@inheritdoc}' => [new ChildWithInheritDoc(), 1]; + yield 'parent contract with @inheritDoc' => [new ChildWithInheritDoc(), 2]; + yield 'grandparent contract' => [new ChildWithInheritDoc(), 3]; + yield 'own contract of an implementation' => [new RangeWithoutInheritance(), 1]; + yield 'first interface with {@inheritdoc}' => [new RangeWithInheritDoc(), 2]; + yield 'second interface with {@inheritdoc}' => [new RangeWithInheritDoc(), 3]; + } + + #[DataProvider('providerInheritance')] + public function testInheritedPreconditionsAreChecked(object $subject, int $value): void + { + self::assertTrue(\method_exists($subject, 'add')); + + $this->expectException(PreconditionViolation::class); + $subject->add($value); + } + + /** + * @return iterable + */ + public static function providerNoInheritance(): iterable + { + yield 'parent contract is not inherited by default' => [new ChildWithoutInheritance(), 2]; + yield 'interface A contract is not inherited by default' => [new RangeWithoutInheritance(), 2]; + yield 'interface B contract is not inherited by default' => [new RangeWithoutInheritance(), 3]; + yield 'value valid for the whole hierarchy' => [new ChildWithInheritDoc(), 4]; + } + + #[DataProvider('providerNoInheritance')] + public function testPreconditionsOfParentsAreOptIn(object $subject, int $value): void + { + self::assertTrue(\method_exists($subject, 'add')); + $subject->add($value); + } + + public function testParentContractIsEvaluatedInParentScope(): void + { + $child = new PrivateChild(); + $child->set(10); + + $this->expectException(PreconditionViolation::class); + $this->expectExceptionMessage('$value >= $this->minimum'); + $child->set(9); + } +} diff --git a/tests/Unit/Attribute/AttributeTest.php b/tests/Unit/Attribute/AttributeTest.php new file mode 100644 index 0000000..be3bfc7 --- /dev/null +++ b/tests/Unit/Attribute/AttributeTest.php @@ -0,0 +1,55 @@ +getAttributes(Attribute::class); + + self::assertCount(1, $attributes); + self::assertSame($flags, $attributes[0]->newInstance()->flags); + } + + /** + * @return iterable + */ + public static function providerContracts(): iterable + { + yield 'verify' => [new Verify('$a > 0')]; + yield 'ensure' => [new Ensure('$a > 0')]; + yield 'invariant' => [new Invariant('$a > 0')]; + } + + #[DataProvider('providerContracts')] + public function testContractsExposeTheirExpression(Contract $contract): void + { + self::assertSame('$a > 0', $contract->expression); + } +} diff --git a/tests/Unit/Contract/ContractEvaluatorTest.php b/tests/Unit/Contract/ContractEvaluatorTest.php new file mode 100644 index 0000000..86906a6 --- /dev/null +++ b/tests/Unit/Contract/ContractEvaluatorTest.php @@ -0,0 +1,160 @@ +evaluator = new ContractEvaluator(); + } + + public function testArgumentsAreKeyedByName(): void + { + $invocation = FakeInvocation::on(new Square(), 'withParameters', 1, 2, 3, 4); + + self::assertSame(['a' => 1, 'b' => 2, 'rest' => [3, 4]], $this->evaluator->getArguments($invocation)); + } + + public function testMissingArgumentsUseDefaults(): void + { + $invocation = FakeInvocation::on(new Square(), 'withParameters', 1); + + self::assertSame(['a' => 1, 'b' => 5, 'rest' => []], $this->evaluator->getArguments($invocation)); + } + + public function testHoldingContractsPass(): void + { + $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); + $contracts = [ + new BoundContract(new Verify('$factor === 2.0'), Square::class), + new BoundContract(new Verify('$this->size === 2'), Square::class), + new BoundContract(new Verify('null'), Square::class), + ]; + + $this->evaluator->check($invocation, $contracts, ['factor' => 2.0], ContractKind::Precondition); + + self::assertFalse($this->evaluator->isEvaluating()); + } + + /** + * @param class-string $violationClass + */ + #[TestWith([ContractKind::Precondition, PreconditionViolation::class])] + #[TestWith([ContractKind::Postcondition, PostconditionViolation::class])] + #[TestWith([ContractKind::Invariant, InvariantViolation::class])] + public function testKindSelectsTheViolation(ContractKind $kind, string $violationClass): void + { + $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); + + $this->expectException($violationClass); + $this->evaluator->check($invocation, [new BoundContract(new Ensure('false'), Square::class)], [], $kind); + } + + public function testVariablesCanNotReplaceThis(): void + { + $square = new Square(); + $invocation = FakeInvocation::on($square, 'scale', 2.0); + $contracts = [new BoundContract(new Invariant('$this instanceof \PhpDeal\Tests\Unit\Stub\Square'), Square::class)]; + + $this->evaluator->check($invocation, $contracts, ['this' => new stdClass()], ContractKind::Invariant); + + $this->addToAssertionCount(1); + } + + public function testEvaluationFlagIsSetWhileExpressionRuns(): void + { + $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); + $contracts = [new BoundContract(new Verify('$evaluator->isEvaluating()'), Square::class)]; + + $this->evaluator->check($invocation, $contracts, ['evaluator' => $this->evaluator], ContractKind::Precondition); + + self::assertFalse($this->evaluator->isEvaluating()); + } + + public function testEvaluationFlagIsResetAfterFailure(): void + { + $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); + $contracts = [new BoundContract(new Verify('throw new \RuntimeException("boom")'), Square::class)]; + + try { + $this->evaluator->check($invocation, $contracts, [], ContractKind::Precondition); + self::fail('A violation was expected'); + } catch (PreconditionViolation $violation) { + self::assertInstanceOf(RuntimeException::class, $violation->getPrevious()); + self::assertStringEndsWith(': boom', $violation->getMessage()); + } + self::assertFalse($this->evaluator->isEvaluating()); + } + + public function testStaticInvocationIsEvaluatedInClassScope(): void + { + $invocation = FakeInvocation::onStatic(Square::class, 'create'); + $contracts = [new BoundContract(new Ensure('self::class === \PhpDeal\Tests\Unit\Stub\Square::class'), Square::class)]; + + $this->evaluator->check($invocation, $contracts, [], ContractKind::Postcondition); + + $this->addToAssertionCount(1); + } + + public function testThisInStaticInvocationIsInvalid(): void + { + $invocation = FakeInvocation::onStatic(Square::class, 'create'); + + $this->expectException(InvalidContractException::class); + $this->expectExceptionMessage('Contract "$this->size > 0" of ' . Square::class . '::create() uses $this'); + $this->evaluator->check( + $invocation, + [new BoundContract(new Ensure('$this->size > 0'), Square::class)], + [], + ContractKind::Postcondition, + ); + } + + public function testSyntaxErrorIsInvalid(): void + { + $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); + + try { + $this->evaluator->check($invocation, [new BoundContract(new Verify('1 +'), Square::class)], [], ContractKind::Precondition); + self::fail('An invalid contract was expected'); + } catch (InvalidContractException $exception) { + self::assertInstanceOf(ParseError::class, $exception->getPrevious()); + } + } + + public function testNonBooleanResultIsInvalid(): void + { + $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); + + $this->expectException(InvalidContractException::class); + $this->expectExceptionMessage('string returned'); + $this->evaluator->check($invocation, [new BoundContract(new Verify('"yes"'), Square::class)], [], ContractKind::Precondition); + } +} diff --git a/tests/Unit/Contract/ContractFetcherTest.php b/tests/Unit/Contract/ContractFetcherTest.php new file mode 100644 index 0000000..e0660b4 --- /dev/null +++ b/tests/Unit/Contract/ContractFetcherTest.php @@ -0,0 +1,110 @@ +fetcher = new ContractFetcher(); + } + + public function testPreconditionsOfParentsAreNotInheritedByDefault(): void + { + $contracts = $this->fetcher->getPreconditions(new ReflectionMethod(Square::class, 'scale')); + + self::assertSame([['$factor !== 13.0', Square::class]], self::describe($contracts)); + self::assertContainsOnlyInstancesOf(Verify::class, \array_map(static fn(BoundContract $c) => $c->contract, $contracts)); + } + + public function testInheritAttributeEnablesParentPreconditions(): void + { + $contracts = $this->fetcher->getPreconditions(new ReflectionMethod(Square::class, 'resize')); + + self::assertSame([['$factor > 0', Polygon::class]], self::describe($contracts)); + } + + public function testInheritDocTagEnablesParentPreconditions(): void + { + $contracts = $this->fetcher->getPreconditions(new ReflectionMethod(Square::class, 'documented')); + + self::assertSame([['true', Square::class]], self::describe($contracts)); + } + + public function testPostconditionsIncludeParentsAndInterfacesInTheirScopes(): void + { + $contracts = $this->fetcher->getPostconditions(new ReflectionMethod(Square::class, 'scale')); + + self::assertSame( + [ + ['$__result >= $this->size', Square::class], + // Polygon and Shape declare the same expression, it is checked once in the closest scope + ['$__result > 0', Polygon::class], + ], + self::describe($contracts), + ); + self::assertContainsOnlyInstancesOf(Ensure::class, \array_map(static fn(BoundContract $c) => $c->contract, $contracts)); + } + + public function testPrivateParentMethodsAreNotPrototypes(): void + { + $contracts = $this->fetcher->getPostconditions(new ReflectionMethod(Square::class, 'hidden')); + + self::assertSame([], $contracts); + } + + public function testInvariantsOfInterfacesUseTheScopeOfTheClass(): void + { + $contracts = $this->fetcher->getInvariants(new ReflectionClass(Square::class)); + + self::assertSame( + [ + ['$this->sides === 4', Square::class], + ['$this->sides >= 3', Polygon::class], + ['$this->sides > 0', Square::class], + ], + self::describe($contracts), + ); + self::assertContainsOnlyInstancesOf(Invariant::class, \array_map(static fn(BoundContract $c) => $c->contract, $contracts)); + } + + public function testResultsAreCached(): void + { + $method = new ReflectionMethod(Square::class, 'scale'); + $class = new ReflectionClass(Square::class); + + self::assertSame($this->fetcher->getPostconditions($method), $this->fetcher->getPostconditions($method)); + self::assertSame($this->fetcher->getInvariants($class), $this->fetcher->getInvariants($class)); + } + + /** + * @param list $contracts + * + * @return list + */ + private static function describe(array $contracts): array + { + return \array_map( + static fn(BoundContract $contract): array => [$contract->contract->expression, $contract->scope], + $contracts, + ); + } +} diff --git a/tests/Unit/ContractApplicationTest.php b/tests/Unit/ContractApplicationTest.php new file mode 100644 index 0000000..af67865 --- /dev/null +++ b/tests/Unit/ContractApplicationTest.php @@ -0,0 +1,49 @@ +createMock(AspectContainer::class); + $factories = []; + $container + ->expects(self::exactly(3)) + ->method('addLazyService') + ->willReturnCallback(static function (string $id, Closure $factory) use (&$factories): void { + $factories[$id] = $factory; + }); + + ContractApplication::registerAspects($container); + + self::assertSame( + [PreconditionCheckerAspect::class, PostconditionCheckerAspect::class, InvariantCheckerAspect::class], + \array_keys($factories), + ); + self::assertInstanceOf(PreconditionCheckerAspect::class, $factories[PreconditionCheckerAspect::class]($container)); + self::assertInstanceOf(PostconditionCheckerAspect::class, $factories[PostconditionCheckerAspect::class]($container)); + self::assertInstanceOf(InvariantCheckerAspect::class, $factories[InvariantCheckerAspect::class]($container)); + } + + public function testKernelIsRunning(): void + { + $container = ContractApplication::getInstance()->getContainer(); + + self::assertTrue($container->has(PreconditionCheckerAspect::class)); + self::assertTrue($container->has(PostconditionCheckerAspect::class)); + self::assertTrue($container->has(InvariantCheckerAspect::class)); + } +} diff --git a/tests/Unit/Exception/ContractViolationTest.php b/tests/Unit/Exception/ContractViolationTest.php new file mode 100644 index 0000000..673f296 --- /dev/null +++ b/tests/Unit/Exception/ContractViolationTest.php @@ -0,0 +1,115 @@ +scale(13.0)', + $violation->getMessage(), + ); + self::assertSame('$factor !== 13.0', $violation->contract); + self::assertSame(Square::class, $violation->className); + self::assertSame('scale', $violation->methodName); + } + + public function testStaticCallsUseDoubleColon(): void + { + $violation = new PostconditionViolation(FakeInvocation::onStatic(Square::class, 'create'), 'false'); + + self::assertSame('Postcondition "false" violated in ' . Square::class . '::create()', $violation->getMessage()); + } + + public function testMessageIncludesThePreviousError(): void + { + $violation = new InvariantViolation( + FakeInvocation::on(new Square(), 'scale', 1.0), + 'check()', + new RuntimeException('Value is too small'), + ); + + self::assertStringEndsWith('->scale(1.0): Value is too small', $violation->getMessage()); + self::assertStringStartsWith('Invariant "check()"', $violation->getMessage()); + } + + public function testBaseViolationKeepsGenericKind(): void + { + $violation = new ContractViolation(FakeInvocation::on(new Square(), 'scale', 1.0), 'false'); + + self::assertStringStartsWith('Contract "false" violated', $violation->getMessage()); + } + + public function testLocationPointsToTheMethod(): void + { + $method = new ReflectionMethod(Square::class, 'scale'); + $violation = new PreconditionViolation(FakeInvocation::on(new Square(), 'scale', 1.0), 'false'); + + self::assertSame($method->getFileName(), $violation->getFile()); + self::assertSame($method->getStartLine(), $violation->getLine()); + } + + /** + * @return iterable + */ + public static function providerArguments(): iterable + { + yield 'null' => [null, 'null']; + yield 'true' => [true, 'true']; + yield 'false' => [false, 'false']; + yield 'integer' => [42, '42']; + yield 'float' => [1.5, '1.5']; + yield 'string' => ["it's", "'it\\'s'"]; + yield 'long string' => [\str_repeat('a', 100), "'" . \str_repeat('a', 36) . '...']; + yield 'long unicode string' => [\str_repeat('ั', 50), "'" . \str_repeat('ั', 36) . '...']; + yield 'array' => [[1, 2, 3], 'array(3)']; + yield 'enum' => [Status::Active, Status::class . '::Active']; + yield 'object' => [new stdClass(), 'stdClass']; + yield 'closure' => [static fn() => null, 'Closure']; + } + + #[DataProvider('providerArguments')] + public function testArgumentsAreRenderedSafely(mixed $argument, string $expected): void + { + $invocation = new FakeInvocation(new Square(), Square::class, 'scale', [$argument]); + $violation = new PreconditionViolation($invocation, 'false'); + + self::assertStringEndsWith('->scale(' . $expected . ')', $violation->getMessage()); + } + + public function testResourcesAreRenderedByType(): void + { + $resource = \fopen('php://memory', 'rb'); + self::assertIsResource($resource); + + $violation = new PreconditionViolation(new FakeInvocation(new Square(), Square::class, 'scale', [$resource]), 'false'); + \fclose($resource); + + self::assertStringEndsWith('->scale(resource (stream))', $violation->getMessage()); + } +} diff --git a/tests/Unit/Stub/FakeInvocation.php b/tests/Unit/Stub/FakeInvocation.php new file mode 100644 index 0000000..80c7797 --- /dev/null +++ b/tests/Unit/Stub/FakeInvocation.php @@ -0,0 +1,84 @@ + + */ +final class FakeInvocation implements MethodInvocation +{ + private ReflectionMethod $method; + + /** + * @param class-string $className + * @param list $arguments + */ + public function __construct( + private readonly ?object $instance, + string $className, + string $methodName, + private array $arguments = [], + ) { + $this->method = new ReflectionMethod($className, $methodName); + } + + public static function on(object $instance, string $methodName, mixed ...$arguments): self + { + return new self($instance, $instance::class, $methodName, \array_values($arguments)); + } + + /** + * @param class-string $className + */ + public static function onStatic(string $className, string $methodName, mixed ...$arguments): self + { + return new self(null, $className, $methodName, \array_values($arguments)); + } + + public function getMethod(): ReflectionMethod + { + return $this->method; + } + + public function getArguments(): array + { + return $this->arguments; + } + + public function setArguments(array $arguments): void + { + $this->arguments = $arguments; + } + + public function proceed(): mixed + { + return $this->method->invokeArgs($this->instance, $this->arguments); + } + + public function isDynamic(): bool + { + return $this->instance !== null; + } + + public function getThis(): ?object + { + return $this->instance; + } + + public function getScope(): string + { + return $this->method->class; + } + + public function __toString(): string + { + return $this->method->class . '->' . $this->method->name; + } +} diff --git a/tests/Unit/Stub/Polygon.php b/tests/Unit/Stub/Polygon.php new file mode 100644 index 0000000..0b7a9ba --- /dev/null +++ b/tests/Unit/Stub/Polygon.php @@ -0,0 +1,39 @@ +sides >= 3')] +abstract class Polygon implements Shape +{ + protected int $sides = 3; + + #[Verify('$factor < 100')] + #[Ensure('$__result > 0')] + public function scale(float $factor): float + { + return $factor; + } + + #[Verify('$factor > 0')] + public function resize(float $factor): float + { + return $factor; + } + + public function reveal(): void + { + $this->hidden(1); + } + + /** + * A private method is not a prototype of Square::hidden(), its contracts are not inherited + */ + #[Verify('$secret > 0')] + private function hidden(int $secret): void {} +} diff --git a/tests/Unit/Stub/Shape.php b/tests/Unit/Stub/Shape.php new file mode 100644 index 0000000..bf204e9 --- /dev/null +++ b/tests/Unit/Stub/Shape.php @@ -0,0 +1,17 @@ +sides > 0')] +interface Shape +{ + #[Verify('$factor > 0')] + #[Ensure('$__result > 0')] + public function scale(float $factor): float; +} diff --git a/tests/Unit/Stub/Square.php b/tests/Unit/Stub/Square.php new file mode 100644 index 0000000..be894e7 --- /dev/null +++ b/tests/Unit/Stub/Square.php @@ -0,0 +1,55 @@ +sides === 4')] +final class Square extends Polygon implements Stringable +{ + protected int $sides = 4; + + private int $size = 2; + + #[Verify('$factor !== 13.0')] + #[Ensure('$__result >= $this->size')] + public function scale(float $factor): float + { + return $factor * $this->size; + } + + #[Inherit] + public function resize(float $factor): float + { + return $factor; + } + + /** + * {@inheritDoc} + */ + #[Verify('true')] + public function documented(): void {} + + #[Verify('$secret > 0')] + public function hidden(int $secret): void {} + + #[Verify('$a > 0')] + public function withParameters(int $a, int $b = 5, int ...$rest): void {} + + #[Verify('$__result')] + public static function create(): self + { + return new self(); + } + + public function __toString(): string + { + return 'square'; + } +} diff --git a/tests/Unit/Stub/Status.php b/tests/Unit/Stub/Status.php new file mode 100644 index 0000000..661b6ae --- /dev/null +++ b/tests/Unit/Stub/Status.php @@ -0,0 +1,10 @@ +init([ - 'debug' => true, - 'appDir' => __DIR__, - 'cacheDir' => __DIR__ . '/cache/', + 'debug' => true, + 'appDir' => \dirname(__DIR__), + 'cacheDir' => __DIR__ . '/cache', + 'includePaths' => [__DIR__ . '/Fixtures'], ]);