You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

287 lines
16 KiB

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