PHPackages                             hediet/contracts - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. hediet/contracts

ActiveLibrary[Testing &amp; Quality](/categories/testing)

hediet/contracts
================

A library which helps to specify, check and reflect code contracts.

v0.1.0(11y ago)149MITPHPPHP &gt;=5.3.0

Since Mar 14Pushed 11y agoCompare

[ Source](https://github.com/hediet/php-contracts)[ Packagist](https://packagist.org/packages/hediet/contracts)[ RSS](/packages/hediet-contracts/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (4)Versions (2)Used By (0)

PHP Contracts - A Powerful Assertion Library for PHP
====================================================

[](#php-contracts---a-powerful-assertion-library-for-php)

PHP Contracts is an assertion library for PHP to validate arguments and invariants. This library aims to replace my library [nunzion/php-expect](https://bitbucket.org/nunzion/php-expect).

Warning
-------

[](#warning)

This library is still in development! However, the signature of the method `Contract::requires` will not change and it is guaranteed that an exception is beeing thrown if the condition evaluates to `false`.

Installation
------------

[](#installation)

You can use [Composer](http://getcomposer.org/) to download and install PHP Contracts. To add PHP Contracts to your project, simply add a dependency on hediet/contracts to your project's `composer.json` file.

Here is a minimal example of a `composer.json` file that just defines a dependency on PHP Contracts:

```
{
    "require": {
        "hediet/contracts": "dev-master"
    }
}
```

Usage
-----

[](#usage)

Using this library is as simple as calling `Contract::requires` with an arbitrary condition:

```
use Hediet\Contract;

function sum($a, $b)
{
    Contract::requires(is_int($a) && is_int($b));
}
```

If the specified condition evaluates to `false`, PHP Contracts analyzes the condition and throws an exception with an appropriate error message.

The following code will throw an `\InvalidArgumentException` with the message `Argument 'b' must be of type 'integer', but is of type 'string'.`:

```
sum(1, "test");
```

### Explicitly Supported Tests

[](#explicitly-supported-tests)

Currently PHP Contracts understands the following conditions:

- All is\_TYPE functions for TYPE being a primitive.
- Comparison operators like `=`.
- Disjunction of type constraints, e.g. `is_int($a) || is_float($a) || $a === null`. Internally, a type constraint is being created for $a which denotes that $a must be of type `int|float|null`.
- Conjunction of constraints.

However, currently all expressions must be constants or arguments.

### Examples

[](#examples)

```
public function intArgumentsProvider() { return array(array(7, 1)); }

/**
 * @dataProvider intArgumentsProvider
 * @expectedException \InvalidArgumentException
 * @expectedExceptionMessage Argument 'a' must be greater than '1'
 * and less than or equal to argument 'b', but 'a' is 7 and 'b' is 1.
 */
public function testExampleRange($a, $b)
{
    Contract::requires(1 < $a && $a  10));
}
```

Internals
---------

[](#internals)

If the condition evaluates to `true`, the requires method returns immediately. Thus, if a condition does not fail, there is no significant performance decrease.

If a condition fails, i.e. evaluates to `false`, the stacktrace is used to determine the location of the `requires` call. After that, the invocation is parsed with nikic/PHP-Parser and converted to a set of constraints. These constraints may reference expressions to which the constraints are applied to. By using the stacktrace a second time, the arguments and the value of `$this` can be obtained for the context of the invocation to evaluate these expressions, so that a constraint can add an explanation of why he has failed.

Todos
-----

[](#todos)

- Support deep expressions, so that conditions like `Contract::requires(count($a) > 0)` can be analyzed. Since $a may be obtained from the stacktrace and count is a pure method, `count($a)` can be evaluated without side effects.
- Support various array tests.
- Throw an invariant exception if no argument is referenced in the condition.
- Use optionally provided values to evaluate expressions which uses variables that are neither arguments nor `$this`.
- Add a reflection API which parses the first `Contract::requires` calls of a method and returns their corresponding constraints. This enables propagating constraints to the UI.

Author
------

[](#author)

Henning Dieterichs -

License
-------

[](#license)

PHP Expect is licensed under the MIT License.

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

4083d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4bbf4a94e3658e3567154235723a15a30433f80e2af8049619cb30248e8821ac?d=identicon)[Henning Dieterichs](/maintainers/Henning%20Dieterichs)

---

Top Contributors

[![hediet](https://avatars.githubusercontent.com/u/2931520?v=4)](https://github.com/hediet "hediet (9 commits)")

---

Tags

validationcodeexceptionassertassertionargumentcontractpreconditioninvariant

### Embed Badge

![Health badge](/badges/hediet-contracts/health.svg)

```
[![Health](https://phpackages.com/badges/hediet-contracts/health.svg)](https://phpackages.com/packages/hediet-contracts)
```

###  Alternatives

[beberlei/assert

Thin assertion library for input validation in business models.

2.4k96.9M570](/packages/beberlei-assert)[vimeo/psalm

A static analysis tool for finding errors in PHP applications

5.8k77.5M6.7k](/packages/vimeo-psalm)[elliotchance/concise

Concise is test framework for using plain English and minimal code, built on PHPUnit.

45223.8k4](/packages/elliotchance-concise)[nilportugues/assert

A simple and elegant assertion and guard methods library for input validation.

1066.0k7](/packages/nilportugues-assert)[respect/assertion

The power of Respect\\Validation into an assertion library

2828.0k](/packages/respect-assertion)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
