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