AssertionChain.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 assertions.
  17. *
  18. * @author Benjamin Eberlei <kontakt@beberlei.de>
  19. *
  20. * @method AssertionChain alnum(string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric.
  21. * @method AssertionChain base64(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined.
  22. * @method AssertionChain 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 AssertionChain 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 AssertionChain 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 AssertionChain boolean(string|callable $message = null, string $propertyPath = null) Assert that value is php boolean.
  26. * @method AssertionChain choice(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices.
  27. * @method AssertionChain 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 AssertionChain classExists(string|callable $message = null, string $propertyPath = null) Assert that the class exists.
  29. * @method AssertionChain contains(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars.
  30. * @method AssertionChain count(int $count, string|callable $message = null, string $propertyPath = null) Assert that the count of countable is equal to count.
  31. * @method AssertionChain date(string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format.
  32. * @method AssertionChain defined(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined.
  33. * @method AssertionChain digit(string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit.
  34. * @method AssertionChain directory(string|callable $message = null, string $propertyPath = null) Assert that a directory exists.
  35. * @method AssertionChain e164(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number.
  36. * @method AssertionChain email(string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL).
  37. * @method AssertionChain endsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars.
  38. * @method AssertionChain eq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using ==).
  39. * @method AssertionChain eqArraySubset(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that the array contains the subset.
  40. * @method AssertionChain extensionLoaded(string|callable $message = null, string $propertyPath = null) Assert that extension is loaded.
  41. * @method AssertionChain 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 AssertionChain false(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False.
  43. * @method AssertionChain file(string|callable $message = null, string $propertyPath = null) Assert that a file exists.
  44. * @method AssertionChain float(string|callable $message = null, string $propertyPath = null) Assert that value is a php float.
  45. * @method AssertionChain greaterOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit.
  46. * @method AssertionChain greaterThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit.
  47. * @method AssertionChain implementsInterface(string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface.
  48. * @method AssertionChain 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 AssertionChain integer(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer.
  50. * @method AssertionChain integerish(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish.
  51. * @method AssertionChain interfaceExists(string|callable $message = null, string $propertyPath = null) Assert that the interface exists.
  52. * @method AssertionChain ip(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address.
  53. * @method AssertionChain ipv4(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address.
  54. * @method AssertionChain ipv6(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address.
  55. * @method AssertionChain isArray(string|callable $message = null, string $propertyPath = null) Assert that value is an array.
  56. * @method AssertionChain isArrayAccessible(string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object.
  57. * @method AssertionChain isCallable(string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable.
  58. * @method AssertionChain isCountable(string|callable $message = null, string $propertyPath = null) Assert that value is countable.
  59. * @method AssertionChain isInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name.
  60. * @method AssertionChain isJsonString(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string.
  61. * @method AssertionChain isObject(string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object.
  62. * @method AssertionChain isResource(string|callable $message = null, string $propertyPath = null) Assert that value is a resource.
  63. * @method AssertionChain isTraversable(string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object.
  64. * @method AssertionChain keyExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array.
  65. * @method AssertionChain 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 AssertionChain keyNotExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array.
  67. * @method AssertionChain length(int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length.
  68. * @method AssertionChain lessOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit.
  69. * @method AssertionChain lessThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit.
  70. * @method AssertionChain max(mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit.
  71. * @method AssertionChain maxCount(int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at most $count elements.
  72. * @method AssertionChain 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 AssertionChain methodExists(mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object.
  74. * @method AssertionChain 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 AssertionChain minCount(int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at least $count elements.
  76. * @method AssertionChain 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 AssertionChain noContent(string|callable $message = null, string $propertyPath = null) Assert that value is empty.
  78. * @method AssertionChain notBlank(string|callable $message = null, string $propertyPath = null) Assert that value is not blank.
  79. * @method AssertionChain 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 AssertionChain notEmpty(string|callable $message = null, string $propertyPath = null) Assert that value is not empty.
  81. * @method AssertionChain 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 AssertionChain notEq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using ==).
  83. * @method AssertionChain notInArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices.
  84. * @method AssertionChain notIsInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name.
  85. * @method AssertionChain notNull(string|callable $message = null, string $propertyPath = null) Assert that value is not null.
  86. * @method AssertionChain notRegex(string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value does not match a regex.
  87. * @method AssertionChain notSame(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using ===).
  88. * @method AssertionChain null(string|callable $message = null, string $propertyPath = null) Assert that value is null.
  89. * @method AssertionChain numeric(string|callable $message = null, string $propertyPath = null) Assert that value is numeric.
  90. * @method AssertionChain objectOrClass(string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists.
  91. * @method AssertionChain phpVersion(mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version.
  92. * @method AssertionChain 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 AssertionChain 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 AssertionChain range(mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers.
  95. * @method AssertionChain readable(string|callable $message = null, string $propertyPath = null) Assert that the value is something readable.
  96. * @method AssertionChain regex(string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex.
  97. * @method AssertionChain same(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===).
  98. * @method AssertionChain satisfy(callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback.
  99. * @method AssertionChain scalar(string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar.
  100. * @method AssertionChain startsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars.
  101. * @method AssertionChain string(string|callable $message = null, string $propertyPath = null) Assert that value is a string.
  102. * @method AssertionChain subclassOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name.
  103. * @method AssertionChain true(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True.
  104. * @method AssertionChain uniqueValues(string|callable $message = null, string $propertyPath = null) Assert that values in array are unique (using strict equality).
  105. * @method AssertionChain url(string|callable $message = null, string $propertyPath = null) Assert that value is an URL.
  106. * @method AssertionChain uuid(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID.
  107. * @method AssertionChain version(string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions.
  108. * @method AssertionChain writeable(string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable.
  109. */
  110. class AssertionChain
  111. {
  112. /**
  113. * @var mixed
  114. */
  115. private $value;
  116. /**
  117. * @var string|callable|null
  118. */
  119. private $defaultMessage;
  120. /**
  121. * @var string|null
  122. */
  123. private $defaultPropertyPath;
  124. /**
  125. * Return each assertion as always valid.
  126. *
  127. * @var bool
  128. */
  129. private $alwaysValid = false;
  130. /**
  131. * Perform assertion on every element of array or traversable.
  132. *
  133. * @var bool
  134. */
  135. private $all = false;
  136. /** @var string|Assertion Class to use for assertion calls */
  137. private $assertionClassName = 'Assert\Assertion';
  138. /**
  139. * AssertionChain constructor.
  140. *
  141. * @param mixed $value
  142. * @param string|callable|null $defaultMessage
  143. */
  144. public function __construct($value, $defaultMessage = null, ?string $defaultPropertyPath = null)
  145. {
  146. $this->value = $value;
  147. $this->defaultMessage = $defaultMessage;
  148. $this->defaultPropertyPath = $defaultPropertyPath;
  149. }
  150. /**
  151. * Call assertion on the current value in the chain.
  152. *
  153. * @param string $methodName
  154. * @param array $args
  155. */
  156. public function __call($methodName, $args): AssertionChain
  157. {
  158. if (true === $this->alwaysValid) {
  159. return $this;
  160. }
  161. try {
  162. $method = new \ReflectionMethod($this->assertionClassName, $methodName);
  163. } catch (\ReflectionException $exception) {
  164. throw new \RuntimeException("Assertion '".$methodName."' does not exist.");
  165. }
  166. \array_unshift($args, $this->value);
  167. $params = $method->getParameters();
  168. foreach ($params as $idx => $param) {
  169. if (isset($args[$idx])) {
  170. continue;
  171. }
  172. switch ($param->getName()) {
  173. case 'message':
  174. $args[$idx] = $this->defaultMessage;
  175. break;
  176. case 'propertyPath':
  177. $args[$idx] = $this->defaultPropertyPath;
  178. break;
  179. }
  180. }
  181. if ($this->all) {
  182. $methodName = 'all'.$methodName;
  183. }
  184. \call_user_func_array([$this->assertionClassName, $methodName], $args);
  185. return $this;
  186. }
  187. /**
  188. * Switch chain into validation mode for an array of values.
  189. */
  190. public function all(): AssertionChain
  191. {
  192. $this->all = true;
  193. return $this;
  194. }
  195. /**
  196. * Switch chain into mode allowing nulls, ignoring further assertions.
  197. */
  198. public function nullOr(): AssertionChain
  199. {
  200. if (null === $this->value) {
  201. $this->alwaysValid = true;
  202. }
  203. return $this;
  204. }
  205. /**
  206. * @param string $className
  207. *
  208. * @return $this
  209. */
  210. public function setAssertionClassName($className): AssertionChain
  211. {
  212. if (!\is_string($className)) {
  213. throw new LogicException('Exception class name must be passed as a string');
  214. }
  215. if (Assertion::class !== $className && !\is_subclass_of($className, Assertion::class)) {
  216. throw new LogicException($className.' is not (a subclass of) '.Assertion::class);
  217. }
  218. $this->assertionClassName = $className;
  219. return $this;
  220. }
  221. }