Skip to content
Merged
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
16 changes: 16 additions & 0 deletions .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "php-deal",
"owner": {
"name": "PhpDeal"
},
"description": "Claude Code plugins of the PhpDeal Design by Contract framework for PHP",
"plugins": [
{
"name": "php-deal",
"source": "./",
"description": "Turns business specifications into self-checking PHP code with php-deal/framework contracts and into PHPUnit tests derived from those contracts.",
"category": "development",
"tags": ["php", "design-by-contract", "testing"]
}
]
}
14 changes: 14 additions & 0 deletions .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "php-deal",
"displayName": "PhpDeal: Design by Contract",
"version": "2.0.0",
"description": "Turns business specifications into self-checking PHP code with php-deal/framework contracts (#[Verify], #[Ensure], #[Invariant]) and into PHPUnit tests derived from those contracts.",
"author": {
"name": "PhpDeal contributors",
"url": "https://github.com/php-deal/framework/graphs/contributors"
},
"homepage": "https://github.com/php-deal/framework",
"repository": "https://github.com/php-deal/framework",
"license": "MIT",
"keywords": ["php", "design-by-contract", "contracts", "preconditions", "postconditions", "invariants", "phpunit", "specification"]
}
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
/phpunit.xml.dist export-ignore
/CONTRIBUTING.md export-ignore
/AGENTS.md export-ignore
/.claude-plugin export-ignore

*.php diff=php
2 changes: 1 addition & 1 deletion .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;

$finder = Finder::create()
->in([__DIR__ . '/src', __DIR__ . '/tests', __DIR__ . '/demo'])
->in([__DIR__ . '/src', __DIR__ . '/tests', __DIR__ . '/demo', __DIR__ . '/skills'])
->exclude(['cache'])
->append([__FILE__]);

Expand Down
10 changes: 8 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,13 @@ lowest-dependencies job and `composer audit`.
| `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/Fixtures/` | Classes **woven** by the test bootstrap. Only this directory and the skill example are 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`. |
| `tests/Skill/` | Tests of the contract checker of the skill (suite `skill`, with the skill example). |
| `demo/` | Runnable example, also run in CI. |
| `skills/design-by-contract/` | Agent Skill for users' AI agents: `SKILL.md`, `references/`, the contract checker in `scripts/`, and a worked example in `examples/` that the test suite weaves and runs. |
| `.claude-plugin/` | Manifests that publish the repository as a Claude Code plugin marketplace with the skill. |

## How it works (read before changing behaviour)

Expand Down Expand Up @@ -100,4 +103,7 @@ lowest-dependencies job and `composer audit`.

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.
Changes to expressions, variables, inheritance or weaving also go into `skills/design-by-contract/` (the skill
and its checker teach those rules to users' agents). Bump `version` in `.claude-plugin/plugin.json` together with
a release, and run `claude plugin validate . --strict` when you change the manifests.
3. README and skill code examples still work: they are meant to be copy-paste runnable.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ A rewrite for modern PHP. See [UPGRADE-2.0.md](UPGRADE-2.0.md) for the migration
- 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.
- Agent Skill `design-by-contract` for AI coding agents: turns business specifications into contracted code and
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`.

### Changed

