1Webmozart Assert
2================
3
4[](https://packagist.org/packages/webmozart/assert)
5[](https://packagist.org/packages/webmozart/assert)
6
7This library contains efficient assertions to test the input and output of
8your methods. With these assertions, you can greatly reduce the amount of coding
9needed to write a safe implementation.
10
11All assertions in the [`Assert`] class throw an `Webmozart\Assert\InvalidArgumentException` if
12they fail.
13
14FAQ
15---
16
17**What's the difference to [beberlei/assert]?**
18
19This library is heavily inspired by Benjamin Eberlei's wonderful [assert package],
20but fixes a usability issue with error messages that can't be fixed there without
21breaking backwards compatibility.
22
23This package features usable error messages by default. However, you can also
24easily write custom error messages:
25
26```
27Assert::string($path, 'The path is expected to be a string. Got: %s');
28```
29
30In [beberlei/assert], the ordering of the `%s` placeholders is different for
31every assertion. This package, on the contrary, provides consistent placeholder
32ordering for all assertions:
33
34* `%s`: The tested value as string, e.g. `"/foo/bar"`.
35* `%2$s`, `%3$s`, ...: Additional assertion-specific values, e.g. the
36 minimum/maximum length, allowed values, etc.
37
38Check the source code of the assertions to find out details about the additional
39available placeholders.
40
41Installation
42------------
43
44Use [Composer] to install the package:
45
46```bash
47composer require webmozart/assert
48```
49
50Example
51-------
52
53```php
54use Webmozart\Assert\Assert;
55
56class Employee
57{
58 public function __construct($id)
59 {
60 Assert::integer($id, 'The employee ID must be an integer. Got: %s');
61 Assert::greaterThan($id, 0, 'The employee ID must be a positive integer. Got: %s');
62 }
63}
64```
65
66If you create an employee with an invalid ID, an exception is thrown:
67
68```php
69new Employee('foobar');
70// => Webmozart\Assert\InvalidArgumentException:
71// The employee ID must be an integer. Got: string
72
73new Employee(-10);
74// => Webmozart\Assert\InvalidArgumentException:
75// The employee ID must be a positive integer. Got: -10
76```
77
78Assertions
79----------
80
81The [`Assert`] class provides the following assertions:
82
83### Type Assertions
84
85Method | Description
86-------------------------------------------------------- | --------------------------------------------------
87`string($value, $message = '')` | Check that a value is a string
88`stringNotEmpty($value, $message = '')` | Check that a value is a non-empty string
89`integer($value, $message = '')` | Check that a value is an integer
90`integerish($value, $message = '')` | Check that a value casts to an integer
91`positiveInteger($value, $message = '')` | Check that a value is a positive (non-zero) integer
92`float($value, $message = '')` | Check that a value is a float
93`numeric($value, $message = '')` | Check that a value is numeric
94`natural($value, $message= ''')` | Check that a value is a non-negative integer
95`boolean($value, $message = '')` | Check that a value is a boolean
96`scalar($value, $message = '')` | Check that a value is a scalar
97`object($value, $message = '')` | Check that a value is an object
98`resource($value, $type = null, $message = '')` | Check that a value is a resource
99`isCallable($value, $message = '')` | Check that a value is a callable
100`isArray($value, $message = '')` | Check that a value is an array
101`isTraversable($value, $message = '')` (deprecated) | Check that a value is an array or a `\Traversable`
102`isIterable($value, $message = '')` | Check that a value is an array or a `\Traversable`
103`isCountable($value, $message = '')` | Check that a value is an array or a `\Countable`
104`isInstanceOf($value, $class, $message = '')` | Check that a value is an `instanceof` a class
105`isInstanceOfAny($value, array $classes, $message = '')` | Check that a value is an `instanceof` at least one class on the array of classes
106`notInstanceOf($value, $class, $message = '')` | Check that a value is not an `instanceof` a class
107`isAOf($value, $class, $message = '')` | Check that a value is of the class or has one of its parents
108`isAnyOf($value, array $classes, $message = '')` | Check that a value is of at least one of the classes or has one of its parents
109`isNotA($value, $class, $message = '')` | Check that a value is not of the class or has not one of its parents
110`isArrayAccessible($value, $message = '')` | Check that a value can be accessed as an array
111`uniqueValues($values, $message = '')` | Check that the given array contains unique values
112
113### Comparison Assertions
114
115Method | Description
116----------------------------------------------- | ------------------------------------------------------------------
117`true($value, $message = '')` | Check that a value is `true`
118`false($value, $message = '')` | Check that a value is `false`
119`notFalse($value, $message = '')` | Check that a value is not `false`
120`null($value, $message = '')` | Check that a value is `null`
121`notNull($value, $message = '')` | Check that a value is not `null`
122`isEmpty($value, $message = '')` | Check that a value is `empty()`
123`notEmpty($value, $message = '')` | Check that a value is not `empty()`
124`eq($value, $value2, $message = '')` | Check that a value equals another (`==`)
125`notEq($value, $value2, $message = '')` | Check that a value does not equal another (`!=`)
126`same($value, $value2, $message = '')` | Check that a value is identical to another (`===`)
127`notSame($value, $value2, $message = '')` | Check that a value is not identical to another (`!==`)
128`greaterThan($value, $value2, $message = '')` | Check that a value is greater than another
129`greaterThanEq($value, $value2, $message = '')` | Check that a value is greater than or equal to another
130`lessThan($value, $value2, $message = '')` | Check that a value is less than another
131`lessThanEq($value, $value2, $message = '')` | Check that a value is less than or equal to another
132`range($value, $min, $max, $message = '')` | Check that a value is within a range
133`inArray($value, array $values, $message = '')` | Check that a value is one of a list of values
134`oneOf($value, array $values, $message = '')` | Check that a value is one of a list of values (alias of `inArray`)
135
136### String Assertions
137
138You should check that a value is a string with `Assert::string()` before making
139any of the following assertions.
140
141Method | Description
142--------------------------------------------------- | -----------------------------------------------------------------
143`contains($value, $subString, $message = '')` | Check that a string contains a substring
144`notContains($value, $subString, $message = '')` | Check that a string does not contain a substring
145`startsWith($value, $prefix, $message = '')` | Check that a string has a prefix
146`notStartsWith($value, $prefix, $message = '')` | Check that a string does not have a prefix
147`startsWithLetter($value, $message = '')` | Check that a string starts with a letter
148`endsWith($value, $suffix, $message = '')` | Check that a string has a suffix
149`notEndsWith($value, $suffix, $message = '')` | Check that a string does not have a suffix
150`regex($value, $pattern, $message = '')` | Check that a string matches a regular expression
151`notRegex($value, $pattern, $message = '')` | Check that a string does not match a regular expression
152`unicodeLetters($value, $message = '')` | Check that a string contains Unicode letters only
153`alpha($value, $message = '')` | Check that a string contains letters only
154`digits($value, $message = '')` | Check that a string contains digits only
155`alnum($value, $message = '')` | Check that a string contains letters and digits only
156`lower($value, $message = '')` | Check that a string contains lowercase characters only
157`upper($value, $message = '')` | Check that a string contains uppercase characters only
158`length($value, $length, $message = '')` | Check that a string has a certain number of characters
159`minLength($value, $min, $message = '')` | Check that a string has at least a certain number of characters
160`maxLength($value, $max, $message = '')` | Check that a string has at most a certain number of characters
161`lengthBetween($value, $min, $max, $message = '')` | Check that a string has a length in the given range
162`uuid($value, $message = '')` | Check that a string is a valid UUID
163`ip($value, $message = '')` | Check that a string is a valid IP (either IPv4 or IPv6)
164`ipv4($value, $message = '')` | Check that a string is a valid IPv4
165`ipv6($value, $message = '')` | Check that a string is a valid IPv6
166`email($value, $message = '')` | Check that a string is a valid e-mail address
167`notWhitespaceOnly($value, $message = '')` | Check that a string contains at least one non-whitespace character
168
169### File Assertions
170
171Method | Description
172----------------------------------- | --------------------------------------------------
173`fileExists($value, $message = '')` | Check that a value is an existing path
174`file($value, $message = '')` | Check that a value is an existing file
175`directory($value, $message = '')` | Check that a value is an existing directory
176`readable($value, $message = '')` | Check that a value is a readable path
177`writable($value, $message = '')` | Check that a value is a writable path
178
179### Object Assertions
180
181Method | Description
182----------------------------------------------------- | --------------------------------------------------
183`classExists($value, $message = '')` | Check that a value is an existing class name
184`subclassOf($value, $class, $message = '')` | Check that a class is a subclass of another
185`interfaceExists($value, $message = '')` | Check that a value is an existing interface name
186`implementsInterface($value, $class, $message = '')` | Check that a class implements an interface
187`propertyExists($value, $property, $message = '')` | Check that a property exists in a class/object
188`propertyNotExists($value, $property, $message = '')` | Check that a property does not exist in a class/object
189`methodExists($value, $method, $message = '')` | Check that a method exists in a class/object
190`methodNotExists($value, $method, $message = '')` | Check that a method does not exist in a class/object
191
192### Array Assertions
193
194Method | Description
195-------------------------------------------------- | ------------------------------------------------------------------
196`keyExists($array, $key, $message = '')` | Check that a key exists in an array
197`keyNotExists($array, $key, $message = '')` | Check that a key does not exist in an array
198`validArrayKey($key, $message = '')` | Check that a value is a valid array key (int or string)
199`count($array, $number, $message = '')` | Check that an array contains a specific number of elements
200`minCount($array, $min, $message = '')` | Check that an array contains at least a certain number of elements
201`maxCount($array, $max, $message = '')` | Check that an array contains at most a certain number of elements
202`countBetween($array, $min, $max, $message = '')` | Check that an array has a count in the given range
203`isList($array, $message = '')` | Check that an array is a non-associative list
204`isNonEmptyList($array, $message = '')` | Check that an array is a non-associative list, and not empty
205`isMap($array, $message = '')` | Check that an array is associative and has strings as keys
206`isNonEmptyMap($array, $message = '')` | Check that an array is associative and has strings as keys, and is not empty
207
208### Function Assertions
209
210Method | Description
211------------------------------------------- | -----------------------------------------------------------------------------------------------------
212`throws($closure, $class, $message = '')` | Check that a function throws a certain exception. Subclasses of the exception class will be accepted.
213
214### Collection Assertions
215
216All of the above assertions can be prefixed with `all*()` to test the contents
217of an array or a `\Traversable`:
218
219```php
220Assert::allIsInstanceOf($employees, 'Acme\Employee');
221```
222
223### Nullable Assertions
224
225All of the above assertions can be prefixed with `nullOr*()` to run the
226assertion only if it the value is not `null`:
227
228```php
229Assert::nullOrString($middleName, 'The middle name must be a string or null. Got: %s');
230```
231
232### Extending Assert
233
234The `Assert` class comes with a few methods, which can be overridden to change the class behaviour. You can also extend it to
235add your own assertions.
236
237#### Overriding methods
238
239Overriding the following methods in your assertion class allows you to change the behaviour of the assertions:
240
241* `public static function __callStatic($name, $arguments)`
242 * This method is used to 'create' the `nullOr` and `all` versions of the assertions.
243* `protected static function valueToString($value)`
244 * This method is used for error messages, to convert the value to a string value for displaying. You could use this for representing a value object with a `__toString` method for example.
245* `protected static function typeToString($value)`
246 * This method is used for error messages, to convert the a value to a string representing its type.
247* `protected static function strlen($value)`
248 * This method is used to calculate string length for relevant methods, using the `mb_strlen` if available and useful.
249* `protected static function reportInvalidArgument($message)`
250 * This method is called when an assertion fails, with the specified error message. Here you can throw your own exception, or log something.
251
252## Static analysis support
253
254Where applicable, assertion functions are annotated to support Psalm's
255[Assertion syntax](https://psalm.dev/docs/annotating_code/assertion_syntax/).
256A dedicated [PHPStan Plugin](https://github.com/phpstan/phpstan-webmozart-assert) is
257required for proper type support.
258
259Authors
260-------
261
262* [Bernhard Schussek] a.k.a. [@webmozart]
263* [The Community Contributors]
264
265Contribute
266----------
267
268Contributions to the package are always welcome!
269
270* Report any bugs or issues you find on the [issue tracker].
271* You can grab the source code at the package's [Git repository].
272
273License
274-------
275
276All contents of this package are licensed under the [MIT license].
277
278[beberlei/assert]: https://github.com/beberlei/assert
279[assert package]: https://github.com/beberlei/assert
280[Composer]: https://getcomposer.org
281[Bernhard Schussek]: https://webmozarts.com
282[The Community Contributors]: https://github.com/webmozart/assert/graphs/contributors
283[issue tracker]: https://github.com/webmozart/assert/issues
284[Git repository]: https://github.com/webmozart/assert
285[@webmozart]: https://twitter.com/webmozart
286[MIT license]: LICENSE
287[`Assert`]: src/Assert.php
288