Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,12 @@ lowest-dependencies job and `composer audit`.

| Path | Contents |
|------------------------------|----------|
| `src/Attribute/` | The attributes. `Verify`, `Ensure`, `Invariant` implement the `Contract` interface (`$expression`). |
| `src/Attribute/` | The attributes. `Verify`, `Ensure`, `Invariant` implement the `Contract` interface (`$expression`); only these three are ever evaluated. |
| `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/ContractEvaluator.php` | Evaluates contracts: calls compiled closures, or compiles expressions with `eval()` (once) and binds them. |
| `src/Contract/ContractRewriter.php` | Go! AOP `NodeRewriter` (PHP 8.5+): adds the compiled closure as `check:` to contract attributes while weaving. |
| `src/Contract/ContractCompiler.php` | Turns an expression into the source of a static closure, or `null` when it must stay on `eval()`. |
| `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`. |
Expand Down Expand Up @@ -70,6 +72,15 @@ lowest-dependencies job and `composer audit`.
- `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.
- **Compiled contracts (PHP 8.5+).** `ContractRewriter` appends `check: static function ($__this, ...) {...}` to the
attribute in the token stream, on the same line (comments dropped, newlines flattened, names fully qualified,
`$this` → `$__this`). The proxy re-declares attributes from the AST without `check`, so `ContractFetcher` reads them
from the `...OriginalAlias` method or the `...OriginalTrait`. `BoundContract` binds the closure to its scope once.
`ContractCompiler` returns `null` for anything that could behave differently than in `eval()`; keep it conservative,
an invalid closure breaks the whole woven file.
- **Per-call cost.** Aspects run on every call: keep reflection and string building out of the hot path. Cache by
class and method name in nested arrays (`ContractFetcher`, `ContractEvaluator`), and build error text only when
throwing.
- **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 `<Class>OriginalTrait`, and the proxy keeps the
Expand Down
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ specifications into contracted code and tests. See [UPGRADE-2.0.md](UPGRADE-2.0.
PHPUnit tests derived from the contracts. It is installable as a Claude Code plugin from this repository
(`/plugin marketplace add php-deal/framework`) (#36).
- Static checker for contract expressions, `skills/design-by-contract/scripts/lint-contracts.php`.
- On PHP 8.5+ contract expressions are compiled into static closures while Go! AOP weaves the class, on the line of
the attribute (new `check` argument of `#[Verify]`, `#[Ensure]` and `#[Invariant]`, filled in by PhpDeal). They are
cached by opcache, run without `eval()`, and breakpoints and stack traces point to the contract. Expressions that
could behave differently as a static closure, and PHP 8.4, keep using `eval()` (#76).

### Changed

Expand All @@ -36,6 +40,11 @@ specifications into contracted code and tests. See [UPGRADE-2.0.md](UPGRADE-2.0.
- 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.
- Less work per call: contracts, method parameters, invariants by class name and the cloneability of a class are
looked up in per-process caches before any reflection call, and error locations are built only on errors (#80).
- Only the built-in `#[Verify]`, `#[Ensure]` and `#[Invariant]` attributes are evaluated; `BoundContract` accepts no
other `Contract` implementation, so computed text can not reach `eval()`. Compiled contracts come from the string
literal in the source (#85).
- Violations point to the line of the method that declares the contract.

### Fixed
Expand All @@ -44,6 +53,7 @@ specifications into contracted code and tests. See [UPGRADE-2.0.md](UPGRADE-2.0.
- 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.
- `$this` inside a string literal of a static method's contract no longer throws `InvalidContractException` (#84).

### Removed

Expand Down
34 changes: 29 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,9 @@ random values, and `\in_array()` without strict comparison.
- 🧬 **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.
- ⚡ **Fast**: each expression is compiled once, contracts are read once per class, and the object is cloned only when
a contract uses `$__old`.
- ⚡ **Fast**: on PHP 8.5+ contracts are compiled into the woven classes, so opcache caches them and no `eval()` runs;
contracts are read once per class, and the object is cloned only when a contract uses `$__old`.
- 🐞 **Debuggable**: on PHP 8.5+ a breakpoint on a contract line stops in the contract, and stack traces point to it.
- 🔁 **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.
Expand Down Expand Up @@ -475,8 +476,8 @@ violated. Returning `null` is accepted too, for assertion helpers that return no
- **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)'`.
- **Names.** The expression is written for the global namespace, 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:

Expand All @@ -488,6 +489,28 @@ public function setDiscount(int $percent): void {}
- **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.

### Compiled contracts (PHP 8.5+)

On PHP 8.5 and newer, PhpDeal compiles every expression into a static closure while Go! AOP weaves the class, and
adds it to the attribute on the same line. The woven cache file contains, for example:

```php
#[Verify('$amount > 0', check: static function ($__this, $amount, ...$__arguments) { return ($amount > 0); })]
```

You never write `check:` yourself. Compiled contracts are cached by opcache, can be preloaded, and run without
`eval()`, so they also work on hosts that forbid it. A breakpoint on the line of a contract stops inside it, and an
error raised by the expression points to that line. The cache is built by `cache:warmup:aop` as usual.

An expression is evaluated with `eval()` instead, as on PHP 8.4, when it could behave differently as a static closure:
a syntax error or `$this` in a static method (both still throw `InvalidContractException` when the method is called),
`static::` or `self::method()` in an instance context, a nested `function () {}`, magic constants such as `__CLASS__`,
variable variables, `compact()`/`extract()`/`get_defined_vars()`, a newline inside a string literal, and an
invariant that reads a variable other than `$this` and `$__result`. Classes that are not woven use `eval()` too.

Only the built-in attributes are evaluated, and their expressions are constant expressions in your source code. Never
build an expression from configuration, environment variables, a database or user input: it is executed as PHP code.

## Handling violations

Every exception of PhpDeal implements `PhpDeal\Exception\ExceptionInterface`:
Expand Down Expand Up @@ -543,7 +566,8 @@ if (($_SERVER['APP_ENV'] ?? 'prod') !== 'prod') {

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).
[Go! AOP deployment guide](https://github.com/goaop/framework/blob/master/docs/configuration.md). Build the cache
with the PHP version that runs it: a cache woven on PHP 8.5 holds closures in attributes, which PHP 8.4 can not load.

## Upgrading from 1.x

Expand Down
7 changes: 4 additions & 3 deletions skills/design-by-contract/references/expressions.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Contract expressions

A contract is one PHP expression in a string. PhpDeal compiles it once into a closure and binds the closure to the
object, in the scope of the class that declares the contract.
A contract is one PHP expression in a string. PhpDeal compiles it into a closure that runs in the scope of the class
that declares the contract. On PHP 8.5+ the closure is written into the woven class (the `check:` argument of the
attribute), on PHP 8.4 it is compiled with `eval()` at run time. Never write `check:` yourself.

## Contents

Expand Down Expand Up @@ -41,7 +42,7 @@ there: an invariant describes the object alone.
- The expression can read private and protected members of the declaring class: `$this->balance`,
`$this->isValid($x)`, `self::LIMIT`, `static::$registry`. A contract of an interface runs in the scope of the
implementing class. A contract of a parent class runs in the scope of the parent and can read its private state.
- The expression is compiled outside of your file, in the global namespace. `use` imports do **not** apply:
- The expression is written for the global namespace. `use` imports do **not** apply:
- classes, enums and interfaces are fully qualified: `$status === \App\Order\Status::Paid`,
`$at instanceof \DateTimeImmutable`;
- functions get a leading backslash: `\count()`, `\in_array($x, self::ALLOWED, true)`, `\preg_match(...)`;
Expand Down
3 changes: 1 addition & 2 deletions src/Aspect/InvariantCheckerAspect.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
use PhpDeal\Contract\ContractFetcher;
use PhpDeal\Contract\ContractKind;
use PhpDeal\Exception\InvariantViolation;
use ReflectionObject;

/**
* Checks `#[Invariant]` class invariants after the constructor and after every public method
Expand Down Expand Up @@ -48,7 +47,7 @@ public function checkInvariants(MethodInvocation $invocation): mixed
if ($instance === null || $this->evaluator->isEvaluating()) {
return $result;
}
$contracts = $this->fetcher->getInvariants(new ReflectionObject($instance));
$contracts = $this->fetcher->getInvariants($instance::class);
if ($contracts === []) {
return $result;
}
Expand Down
10 changes: 6 additions & 4 deletions src/Aspect/PostconditionCheckerAspect.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
use PhpDeal\Contract\ContractFetcher;
use PhpDeal\Contract\ContractKind;
use PhpDeal\Exception\PostconditionViolation;
use ReflectionObject;

/**
* Checks `#[Ensure]` post-conditions after the method body has returned
Expand Down Expand Up @@ -56,8 +55,11 @@ public function checkPostconditions(MethodInvocation $invocation): mixed
$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;
if ($instance !== null && self::usesOldState($contracts)) {
$oldState = $this->evaluator->cloneState($instance);
if ($oldState !== null) {
$variables['__old'] = $oldState;
}
}

$result = $invocation->proceed();
Expand All @@ -73,7 +75,7 @@ public function checkPostconditions(MethodInvocation $invocation): mixed
private static function usesOldState(array $contracts): bool
{
foreach ($contracts as $boundContract) {
if (\str_contains($boundContract->contract->expression, '$__old')) {
if ($boundContract->usesOldState) {
return true;
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/Attribute/Contract.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@
*
* 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.
*
* Only the built-in {@see Verify}, {@see Ensure} and {@see Invariant} attributes are evaluated. The expression is
* executed as PHP code, so it must be written in the source code, as a constant expression of the attribute. Never
* build it from configuration, environment variables, a database or user input. Other implementations of this
* interface are ignored.
*/
interface Contract
{
Expand Down
10 changes: 8 additions & 2 deletions src/Attribute/Ensure.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace PhpDeal\Attribute;

use Attribute;
use Closure;

/**
* Post-condition: a promise of the method, checked after the method body has returned.
Expand All @@ -27,7 +28,12 @@
final readonly class Ensure implements Contract
{
/**
* @param string $expression PHP expression that must evaluate to true
* @param string $expression PHP expression that must evaluate to true
* @param Closure|null $check The expression compiled into a static closure. PhpDeal writes it into the woven
* class on PHP 8.5+, it is not meant to be written by hand
*/
public function __construct(public string $expression) {}
public function __construct(
public string $expression,
public ?Closure $check = null,
) {}
}
10 changes: 8 additions & 2 deletions src/Attribute/Invariant.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace PhpDeal\Attribute;

use Attribute;
use Closure;

/**
* Class invariant: a condition that holds after the constructor and after every public method call.
Expand All @@ -26,7 +27,12 @@
final readonly class Invariant implements Contract
{
/**
* @param string $expression PHP expression that must evaluate to true
* @param string $expression PHP expression that must evaluate to true
* @param Closure|null $check The expression compiled into a static closure. PhpDeal writes it into the woven
* class on PHP 8.5+, it is not meant to be written by hand
*/
public function __construct(public string $expression) {}
public function __construct(
public string $expression,
public ?Closure $check = null,
) {}
}
10 changes: 8 additions & 2 deletions src/Attribute/Verify.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace PhpDeal\Attribute;

use Attribute;
use Closure;

/**
* Pre-condition: a requirement upon the caller, checked before the method body runs.
Expand All @@ -26,7 +27,12 @@
final readonly class Verify implements Contract
{
/**
* @param string $expression PHP expression that must evaluate to true
* @param string $expression PHP expression that must evaluate to true
* @param Closure|null $check The expression compiled into a static closure. PhpDeal writes it into the woven
* class on PHP 8.5+, it is not meant to be written by hand
*/
public function __construct(public string $expression) {}
public function __construct(
public string $expression,
public ?Closure $check = null,
) {}
}
30 changes: 25 additions & 5 deletions src/Contract/BoundContract.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,42 @@

namespace PhpDeal\Contract;

use PhpDeal\Attribute\Contract;
use Closure;
use PhpDeal\Attribute\Ensure;
use PhpDeal\Attribute\Invariant;
use PhpDeal\Attribute\Verify;

/**
* 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.
*
* Only the built-in attributes are accepted: their expressions are constant expressions written in the source, so
* no computed text ever reaches eval().
*/
final readonly class BoundContract
{
/**
* @param Contract $contract Contract attribute
* @param class-string $scope Class scope for the expression
* Compiled expression bound to the scope, null when the expression is evaluated with eval()
*/
public ?Closure $check;

/**
* Whether the expression reads `$__old`, so the object must be cloned before the call
*/
public bool $usesOldState;

/**
* @param Verify|Ensure|Invariant $contract Contract attribute
* @param class-string $scope Class scope for the expression
*/
public function __construct(
public Contract $contract,
public Verify|Ensure|Invariant $contract,
public string $scope,
) {}
) {
// The closure is declared in the woven trait or the interface, it must run in the scope of the contract
$this->check = $contract->check !== null ? Closure::bind($contract->check, null, $scope) : null;
$this->usesOldState = \str_contains($contract->expression, '$__old');
}
}
Loading
Loading