Expand Down
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ new Account()->deposit(-10);
- [Writing expressions](#writing-expressions)
- [Handling violations](#handling-violations)
- [PHPStan integration](#phpstan-integration)
- [AI coding agents](#ai-coding-agents)
- [Production](#production)
- [Upgrading from 1.x](#upgrading-from-1x)
- [Contributing](#contributing)
Expand Down Expand Up @@ -366,6 +367,35 @@ includes:
- vendor/php-deal/framework/extension.neon
```

## AI coding agents

PhpDeal ships an [Agent Skill](https://agentskills.io) that teaches AI coding agents to turn a business
specification into self-checking code: it extracts the rules, maps each one to a `#[Verify]`, `#[Ensure]` or
`#[Invariant]` (or to plain code for business errors), writes the classes, checks the contract expressions and
derives PHPUnit tests from the contracts. The tests cover the examples of the specification, the boundaries of the
preconditions and random sequences of valid calls.

In Claude Code, install it as a plugin from this repository:

```
/plugin marketplace add php-deal/framework
/plugin install php-deal@php-deal
```

Then ask for it, e.g. *"Implement docs/booking-spec.md with Design by Contract"*, or run
`/php-deal:design-by-contract`. Other agents that read the Agent Skills format can use the folder
[`skills/design-by-contract`](skills/design-by-contract) directly. It is also installed with the package, at
`vendor/php-deal/framework/skills/design-by-contract`.

The skill bundles a checker for contract expressions, which works without an AI as well. Contracts are strings, so
neither PHP nor PHPStan see their mistakes. The checker reports syntax errors, misspelled variables, `$__old` or
`$__result` in the wrong kind of contract, `$this` in static methods, names that `use` imports do not resolve, and
more:

```bash
php vendor/php-deal/framework/skills/design-by-contract/scripts/lint-contracts.php src
```

## Production

Contracts are a development and testing tool: every checked call costs an expression evaluation. The usual setup is
Expand Down
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,12 @@
"autoload-dev": {
"psr-4": {
"Demo\\": "demo/",
"Example\\Inventory\\": "skills/design-by-contract/examples/inventory/",
"PhpDeal\\Tests\\": "tests/"
}
},
"classmap": [
"skills/design-by-contract/scripts/"
]
},
"scripts": {
"cs": "php-cs-fixer check --diff",
Expand Down
1 change: 1 addition & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ parameters:
- src
- tests
- demo
- skills
excludePaths:
- tests/cache (?)
- demo/cache (?)
Expand Down
4 changes: 4 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
<testsuite name="functional">
<directory>tests/Functional</directory>
</testsuite>
<testsuite name="skill">
<directory>tests/Skill</directory>
<directory>skills/design-by-contract/examples</directory>
</testsuite>
</testsuites>

<source>
Expand Down
182 changes: 182 additions & 0 deletions skills/design-by-contract/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
---
name: design-by-contract
description: >-
Turns business specifications (requirements, user stories, acceptance criteria, domain rules) into self-checking
PHP code with php-deal/framework: #[Verify] preconditions, #[Ensure] postconditions and #[Invariant] invariants,
plus PHPUnit tests derived from those contracts. Use it to implement a spec in PHP with Design by Contract, to add
contracts to existing PHP classes, to turn business rules into preconditions, postconditions or invariants, to
generate tests from contracts, or to review and fix php-deal contract expressions.
license: MIT
compatibility: Needs PHP 8.4+ and php-deal/framework 2.x in the target project. PHPUnit is used for the tests.
---

# Design by Contract with PhpDeal

Turn a business specification into PHP code that checks its own rules on every call, and into tests that exercise
those rules. PhpDeal reads the contracts from native attributes. They hold PHP expressions as strings, and
[Go! AOP](https://github.com/goaop/framework) evaluates them around the method:

```php
use PhpDeal\Attribute\{Ensure, Invariant, Verify};

#[Invariant('$this->balance >= 0')] // always true between calls
class Account
{
private int $balance = 0;

#[Verify('$amount > 0')] // the caller's obligation, checked before the body
#[Ensure('$this->balance === $__old->balance + $amount')] // the method's promise, checked after it
public function deposit(int $amount): void
{
$this->balance += $amount;
}
}
```

A broken contract throws `PreconditionViolation`, `PostconditionViolation` or `InvariantViolation`. A contract
violation always means a bug in the caller or in the method. It never means invalid user input.

## Workflow

Copy this checklist and work through it:

```
- [ ] 1. Check the project setup
- [ ] 2. Extract the rules from the specification and number them
- [ ] 3. Classify every rule: precondition, postcondition, invariant, business error or not a contract
- [ ] 4. Design the API: classes, interfaces, query methods for the preconditions
- [ ] 5. Write the code with its contracts
- [ ] 6. Run the contract checker, fix every error
- [ ] 7. Derive the tests and run them
- [ ] 8. Report the rule-to-contract table, the assumptions and the open questions
```

### 1. Check the project setup

- `composer.json` requires `php-deal/framework` (2.x) and PHP 8.4 or newer. If it does not, ask before adding the
dependency with `composer require php-deal/framework`. Without a `composer.json` you can inspect, rely on the weaving
check in step 7: one test that breaks a precondition must throw `PreconditionViolation`.
- Contracts are checked only in woven classes. `ContractApplication::getInstance()->init([...])` must run before the
classes are autoloaded, in the front controller and in the test bootstrap. Its `includePaths` must cover the
directory of the new classes. If the project already has its own Go! AOP kernel, it calls
`ContractApplication::registerAspects($container)` instead. Without weaving the attributes do nothing, so tests
pass without checking anything.
- See [references/setup.md](references/setup.md) for the snippets.

### 2. Extract the rules

Read the specification and list every statement that constrains state, input, output or behaviour. Give each one a
stable ID (`R1`, `R2`, ...), or keep the IDs the specification already uses. Quote the source wording. Do not invent
rules. When the specification is ambiguous or silent, write the question down and pick the most conservative
assumption, which is usually the stricter precondition. Data that the API needs but the specification only implies,
such as an id or the name of the person who acts, is API design: add it, list it as an assumption (`A1`, `A2`, ...),
and constrain it only as far as the code needs.

### 3. Classify each rule

| The specification says... | Use |
|-----------------------------------------------------------------------------------|--------------------------------------------|
| "only when", "must be", "at most", "requires": a condition the caller can check first | `#[Verify]` on the method |
| "after X...", "increases by", "returns", "never changes Y": an effect of the call | `#[Ensure]` with `$__old` / `$__result` |
| "always", "never", "at all times": a fact about the object | `#[Invariant]` on the class or interface |
| "is rejected with the message...", "show an error": input from people or systems | Code that throws a domain exception, plus `#[Ensure]` for the success path |
| Timing, notifications, persistence, permissions, other services | Not a contract: integration tests or code |

Two points need judgement:

- **Precondition or business error?** A precondition is a promise the caller can keep. It is off in production when
the kernel is not started, and its violation is a programming error. When the specification describes a reaction
to bad input (a message, a rejected status, a retry), implement that reaction in code. You can also add a
precondition at the boundary where the input has already been validated. Give the caller a query method
(`available()`, `canCancel()`) so that it can check a precondition before the call.
- **Strength.** Write the strongest contract the specification supports. Prefer
`$this->total === $__old->total + $amount` to `$this->total > $__old->total`. Add frame conditions for state that
must not change: `#[Ensure('$this->reserved === $__old->reserved')]`.

[references/spec-to-contracts.md](references/spec-to-contracts.md) has a catalogue of rule patterns with their
contracts: ranges, state machines, collections, uniqueness, implications, money and dates.

### 4. Design the API

- Put contracts on an interface when it will have several implementations, and mark each implementation with
`#[Inherit]`. Without it the interface's preconditions do not apply, and a class that declares no contract
attribute of its own is not checked at all.
- Keep complex predicates in a private method (`#[Verify('$this->isValidTransition($to)')]`). Contracts run in the
scope of the class, so they can call private methods and read private properties.
- Expose cheap public query methods for the state that preconditions depend on.

### 5. Write the code

Expression rules. Every one of them breaks contracts silently when ignored:

- Write expressions in **single quotes**: `#[Verify('$amount > 0')]`. In double quotes PHP would interpolate `$amount`.
- **No `use` imports inside expressions.** Write class names fully qualified (`\App\Money::isValid($amount)`), and
global functions with a leading backslash (`\count($items)`). `self::`, `static::` and `parent::` work.
- Arguments are available by parameter name, with defaults filled in. A variadic parameter is a list: check its
items (`\min($amounts) > 0`), because comparing the list with a number (`$amounts > 0`) is always true.
- `$__result` (return value) and `$__old` (clone of the object before the call) exist only in `#[Ensure]`. `$__old`
is a **shallow** clone: compare scalars, or add a `__clone()` that copies mutable objects.
- A contract returns `true` (holds), `false` (violated) or `null` (for assertion libraries). Any other value throws
`InvalidContractException`.
- Contracts must have no side effects. Do not use `$this` in static methods.
- Postconditions and invariants are not checked when the method throws.
- `#[Verify]` and `#[Ensure]` work on every method: constructors, private, protected and static ones. Invariants are
checked after the constructor and after every **public** method, not after private ones. `final` classes are
woven as well.
- In a constructor `$__result` is always `null` and `$__old` is the object before its properties are set: check
`$this` instead.

[references/expressions.md](references/expressions.md) has the full reference and the pitfalls of floats, dates,
enums, collections and nullables.

Add the rule ID next to each contract, as a trailing comment or in the method docblock, so that a reader can trace
it back to the specification.

### 6. Check the contracts

PHP and PHPStan do not see inside the expression strings. Run the bundled checker on the files you wrote:

```bash
php ${CLAUDE_SKILL_DIR}/scripts/lint-contracts.php --strict src/Inventory
```

`${CLAUDE_SKILL_DIR}` is the directory of this file. In projects with php-deal installed the checker is also at
`vendor/php-deal/framework/skills/design-by-contract/scripts/lint-contracts.php`. It reports syntax errors, unknown
or misspelled variables, `$__old` or `$__result` in the wrong contract, `$this` in static methods, imported names
that do not resolve, double-quoted strings, assignments, the current time or random values, and `\in_array()`
without `true`. Fix every error and warning. It can not check types or the existence of properties: the tests in the
next step do that.

### 7. Derive the tests

Postconditions and invariants are checked on every call of a woven class. Any test that drives the object through
valid calls therefore also tests them. Write these tests:

1. **Specification examples.** Each example or acceptance criterion becomes a test with explicit assertions. This is
the independent oracle: a wrong contract and wrong code can agree with each other.
2. **Precondition boundaries.** For each `#[Verify]`, call just inside the boundary (it passes) and just outside it
(`PreconditionViolation`, and the state is unchanged). This test also proves that weaving is active.
3. **Business errors.** For each rejected input, assert the domain exception and its message.
4. **Random valid sequences.** Sample arguments from the preconditions with a seeded `Random\Randomizer` and run a
few hundred calls. The contracts check every step.

[references/testing.md](references/testing.md) explains each kind and shows the bootstrap. Run the tests. When one
of them reports a violation, decide whether the code, the contract or the test is wrong. Do not weaken a contract to
make a test pass unless the specification supports the weaker version.

### 8. Report

End with:

- a table `Rule | Contract or code | Where | Test`, with one row per rule (`Where` is `Class::method`, or `Class` for
an invariant);
- the assumptions you made, and the open questions for the business;
- the rules that are not contracts, and where they are handled instead.

## Worked example

[examples/inventory/](examples/inventory) holds a complete run: [SPEC.md](examples/inventory/SPEC.md) (rules
R1-R9), [StockItem.php](examples/inventory/StockItem.php) with its contracts,
[CountBelowReserved.php](examples/inventory/CountBelowReserved.php) for the one business error, and
[StockItemTest.php](examples/inventory/StockItemTest.php) with the four kinds of tests. Read it before the first
implementation in a project. The PhpDeal test suite runs it, so it always works.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Example\Inventory;

use DomainException;

/**
* A stock count is lower than the quantity reserved for orders (R9)
*/
final class CountBelowReserved extends DomainException {}
Loading
Loading