LazyAssertion.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. /**
  3. * Assert
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * If you did not receive a copy of the license and are unable to
  10. * obtain it through the world-wide-web, please send an email
  11. * to kontakt@beberlei.de so I can send you a copy immediately.
  12. */
  13. namespace Assert;
  14. use LogicException;
  15. /**
  16. * Chaining builder for lazy assertions.
  17. *
  18. * @author Benjamin Eberlei <kontakt@beberlei.de>
  19. *
  20. * @method LazyAssertion alnum(string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric.
  21. * @method LazyAssertion base64(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined.
  22. * @method LazyAssertion between(mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit.
  23. * @method LazyAssertion betweenExclusive(mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater than a lower limit, and less than an upper limit.
  24. * @method LazyAssertion betweenLength(int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min and max lengths.
  25. * @method LazyAssertion boolean(string|callable $message = null, string $propertyPath = null) Assert that value is php boolean.
  26. * @method LazyAssertion choice(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices.
  27. * @method LazyAssertion choicesNotEmpty(array $choices, string|callable $message = null, string $propertyPath = null) Determines if the values array has every choice as key and that this choice has content.
  28. * @method LazyAssertion classExists(string|callable $message = null, string $propertyPath = null) Assert that the class exists.
  29. * @method LazyAssertion contains(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars.
  30. * @method LazyAssertion count(int $count, string|callable $message = null, string $propertyPath = null) Assert that the count of countable is equal to count.
  31. * @method LazyAssertion date(string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format.
  32. * @method LazyAssertion defined(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined.
  33. * @method LazyAssertion digit(string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit.
  34. * @method LazyAssertion directory(string|callable $message = null, string $propertyPath = null) Assert that a directory exists.
  35. * @method LazyAssertion e164(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number.
  36. * @method LazyAssertion email(string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL).
  37. * @method LazyAssertion endsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars.
  38. * @method LazyAssertion eq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using ==).
  39. * @method LazyAssertion eqArraySubset(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that the array contains the subset.
  40. * @method LazyAssertion extensionLoaded(string|callable $message = null, string $propertyPath = null) Assert that extension is loaded.
  41. * @method LazyAssertion extensionVersion(string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed.
  42. * @method LazyAssertion false(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False.
  43. * @method LazyAssertion file(string|callable $message = null, string $propertyPath = null) Assert that a file exists.
  44. * @method LazyAssertion float(string|callable $message = null, string $propertyPath = null) Assert that value is a php float.
  45. * @method LazyAssertion greaterOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit.
  46. * @method LazyAssertion greaterThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit.
  47. * @method LazyAssertion implementsInterface(string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface.
  48. * @method LazyAssertion inArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice().
  49. * @method LazyAssertion integer(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer.
  50. * @method LazyAssertion integerish(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish.
  51. * @method LazyAssertion interfaceExists(string|callable $message = null, string $propertyPath = null) Assert that the interface exists.
  52. * @method LazyAssertion ip(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address.
  53. * @method LazyAssertion ipv4(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address.
  54. * @method LazyAssertion ipv6(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address.
  55. * @method LazyAssertion isArray(string|callable $message = null, string $propertyPath = null) Assert that value is an array.
  56. * @method LazyAssertion isArrayAccessible(string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object.
  57. * @method LazyAssertion isCallable(string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable.
  58. * @method LazyAssertion isCountable(string|callable $message = null, string $propertyPath = null) Assert that value is countable.
  59. * @method LazyAssertion isInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name.
  60. * @method LazyAssertion isJsonString(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string.
  61. * @method LazyAssertion isObject(string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object.
  62. * @method LazyAssertion isResource(string|callable $message = null, string $propertyPath = null) Assert that value is a resource.
  63. * @method LazyAssertion isTraversable(string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object.
  64. * @method LazyAssertion keyExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array.
  65. * @method LazyAssertion keyIsset(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset().
  66. * @method LazyAssertion keyNotExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array.
  67. * @method LazyAssertion length(int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length.
  68. * @method LazyAssertion lessOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit.
  69. * @method LazyAssertion lessThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit.
  70. * @method LazyAssertion max(mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit.
  71. * @method LazyAssertion maxCount(int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at most $count elements.
  72. * @method LazyAssertion maxLength(int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars.
  73. * @method LazyAssertion methodExists(mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object.
  74. * @method LazyAssertion min(mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit.
  75. * @method LazyAssertion minCount(int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at least $count elements.
  76. * @method LazyAssertion minLength(int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long.
  77. * @method LazyAssertion noContent(string|callable $message = null, string $propertyPath = null) Assert that value is empty.
  78. * @method LazyAssertion notBlank(string|callable $message = null, string $propertyPath = null) Assert that value is not blank.
  79. * @method LazyAssertion notContains(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string does not contains a sequence of chars.
  80. * @method LazyAssertion notEmpty(string|callable $message = null, string $propertyPath = null) Assert that value is not empty.
  81. * @method LazyAssertion notEmptyKey(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty.
  82. * @method LazyAssertion notEq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using ==).
  83. * @method LazyAssertion notInArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices.
  84. * @method LazyAssertion notIsInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name.
  85. * @method LazyAssertion notNull(string|callable $message = null, string $propertyPath = null) Assert that value is not null.
  86. * @method LazyAssertion notRegex(string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value does not match a regex.
  87. * @method LazyAssertion notSame(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using ===).
  88. * @method LazyAssertion null(string|callable $message = null, string $propertyPath = null) Assert that value is null.
  89. * @method LazyAssertion numeric(string|callable $message = null, string $propertyPath = null) Assert that value is numeric.
  90. * @method LazyAssertion objectOrClass(string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists.
  91. * @method LazyAssertion phpVersion(mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version.
  92. * @method LazyAssertion propertiesExist(array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist.
  93. * @method LazyAssertion propertyExists(string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists.
  94. * @method LazyAssertion range(mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers.
  95. * @method LazyAssertion readable(string|callable $message = null, string $propertyPath = null) Assert that the value is something readable.
  96. * @method LazyAssertion regex(string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex.
  97. * @method LazyAssertion same(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===).
  98. * @method LazyAssertion satisfy(callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback.
  99. * @method LazyAssertion scalar(string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar.
  100. * @method LazyAssertion startsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars.
  101. * @method LazyAssertion string(string|callable $message = null, string $propertyPath = null) Assert that value is a string.
  102. * @method LazyAssertion subclassOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name.
  103. * @method LazyAssertion true(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True.
  104. * @method LazyAssertion uniqueValues(string|callable $message = null, string $propertyPath = null) Assert that values in array are unique (using strict equality).
  105. * @method LazyAssertion url(string|callable $message = null, string $propertyPath = null) Assert that value is an URL.
  106. * @method LazyAssertion uuid(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID.
  107. * @method LazyAssertion version(string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions.
  108. * @method LazyAssertion writeable(string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable.
  109. * @method LazyAssertion all() Switch chain into validation mode for an array of values.
  110. * @method LazyAssertion nullOr() Switch chain into mode allowing nulls, ignoring further assertions.
  111. */
  112. class LazyAssertion
  113. {
  114. private $currentChainFailed = false;
  115. private $alwaysTryAll = false;
  116. private $thisChainTryAll = false;
  117. private $currentChain;
  118. private $errors = [];
  119. /** @var string The class to use as AssertionChain factory */
  120. private $assertClass = Assert::class;
  121. /** @var string|LazyAssertionException The class to use for exceptions */
  122. private $exceptionClass = LazyAssertionException::class;
  123. /**
  124. * @param mixed $value
  125. * @param string|callable|null $defaultMessage
  126. *
  127. * @return static
  128. */
  129. public function that($value, ?string $propertyPath = null, $defaultMessage = null)
  130. {
  131. $this->currentChainFailed = false;
  132. $this->thisChainTryAll = false;
  133. $assertClass = $this->assertClass;
  134. $this->currentChain = $assertClass::that($value, $defaultMessage, $propertyPath);
  135. return $this;
  136. }
  137. /**
  138. * @return static
  139. */
  140. public function tryAll()
  141. {
  142. if (!$this->currentChain) {
  143. $this->alwaysTryAll = true;
  144. }
  145. $this->thisChainTryAll = true;
  146. return $this;
  147. }
  148. /**
  149. * @param string $method
  150. * @param array $args
  151. *
  152. * @return static
  153. */
  154. public function __call($method, $args)
  155. {
  156. if (false === $this->alwaysTryAll
  157. && false === $this->thisChainTryAll
  158. && true === $this->currentChainFailed
  159. ) {
  160. return $this;
  161. }
  162. try {
  163. \call_user_func_array([$this->currentChain, $method], $args);
  164. } catch (AssertionFailedException $e) {
  165. $this->errors[] = $e;
  166. $this->currentChainFailed = true;
  167. }
  168. return $this;
  169. }
  170. /**
  171. * @throws LazyAssertionException
  172. */
  173. public function verifyNow(): bool
  174. {
  175. if ($this->errors) {
  176. throw \call_user_func([$this->exceptionClass, 'fromErrors'], $this->errors);
  177. }
  178. return true;
  179. }
  180. /**
  181. * @param string $className
  182. *
  183. * @return static
  184. */
  185. public function setAssertClass(string $className): LazyAssertion
  186. {
  187. if (Assert::class !== $className && !\is_subclass_of($className, Assert::class)) {
  188. throw new LogicException($className.' is not (a subclass of) '.Assert::class);
  189. }
  190. $this->assertClass = $className;
  191. return $this;
  192. }
  193. /**
  194. * @param string $className
  195. *
  196. * @return static
  197. */
  198. public function setExceptionClass(string $className): LazyAssertion
  199. {
  200. if (LazyAssertionException::class !== $className && !\is_subclass_of($className, LazyAssertionException::class)) {
  201. throw new LogicException($className.' is not (a subclass of) '.LazyAssertionException::class);
  202. }
  203. $this->exceptionClass = $className;
  204. return $this;
  205. }
  206. }