| 1 |
This package provides an alternative to PHP's `assert()` that allows for an simple and reliable way |
| 2 |
to check preconditions and postconditions in PHP code. It was proposed [as a MediaWiki RFC](https://www.mediawiki.org/wiki/Requests_for_comment/Assert), |
| 3 |
but is completely generic and can be used by any PHP program or library. It is published under the |
| 4 |
MIT license, see the COPYING file. |
| 5 |
|
| 6 |
Usage |
| 7 |
------- |
| 8 |
|
| 9 |
The Assert class provides several static methods for checking various kinds of assertions. |
| 10 |
The most common kind is to check the type of a parameter, typically in a constructor or a |
| 11 |
setter method: |
| 12 |
|
| 13 |
```php |
| 14 |
function setFoo( $foo ) { |
| 15 |
Assert::parameterType( 'integer', $foo, 'foo' ); |
| 16 |
Assert::parameter( $foo > 0, 'foo', 'must be greater than 0' ); |
| 17 |
} |
| 18 |
|
| 19 |
function __construct( $bar, array $bazz ) { |
| 20 |
Assert::parameterType( 'Me\MyApp\SomeClass', $bar ); |
| 21 |
Assert::parameterElementType( 'int', $bazz ); |
| 22 |
} |
| 23 |
``` |
| 24 |
|
| 25 |
Checking parameters, or other assertions such as pre- or postconditions, is not recommended for |
| 26 |
performance critical regions of the code, since evaluating expressions and calling the assertion |
| 27 |
functions costs time. |
| 28 |
|
| 29 |
|
| 30 |
Rationale |
| 31 |
----------- |
| 32 |
The background of this proposal is the recurring discussions about whether PHP's `assert()` |
| 33 |
can and should be used in MediaWiki code. Two relevant threads: |
| 34 |
* [Using PHP's assert in MediaWiki code](http://www.gossamer-threads.com/lists/wiki/wikitech/275737) |
| 35 |
* [Is assert() allowed?](http://www.gossamer-threads.com/lists/wiki/wikitech/378676) |
| 36 |
|
| 37 |
The outcome appears to be that |
| 38 |
* assertions are generally a good way to improve code quality |
| 39 |
* but PHP's ''assert()'' is broken by design |
| 40 |
|
| 41 |
Following a [suggestion by Tim Starling](http://www.gossamer-threads.com/lists/wiki/wikitech/378815#378815), |
| 42 |
this package provides an alternative to PHP's built in `assert()`. |