مقایسه محصولات در دسته شربت سرماخوردگی کودکان
static::generateMessage($message ?: 'Array does not contain an element with key "%s"'),
static::stringify($key)
);
throw static::createException($value, $message, static::INVALID_KEY_EXISTS, $propertyPath, ['key' => $key]);
}
return true;
}
/**
* Assert that key does not exist in an array.
*
* @param mixed $value
* @param string|int $key
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function keyNotExists($value, $key, $message = null, string $propertyPath = null): bool
{
static::isArray($value, $message, $propertyPath);
if (\array_key_exists($key, $value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Array contains an element with key "%s"'),
static::stringify($key)
);
throw static::createException($value, $message, static::INVALID_KEY_NOT_EXISTS, $propertyPath, ['key' => $key]);
}
return true;
}
/**
* Assert that values in array are unique (using strict equality).
*
* @param mixed[] $values
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function uniqueValues(array $values, $message = null, string $propertyPath = null): bool
{
foreach ($values as $key => $value) {
if (\array_search($value, $values, true) !== $key) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" occurs more than once in array'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_UNIQUE_VALUES, $propertyPath, ['value' => $value]);
}
}
return true;
}
/**
* Assert that key exists in an array/array-accessible object using isset().
*
* @param mixed $value
* @param string|int $key
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function keyIsset($value, $key, $message = null, string $propertyPath = null): bool
{
static::isArrayAccessible($value, $message, $propertyPath);
if (!isset($value[$key])) {
$message = \sprintf(
static::generateMessage($message ?: 'The element with key "%s" was not found'),
static::stringify($key)
);
throw static::createException($value, $message, static::INVALID_KEY_ISSET, $propertyPath, ['key' => $key]);
}
return true;
}
/**
* Assert that key exists in an array/array-accessible object and its value is not empty.
*
* @param mixed $value
* @param string|int $key
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function notEmptyKey($value, $key, $message = null, string $propertyPath = null): bool
{
static::keyIsset($value, $key, $message, $propertyPath);
static::notEmpty($value[$key], $message, $propertyPath);
return true;
}
/**
* Assert that value is not blank.
*
* @param mixed $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function notBlank($value, $message = null, string $propertyPath = null): bool
{
if (false === $value || (empty($value) && '0' != $value) || (\is_string($value) && '' === \trim($value))) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" is blank, but was expected to contain a value.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_NOT_BLANK, $propertyPath);
}
return true;
}
/**
* Assert that value is instance of given class-name.
*
* @param mixed $value
* @param string $className
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-template ExpectedType of object
* @psalm-param class-string $className
* @psalm-assert ExpectedType $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function isInstanceOf($value, $className, $message = null, string $propertyPath = null): bool
{
if (!($value instanceof $className)) {
$message = \sprintf(
static::generateMessage($message ?: 'Class "%s" was expected to be instanceof of "%s" but is not.'),
static::stringify($value),
$className
);
throw static::createException($value, $message, static::INVALID_INSTANCE_OF, $propertyPath, ['class' => $className]);
}
return true;
}
/**
* Assert that value is not instance of given class-name.
*
* @param mixed $value
* @param string $className
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-template ExpectedType of object
* @psalm-param class-string $className
* @psalm-assert !ExpectedType $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function notIsInstanceOf($value, $className, $message = null, string $propertyPath = null): bool
{
if ($value instanceof $className) {
$message = \sprintf(
static::generateMessage($message ?: 'Class "%s" was not expected to be instanceof of "%s".'),
static::stringify($value),
$className
);
throw static::createException($value, $message, static::INVALID_NOT_INSTANCE_OF, $propertyPath, ['class' => $className]);
}
return true;
}
/**
* Assert that value is subclass of given class-name.
*
* @param mixed $value
* @param string $className
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function subclassOf($value, $className, $message = null, string $propertyPath = null): bool
{
if (!\is_subclass_of($value, $className)) {
$message = \sprintf(
static::generateMessage($message ?: 'Class "%s" was expected to be subclass of "%s".'),
static::stringify($value),
$className
);
throw static::createException($value, $message, static::INVALID_SUBCLASS_OF, $propertyPath, ['class' => $className]);
}
return true;
}
/**
* Assert that value is in range of numbers.
*
* @param mixed $value
* @param mixed $minValue
* @param mixed $maxValue
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert =numeric $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function range($value, $minValue, $maxValue, $message = null, string $propertyPath = null): bool
{
static::numeric($value, $message, $propertyPath);
if ($value < $minValue || $value > $maxValue) {
$message = \sprintf(
static::generateMessage($message ?: 'Number "%s" was expected to be at least "%d" and at most "%d".'),
static::stringify($value),
static::stringify($minValue),
static::stringify($maxValue)
);
throw static::createException($value, $message, static::INVALID_RANGE, $propertyPath, ['min' => $minValue, 'max' => $maxValue]);
}
return true;
}
/**
* Assert that a value is at least as big as a given limit.
*
* @param mixed $value
* @param mixed $minValue
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert =numeric $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function min($value, $minValue, $message = null, string $propertyPath = null): bool
{
static::numeric($value, $message, $propertyPath);
if ($value < $minValue) {
$message = \sprintf(
static::generateMessage($message ?: 'Number "%s" was expected to be at least "%s".'),
static::stringify($value),
static::stringify($minValue)
);
throw static::createException($value, $message, static::INVALID_MIN, $propertyPath, ['min' => $minValue]);
}
return true;
}
/**
* Assert that a number is smaller as a given limit.
*
* @param mixed $value
* @param mixed $maxValue
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert =numeric $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function max($value, $maxValue, $message = null, string $propertyPath = null): bool
{
static::numeric($value, $message, $propertyPath);
if ($value > $maxValue) {
$message = \sprintf(
static::generateMessage($message ?: 'Number "%s" was expected to be at most "%s".'),
static::stringify($value),
static::stringify($maxValue)
);
throw static::createException($value, $message, static::INVALID_MAX, $propertyPath, ['max' => $maxValue]);
}
return true;
}
/**
* Assert that a file exists.
*
* @param string $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function file($value, $message = null, string $propertyPath = null): bool
{
static::string($value, $message, $propertyPath);
static::notEmpty($value, $message, $propertyPath);
if (!\is_file($value)) {
$message = \sprintf(
static::generateMessage($message ?: 'File "%s" was expected to exist.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_FILE, $propertyPath);
}
return true;
}
/**
* Assert that a directory exists.
*
* @param string $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function directory($value, $message = null, string $propertyPath = null): bool
{
static::string($value, $message, $propertyPath);
if (!\is_dir($value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Path "%s" was expected to be a directory.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_DIRECTORY, $propertyPath);
}
return true;
}
/**
* Assert that the value is something readable.
*
* @param string $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function readable($value, $message = null, string $propertyPath = null): bool
{
static::string($value, $message, $propertyPath);
if (!\is_readable($value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Path "%s" was expected to be readable.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_READABLE, $propertyPath);
}
return true;
}
/**
* Assert that the value is something writeable.
*
* @param string $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function writeable($value, $message = null, string $propertyPath = null): bool
{
static::string($value, $message, $propertyPath);
if (!\is_writable($value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Path "%s" was expected to be writeable.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_WRITEABLE, $propertyPath);
}
return true;
}
/**
* Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL).
*
* @param mixed $value
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert =string $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function email($value, $message = null, string $propertyPath = null): bool
{
static::string($value, $message, $propertyPath);
if (!\filter_var($value, FILTER_VALIDATE_EMAIL)) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" was expected to be a valid e-mail address.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_EMAIL, $propertyPath);
}
return true;
}
/**
* Assert that value is an URL.
*
* This code snipped was taken from the Symfony project and modified to the special demands of this method.
*
* @param mixed $value
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert =string $value
*
* @return bool
*
* @throws AssertionFailedException
*
* @see https://github.com/symfony/Validator/blob/master/Constraints/UrlValidator.php
* @see https://github.com/symfony/Validator/blob/master/Constraints/Url.php
*/
public static function url($value, $message = null, string $propertyPath = null): bool
{
static::string($value, $message, $propertyPath);
$protocols = ['http', 'https'];
$pattern = '~^
(%s):// # protocol
(([\.\pL\pN-]+:)?([\.\pL\pN-]+)@)? # basic auth
(
([\pL\pN\pS\-\.])+(\.?([\pL\pN]|xn\-\-[\pL\pN-]+)+\.?) # a domain name
| # or
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address
| # or
\[
(?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::))))
\] # an IPv6 address
)
(:[0-9]+)? # a port (optional)
(?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%%[0-9A-Fa-f]{2})* )* # a path
(?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a query (optional)
(?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a fragment (optional)
$~ixu';
$pattern = \sprintf($pattern, \implode('|', $protocols));
if (!\preg_match($pattern, $value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" was expected to be a valid URL starting with http or https'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_URL, $propertyPath);
}
return true;
}
/**
* Assert that value is alphanumeric.
*
* @param mixed $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function alnum($value, $message = null, string $propertyPath = null): bool
{
try {
static::regex($value, '(^([a-zA-Z]{1}[a-zA-Z0-9]*)$)', $message, $propertyPath);
} catch (Throwable $e) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" is not alphanumeric, starting with letters and containing only letters and numbers.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_ALNUM, $propertyPath);
}
return true;
}
/**
* Assert that the value is boolean True.
*
* @param mixed $value
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert true $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function true($value, $message = null, string $propertyPath = null): bool
{
if (true !== $value) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" is not TRUE.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_TRUE, $propertyPath);
}
return true;
}
/**
* Assert that the value is boolean False.
*
* @param mixed $value
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert false $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function false($value, $message = null, string $propertyPath = null): bool
{
if (false !== $value) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" is not FALSE.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_FALSE, $propertyPath);
}
return true;
}
/**
* Assert that the class exists.
*
* @param mixed $value
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert class-string $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function classExists($value, $message = null, string $propertyPath = null): bool
{
if (!\class_exists($value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Class "%s" does not exist.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_CLASS, $propertyPath);
}
return true;
}
/**
* Assert that the interface exists.
*
* @param mixed $value
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert class-string $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function interfaceExists($value, $message = null, string $propertyPath = null): bool
{
if (!\interface_exists($value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Interface "%s" does not exist.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_INTERFACE, $propertyPath);
}
return true;
}
/**
* Assert that the class implements the interface.
*
* @param mixed $class
* @param string $interfaceName
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function implementsInterface($class, $interfaceName, $message = null, string $propertyPath = null): bool
{
try {
$reflection = new ReflectionClass($class);
if (!$reflection->implementsInterface($interfaceName)) {
$message = \sprintf(
static::generateMessage($message ?: 'Class "%s" does not implement interface "%s".'),
static::stringify($class),
static::stringify($interfaceName)
);
throw static::createException($class, $message, static::INTERFACE_NOT_IMPLEMENTED, $propertyPath, ['interface' => $interfaceName]);
}
} catch (ReflectionException $e) {
$message = \sprintf(
static::generateMessage($message ?: 'Class "%s" failed reflection.'),
static::stringify($class)
);
throw static::createException($class, $message, static::INTERFACE_NOT_IMPLEMENTED, $propertyPath, ['interface' => $interfaceName]);
}
return true;
}
/**
* Assert that the given string is a valid json string.
*
* NOTICE:
* Since this does a json_decode to determine its validity
* you probably should consider, when using the variable
* content afterwards, just to decode and check for yourself instead
* of using this assertion.
*
* @param mixed $value
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert =string $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function isJsonString($value, $message = null, string $propertyPath = null): bool
{
if (null === \json_decode($value) && JSON_ERROR_NONE !== \json_last_error()) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" is not a valid JSON string.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_JSON_STRING, $propertyPath);
}
return true;
}
/**
* Assert that the given string is a valid UUID.
*
* Uses code from {@link https://github.com/ramsey/uuid} that is MIT licensed.
*
* @param string $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function uuid($value, $message = null, string $propertyPath = null): bool
{
$value = \str_replace(['urn:', 'uuid:', '{', '}'], '', $value);
if ('00000000-0000-0000-0000-000000000000' === $value) {
return true;
}
if (!\preg_match('/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/', $value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" is not a valid UUID.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_UUID, $propertyPath);
}
return true;
}
/**
* Assert that the given string is a valid E164 Phone Number.
*
* @see https://en.wikipedia.org/wiki/E.164
*
* @param string $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function e164($value, $message = null, string $propertyPath = null): bool
{
if (!\preg_match('/^\+?[1-9]\d{1,14}$/', $value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" is not a valid E164.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_E164, $propertyPath);
}
return true;
}
/**
* Assert that the count of countable is equal to count.
*
* @param array|Countable|ResourceBundle|SimpleXMLElement $countable
* @param int $count
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function count($countable, $count, $message = null, string $propertyPath = null): bool
{
if ($count !== \count($countable)) {
$message = \sprintf(
static::generateMessage($message ?: 'List does not contain exactly %d elements (%d given).'),
static::stringify($count),
static::stringify(\count($countable))
);
throw static::createException($countable, $message, static::INVALID_COUNT, $propertyPath, ['count' => $count]);
}
return true;
}
/**
* Assert that the countable have at least $count elements.
*
* @param array|Countable|ResourceBundle|SimpleXMLElement $countable
* @param int $count
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function minCount($countable, $count, $message = null, string $propertyPath = null): bool
{
if ($count > \count($countable)) {
$message = \sprintf(
static::generateMessage($message ?: 'List should have at least %d elements, but has %d elements.'),
static::stringify($count),
static::stringify(\count($countable))
);
throw static::createException($countable, $message, static::INVALID_MIN_COUNT, $propertyPath, ['count' => $count]);
}
return true;
}
/**
* Assert that the countable have at most $count elements.
*
* @param array|Countable|ResourceBundle|SimpleXMLElement $countable
* @param int $count
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function maxCount($countable, $count, $message = null, string $propertyPath = null): bool
{
if ($count < \count($countable)) {
$message = \sprintf(
static::generateMessage($message ?: 'List should have at most %d elements, but has %d elements.'),
static::stringify($count),
static::stringify(\count($countable))
);
throw static::createException($countable, $message, static::INVALID_MAX_COUNT, $propertyPath, ['count' => $count]);
}
return true;
}
/**
* static call handler to implement:
* - "null or assertion" delegation
* - "all" delegation.
*
* @param string $method
* @param array $args
*
* @return bool|mixed
*
* @throws AssertionFailedException
*/
public static function __callStatic($method, $args)
{
if (0 === \strpos($method, 'nullOr')) {
if (!\array_key_exists(0, $args)) {
throw new BadMethodCallException('Missing the first argument.');
}
if (null === $args[0]) {
return true;
}
$method = \substr($method, 6);
return \call_user_func_array([\get_called_class(), $method], $args);
}
if (0 === \strpos($method, 'all')) {
if (!\array_key_exists(0, $args)) {
throw new BadMethodCallException('Missing the first argument.');
}
static::isTraversable($args[0]);
$method = \substr($method, 3);
$values = \array_shift($args);
$calledClass = \get_called_class();
foreach ($values as $value) {
\call_user_func_array([$calledClass, $method], \array_merge([$value], $args));
}
return true;
}
throw new BadMethodCallException('No assertion Assertion#'.$method.' exists.');
}
/**
* Determines if the values array has every choice as key and that this choice has content.
*
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function choicesNotEmpty(array $values, array $choices, $message = null, string $propertyPath = null): bool
{
static::notEmpty($values, $message, $propertyPath);
foreach ($choices as $choice) {
static::notEmptyKey($values, $choice, $message, $propertyPath);
}
return true;
}
/**
* Determines that the named method is defined in the provided object.
*
* @param string $value
* @param mixed $object
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function methodExists($value, $object, $message = null, string $propertyPath = null): bool
{
static::isObject($object, $message, $propertyPath);
if (!\method_exists($object, $value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Expected "%s" does not exist in provided object.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_METHOD, $propertyPath, ['object' => \get_class($object)]);
}
return true;
}
/**
* Determines that the provided value is an object.
*
* @param mixed $value
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert object $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function isObject($value, $message = null, string $propertyPath = null): bool
{
if (!\is_object($value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Provided "%s" is not a valid object.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_OBJECT, $propertyPath);
}
return true;
}
/**
* Determines if the value is less than given limit.
*
* @param mixed $value
* @param mixed $limit
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function lessThan($value, $limit, $message = null, string $propertyPath = null): bool
{
if ($value >= $limit) {
$message = \sprintf(
static::generateMessage($message ?: 'Provided "%s" is not less than "%s".'),
static::stringify($value),
static::stringify($limit)
);
throw static::createException($value, $message, static::INVALID_LESS, $propertyPath, ['limit' => $limit]);
}
return true;
}
/**
* Determines if the value is less or equal than given limit.
*
* @param mixed $value
* @param mixed $limit
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function lessOrEqualThan($value, $limit, $message = null, string $propertyPath = null): bool
{
if ($value > $limit) {
$message = \sprintf(
static::generateMessage($message ?: 'Provided "%s" is not less or equal than "%s".'),
static::stringify($value),
static::stringify($limit)
);
throw static::createException($value, $message, static::INVALID_LESS_OR_EQUAL, $propertyPath, ['limit' => $limit]);
}
return true;
}
/**
* Determines if the value is greater than given limit.
*
* @param mixed $value
* @param mixed $limit
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function greaterThan($value, $limit, $message = null, string $propertyPath = null): bool
{
if ($value <= $limit) {
$message = \sprintf(
static::generateMessage($message ?: 'Provided "%s" is not greater than "%s".'),
static::stringify($value),
static::stringify($limit)
);
throw static::createException($value, $message, static::INVALID_GREATER, $propertyPath, ['limit' => $limit]);
}
return true;
}
/**
* Determines if the value is greater or equal than given limit.
*
* @param mixed $value
* @param mixed $limit
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function greaterOrEqualThan($value, $limit, $message = null, string $propertyPath = null): bool
{
if ($value < $limit) {
$message = \sprintf(
static::generateMessage($message ?: 'Provided "%s" is not greater or equal than "%s".'),
static::stringify($value),
static::stringify($limit)
);
throw static::createException($value, $message, static::INVALID_GREATER_OR_EQUAL, $propertyPath, ['limit' => $limit]);
}
return true;
}
/**
* Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit.
*
* @param mixed $value
* @param mixed $lowerLimit
* @param mixed $upperLimit
* @param string|callable|null $message
* @param string $propertyPath
*
* @throws AssertionFailedException
*/
public static function between($value, $lowerLimit, $upperLimit, $message = null, string $propertyPath = null): bool
{
if ($lowerLimit > $value || $value > $upperLimit) {
$message = \sprintf(
static::generateMessage($message ?: 'Provided "%s" is neither greater than or equal to "%s" nor less than or equal to "%s".'),
static::stringify($value),
static::stringify($lowerLimit),
static::stringify($upperLimit)
);
throw static::createException($value, $message, static::INVALID_BETWEEN, $propertyPath, ['lower' => $lowerLimit, 'upper' => $upperLimit]);
}
return true;
}
/**
* Assert that a value is greater than a lower limit, and less than an upper limit.
*
* @param mixed $value
* @param mixed $lowerLimit
* @param mixed $upperLimit
* @param string|callable|null $message
* @param string $propertyPath
*
* @throws AssertionFailedException
*/
public static function betweenExclusive($value, $lowerLimit, $upperLimit, $message = null, string $propertyPath = null): bool
{
if ($lowerLimit >= $value || $value >= $upperLimit) {
$message = \sprintf(
static::generateMessage($message ?: 'Provided "%s" is neither greater than "%s" nor less than "%s".'),
static::stringify($value),
static::stringify($lowerLimit),
static::stringify($upperLimit)
);
throw static::createException($value, $message, static::INVALID_BETWEEN_EXCLUSIVE, $propertyPath, ['lower' => $lowerLimit, 'upper' => $upperLimit]);
}
return true;
}
/**
* Assert that extension is loaded.
*
* @param mixed $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function extensionLoaded($value, $message = null, string $propertyPath = null): bool
{
if (!\extension_loaded($value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Extension "%s" is required.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_EXTENSION, $propertyPath);
}
return true;
}
/**
* Assert that date is valid and corresponds to the given format.
*
* @param string $value
* @param string $format supports all of the options date(), except for the following:
* N, w, W, t, L, o, B, a, A, g, h, I, O, P, Z, c, r
* @param string|callable|null $message
*
* @throws AssertionFailedException
*
* @see http://php.net/manual/function.date.php#refsect1-function.date-parameters
*/
public static function date($value, $format, $message = null, string $propertyPath = null): bool
{
static::string($value, $message, $propertyPath);
static::string($format, $message, $propertyPath);
$dateTime = DateTime::createFromFormat('!'.$format, $value);
if (false === $dateTime || $value !== $dateTime->format($format)) {
$message = \sprintf(
static::generateMessage($message ?: 'Date "%s" is invalid or does not match format "%s".'),
static::stringify($value),
static::stringify($format)
);
throw static::createException($value, $message, static::INVALID_DATE, $propertyPath, ['format' => $format]);
}
return true;
}
/**
* Assert that the value is an object, or a class that exists.
*
* @param mixed $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function objectOrClass($value, $message = null, string $propertyPath = null): bool
{
if (!\is_object($value)) {
static::classExists($value, $message, $propertyPath);
}
return true;
}
/**
* Assert that the value is an object or class, and that the property exists.
*
* @param mixed $value
* @param string $property
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function propertyExists($value, $property, $message = null, string $propertyPath = null): bool
{
static::objectOrClass($value);
if (!\property_exists($value, $property)) {
$message = \sprintf(
static::generateMessage($message ?: 'Class "%s" does not have property "%s".'),
static::stringify($value),
static::stringify($property)
);
throw static::createException($value, $message, static::INVALID_PROPERTY, $propertyPath, ['property' => $property]);
}
return true;
}
/**
* Assert that the value is an object or class, and that the properties all exist.
*
* @param mixed $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function propertiesExist($value, array $properties, $message = null, string $propertyPath = null): bool
{
static::objectOrClass($value);
static::allString($properties, $message, $propertyPath);
$invalidProperties = [];
foreach ($properties as $property) {
if (!\property_exists($value, $property)) {
$invalidProperties[] = $property;
}
}
if ($invalidProperties) {
$message = \sprintf(
static::generateMessage($message ?: 'Class "%s" does not have these properties: %s.'),
static::stringify($value),
static::stringify(\implode(', ', $invalidProperties))
);
throw static::createException($value, $message, static::INVALID_PROPERTY, $propertyPath, ['properties' => $properties]);
}
return true;
}
/**
* Assert comparison of two versions.
*
* @param string $version1
* @param string $operator
* @param string $version2
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function version($version1, $operator, $version2, $message = null, string $propertyPath = null): bool
{
static::notEmpty($operator, 'versionCompare operator is required and cannot be empty.');
if (true !== \version_compare($version1, $version2, $operator)) {
$message = \sprintf(
static::generateMessage($message ?: 'Version "%s" is not "%s" version "%s".'),
static::stringify($version1),
static::stringify($operator),
static::stringify($version2)
);
throw static::createException($version1, $message, static::INVALID_VERSION, $propertyPath, ['operator' => $operator, 'version' => $version2]);
}
return true;
}
/**
* Assert on PHP version.
*
* @param string $operator
* @param mixed $version
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function phpVersion($operator, $version, $message = null, string $propertyPath = null): bool
{
static::defined('PHP_VERSION');
return static::version(PHP_VERSION, $operator, $version, $message, $propertyPath);
}
/**
* Assert that extension is loaded and a specific version is installed.
*
* @param string $extension
* @param string $operator
* @param mixed $version
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function extensionVersion($extension, $operator, $version, $message = null, string $propertyPath = null): bool
{
static::extensionLoaded($extension, $message, $propertyPath);
return static::version(\phpversion($extension), $operator, $version, $message, $propertyPath);
}
/**
* Determines that the provided value is callable.
*
* @param mixed $value
* @param string|callable|null $message
* @param string|null $propertyPath
*
* @psalm-assert callable $value
*
* @return bool
*
* @throws AssertionFailedException
*/
public static function isCallable($value, $message = null, string $propertyPath = null): bool
{
if (!\is_callable($value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Provided "%s" is not a callable.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_CALLABLE, $propertyPath);
}
return true;
}
/**
* Assert that the provided value is valid according to a callback.
*
* If the callback returns `false` the assertion will fail.
*
* @param mixed $value
* @param callable $callback
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function satisfy($value, $callback, $message = null, string $propertyPath = null): bool
{
static::isCallable($callback);
if (false === \call_user_func($callback, $value)) {
$message = \sprintf(
static::generateMessage($message ?: 'Provided "%s" is invalid according to custom rule.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_SATISFY, $propertyPath);
}
return true;
}
/**
* Assert that value is an IPv4 or IPv6 address
* (using input_filter/FILTER_VALIDATE_IP).
*
* @param string $value
* @param int|null $flag
* @param string|callable|null $message
*
* @throws AssertionFailedException
*
* @see http://php.net/manual/filter.filters.flags.php
*/
public static function ip($value, $flag = null, $message = null, string $propertyPath = null): bool
{
static::string($value, $message, $propertyPath);
if ($flag === null) {
$filterVarResult = \filter_var($value, FILTER_VALIDATE_IP);
} else {
$filterVarResult = \filter_var($value, FILTER_VALIDATE_IP, $flag);
}
if (!$filterVarResult) {
$message = \sprintf(
static::generateMessage($message ?: 'Value "%s" was expected to be a valid IP address.'),
static::stringify($value)
);
throw static::createException($value, $message, static::INVALID_IP, $propertyPath, ['flag' => $flag]);
}
return true;
}
/**
* Assert that value is an IPv4 address
* (using input_filter/FILTER_VALIDATE_IP).
*
* @param string $value
* @param int|null $flag
* @param string|callable|null $message
*
* @throws AssertionFailedException
*
* @see http://php.net/manual/filter.filters.flags.php
*/
public static function ipv4($value, $flag = null, $message = null, string $propertyPath = null): bool
{
static::ip($value, $flag | FILTER_FLAG_IPV4, static::generateMessage($message ?: 'Value "%s" was expected to be a valid IPv4 address.'), $propertyPath);
return true;
}
/**
* Assert that value is an IPv6 address
* (using input_filter/FILTER_VALIDATE_IP).
*
* @param string $value
* @param int|null $flag
* @param string|callable|null $message
*
* @throws AssertionFailedException
*
* @see http://php.net/manual/filter.filters.flags.php
*/
public static function ipv6($value, $flag = null, $message = null, string $propertyPath = null): bool
{
static::ip($value, $flag | FILTER_FLAG_IPV6, static::generateMessage($message ?: 'Value "%s" was expected to be a valid IPv6 address.'), $propertyPath);
return true;
}
/**
* Assert that a constant is defined.
*
* @param mixed $constant
* @param string|callable|null $message
*/
public static function defined($constant, $message = null, string $propertyPath = null): bool
{
if (!\defined($constant)) {
$message = \sprintf(static::generateMessage($message ?: 'Value "%s" expected to be a defined constant.'), $constant);
throw static::createException($constant, $message, static::INVALID_CONSTANT, $propertyPath);
}
return true;
}
/**
* Assert that a constant is defined.
*
* @param string $value
* @param string|callable|null $message
*
* @throws AssertionFailedException
*/
public static function base64($value, $message = null, string $propertyPath = null): bool
{
if (false === \base64_decode($value, true)) {
$message = \sprintf(static::generateMessage($message ?: 'Value "%s" is not a valid base64 string.'), $value);
throw static::createException($value, $message, static::INVALID_BASE64, $propertyPath);
}
return true;
}
/**
* Helper method that handles building the assertion failure exceptions.
* They are returned from this method so that the stack trace still shows
* the assertions method.
*
* @param mixed $value
* @param string|callable|null $message
* @param int $code
*
* @return mixed
*/
protected static function createException($value, $message, $code, $propertyPath = null, array $constraints = [])
{
$exceptionClass = static::$exceptionClass;
return new $exceptionClass($message, $code, $propertyPath, $value, $constraints);
}
/**
* Make a string version of a value.
*
* @param mixed $value
*/
protected static function stringify($value): string
{
$result = \gettype($value);
if (\is_bool($value)) {
$result = $value ? '' : '';
} elseif (\is_scalar($value)) {
$val = (string)$value;
if (\mb_strlen($val) > 100) {
$val = \mb_substr($val, 0, 97).'...';
}
$result = $val;
} elseif (\is_array($value)) {
$result = '';
} elseif (\is_object($value)) {
$result = \get_class($value);
} elseif (\is_resource($value)) {
$result = \get_resource_type($value);
} elseif (null === $value) {
$result = '';
}
return $result;
}
/**
* Generate the message.
*
* @param string|callable|null $message
*/
protected static function generateMessage($message): string
{
if (\is_callable($message)) {
$traces = \debug_backtrace(0);
$parameters = [];
try {
$reflection = new ReflectionClass($traces[1]['class']);
$method = $reflection->getMethod($traces[1]['function']);
foreach ($method->getParameters() as $index => $parameter) {
if ('message' !== $parameter->getName()) {
$parameters[$parameter->getName()] = \array_key_exists($index, $traces[1]['args'])
? $traces[1]['args'][$index]
: $parameter->getDefaultValue();
}
}
$parameters['::assertion'] = \sprintf('%s%s%s', $traces[1]['class'], $traces[1]['type'], $traces[1]['function']);
$message = \call_user_func_array($message, [$parameters]);
} // @codeCoverageIgnoreStart
catch (Throwable $exception) {
$message = \sprintf('Unable to generate message : %s', $exception->getMessage());
} // @codeCoverageIgnoreEnd
}
return (string)$message;
}
}