diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 520b0ba2..882d150e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,6 +4,5 @@ Thanks for contributing to assert! Just follow these single guidelines: - You must use [feature / topic branches](https://git-scm.com/book/en/v2/Git-Branching-Branching-Workflows) to ease the merge of contributions. - Coding standard compliance must be ensured before committing or opening pull requests by running `composer assert:cs-fix` or `composer assert:cs-lint` in the root directory of this repository. -- After adding new assertions regenerate the [README.md](README.md) and the docblocks by running `composer assert:generate-docs` on the command line. +- After adding new assertions regenerate the [README.md](README.md) and the docblocks by running `composer assert:generate` on the command line. - After adding new non release relevant artifacts you must ensure they are export ignored in the [.gitattributes](.gitattributes) file. - diff --git a/UPGRADE_3.0.md b/UPGRADE_3.0.md new file mode 100644 index 00000000..8db98576 --- /dev/null +++ b/UPGRADE_3.0.md @@ -0,0 +1,16 @@ +# Upgrade notes + +Dropped php 5.3 support. + +Error code constants in `Assertion` class are now deprecated and will be removed in 4.0 release. +Preferred way is to use constants from `Assert\Assertion` namespace as follows: +``` +# before 3.0: +\Assert\Assertion::INVALID_JSON_STRING + +# 3.0: +\Assert\Assertion\INVALID_JSON_STRING +``` +So you need to replace `::` with `\` before constant name. + +These can be easily done with following regular expression search and replace: search for `Assertion::([A-Z_\d]+)` and replace with `Assertion\\$1`. diff --git a/bin/generate_method_docs.php b/bin/generate_code.php similarity index 82% rename from bin/generate_method_docs.php rename to bin/generate_code.php index 58fc00ad..3cab3a86 100644 --- a/bin/generate_method_docs.php +++ b/bin/generate_code.php @@ -104,7 +104,7 @@ private function gatherAssertions() return \array_filter( $reflClass->getMethods(ReflectionMethod::IS_STATIC), function (ReflectionMethod $reflMethod) { - if ($reflMethod->isProtected()) { + if (!$reflMethod->isPublic()) { return false; } @@ -142,6 +142,14 @@ private function generateFile($phpFile, $lines, $fileType) $fileContent ); break; + + case 'const': + $fileContent = \preg_replace( + '`// constants linked for BC\n(.*)// end constants linked for BC\n`sim', + \sprintf("// constants linked for BC\n %s\n // end constants linked for BC\n", \trim(\implode("\n", $lines))), + $fileContent + ); + break; } $writtenBytes = \file_put_contents($phpFile, $fileContent); @@ -215,11 +223,55 @@ function (ReflectionMethod $reflMethod) { } ); } + + public function generateConstants() + { + $phpFile = __DIR__.'/../lib/Assert/Assertion.php'; + $constants = $this->gatherConstants(); + + $this->generateFile($phpFile, $constants, 'const'); + } + + /** + * @return string[] + */ + private function gatherConstants() + { + $namespace = 'Assert\\Assertion\\'; + + // load class to load all traits and fill namespace with constants + /* @noinspection ExceptionsAnnotatingAndHandlingInspection */ + \Assert\Assertion::string($namespace); + + $constants = \get_defined_constants(true); + if (!isset($constants['user'])) { + return []; + } + + $constants = \array_keys($constants['user']); + + $namespaceConstants = \array_filter($constants, function ($name) use ($namespace) { + return 0 === \strpos($name, $namespace); + }); + + return \array_map(function ($name) use ($namespace) { + $const = \substr($name, \strlen($namespace)); + + return <<generateConstants(); $generator->generateAssertionDocs(); $generator->generateChainDocs(); $generator->generateLazyAssertionDocs(); diff --git a/bin/travis/lint-docs b/bin/travis/lint-docs index 1a6725bb..99262596 100755 --- a/bin/travis/lint-docs +++ b/bin/travis/lint-docs @@ -1,8 +1,8 @@ #!/bin/bash set -e -composer assert:generate-docs +composer assert:generate UNCOMMITED_FILES=$(git status -s | wc -l) if [[ $UNCOMMITED_FILES -ne 0 ]]; then - echo "Please run composer assert:generate-docs and commit the changes"; + echo "Please run composer assert:generate and commit the changes"; exit 1; fi diff --git a/composer.json b/composer.json index 3345cb27..68a6cfb2 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,7 @@ "sort-packages": true }, "require": { - "php": ">=5.3", + "php": ">=5.4", "ext-mbstring": "*" }, "require-dev": { @@ -35,7 +35,8 @@ "Assert\\": "lib/Assert" }, "files": [ - "lib/Assert/functions.php" + "lib/Assert/functions.php", + "lib/Assert/Assertion.php" ] }, "autoload-dev": { @@ -47,7 +48,7 @@ ] }, "scripts": { - "assert:generate-docs": "php bin/generate_method_docs.php", + "assert:generate": "php bin/generate_code.php", "assert:cs-lint": "php-cs-fixer fix --diff -vvv --dry-run", "assert:cs-fix": "php-cs-fixer fix . -vvv || true" } diff --git a/lib/Assert/Assertion.php b/lib/Assert/Assertion.php index 28a9bf4a..088d6f23 100644 --- a/lib/Assert/Assertion.php +++ b/lib/Assert/Assertion.php @@ -14,6 +14,14 @@ namespace Assert; +use Assert\Assertion\ArrayTrait; +use Assert\Assertion\CallableTrait; +use Assert\Assertion\ClassTrait; +use Assert\Assertion\CompareTrait; +use Assert\Assertion\EnvironmentTrait; +use Assert\Assertion\FileSystemTrait; +use Assert\Assertion\ObjectTrait; +use Assert\Assertion\ScalarTrait; use BadMethodCallException; /** @@ -22,7 +30,6 @@ * @author Benjamin Eberlei * * @method static bool allAlnum(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric for all values. - * @method static bool allBase64(string $value, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined for all values. * @method static bool allBetween(mixed $value, mixed $lowerLimit, mixed $upperLimit, string $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 for all values. * @method static bool allBetweenExclusive(mixed $value, mixed $lowerLimit, mixed $upperLimit, string $message = null, string $propertyPath = null) Assert that a value is greater than a lower limit, and less than an upper limit for all values. * @method static bool allBetweenLength(mixed $value, int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min,max lengths for all values. @@ -31,13 +38,13 @@ * @method static bool allChoicesNotEmpty(array $values, 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 for all values. * @method static bool allClassExists(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the class exists for all values. * @method static bool allContains(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars for all values. - * @method static bool allCount(array|\Countable $countable, int $count, string $message = null, string $propertyPath = null) Assert that the count of countable is equal to count for all values. + * @method static bool allCount(array|\Countable $countable, array|\Countable $count, string $message = null, string $propertyPath = null) Assert that the count of countable is equal to count for all values. * @method static bool allDate(string $value, string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format for all values. * @method static bool allDefined(mixed $constant, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined for all values. * @method static bool allDigit(mixed $value, string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit for all values. * @method static bool allDirectory(string $value, string|callable $message = null, string $propertyPath = null) Assert that a directory exists for all values. * @method static bool allE164(string $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number for all values. - * @method static bool allEmail(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL) for all values. + * @method static bool allEmail(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an email adress (using input_filter/FILTER_VALIDATE_EMAIL) for all values. * @method static bool allEndsWith(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars for all values. * @method static bool allEq(mixed $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using == ) for all values. * @method static bool allExtensionLoaded(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded for all values. @@ -67,7 +74,7 @@ * @method static bool allKeyIsset(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset() for all values. * @method static bool allKeyNotExists(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array for all values. * @method static bool allLength(mixed $value, int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length for all values. - * @method static bool allLessOrEqualThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit for all values. + * @method static bool allLessOrEqualThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or than given limit for all values. * @method static bool allLessThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit for all values. * @method static bool allMax(mixed $value, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit for all values. * @method static bool allMaxLength(mixed $value, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars for all values. @@ -104,7 +111,6 @@ * @method static bool allVersion(string $version1, string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions for all values. * @method static bool allWriteable(string $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable for all values. * @method static bool nullOrAlnum(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric or that the value is null. - * @method static bool nullOrBase64(string $value, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined or that the value is null. * @method static bool nullOrBetween(mixed $value, mixed $lowerLimit, mixed $upperLimit, string $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 or that the value is null. * @method static bool nullOrBetweenExclusive(mixed $value, mixed $lowerLimit, mixed $upperLimit, string $message = null, string $propertyPath = null) Assert that a value is greater than a lower limit, and less than an upper limit or that the value is null. * @method static bool nullOrBetweenLength(mixed $value, int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min,max lengths or that the value is null. @@ -113,13 +119,13 @@ * @method static bool nullOrChoicesNotEmpty(array $values, 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 or that the value is null. * @method static bool nullOrClassExists(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the class exists or that the value is null. * @method static bool nullOrContains(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars or that the value is null. - * @method static bool nullOrCount(array|\Countable $countable, int $count, string $message = null, string $propertyPath = null) Assert that the count of countable is equal to count or that the value is null. + * @method static bool nullOrCount(array|\Countable $countable, array|\Countable $count, string $message = null, string $propertyPath = null) Assert that the count of countable is equal to count or that the value is null. * @method static bool nullOrDate(string $value, string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format or that the value is null. * @method static bool nullOrDefined(mixed $constant, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined or that the value is null. * @method static bool nullOrDigit(mixed $value, string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit or that the value is null. * @method static bool nullOrDirectory(string $value, string|callable $message = null, string $propertyPath = null) Assert that a directory exists or that the value is null. * @method static bool nullOrE164(string $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number or that the value is null. - * @method static bool nullOrEmail(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL) or that the value is null. + * @method static bool nullOrEmail(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an email adress (using input_filter/FILTER_VALIDATE_EMAIL) or that the value is null. * @method static bool nullOrEndsWith(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars or that the value is null. * @method static bool nullOrEq(mixed $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using == ) or that the value is null. * @method static bool nullOrExtensionLoaded(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded or that the value is null. @@ -149,7 +155,7 @@ * @method static bool nullOrKeyIsset(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset() or that the value is null. * @method static bool nullOrKeyNotExists(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array or that the value is null. * @method static bool nullOrLength(mixed $value, int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length or that the value is null. - * @method static bool nullOrLessOrEqualThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit or that the value is null. + * @method static bool nullOrLessOrEqualThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or than given limit or that the value is null. * @method static bool nullOrLessThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit or that the value is null. * @method static bool nullOrMax(mixed $value, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit or that the value is null. * @method static bool nullOrMaxLength(mixed $value, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars or that the value is null. @@ -188,2314 +194,445 @@ */ class Assertion { - const INVALID_FLOAT = 9; - const INVALID_INTEGER = 10; - const INVALID_DIGIT = 11; - const INVALID_INTEGERISH = 12; - const INVALID_BOOLEAN = 13; - const VALUE_EMPTY = 14; - const VALUE_NULL = 15; - const VALUE_NOT_NULL = 25; - const INVALID_STRING = 16; - const INVALID_REGEX = 17; - const INVALID_MIN_LENGTH = 18; - const INVALID_MAX_LENGTH = 19; - const INVALID_STRING_START = 20; - const INVALID_STRING_CONTAINS = 21; - const INVALID_CHOICE = 22; - const INVALID_NUMERIC = 23; - const INVALID_ARRAY = 24; - const INVALID_KEY_EXISTS = 26; - const INVALID_NOT_BLANK = 27; - const INVALID_INSTANCE_OF = 28; - const INVALID_SUBCLASS_OF = 29; - const INVALID_RANGE = 30; - const INVALID_ALNUM = 31; - const INVALID_TRUE = 32; - const INVALID_EQ = 33; - const INVALID_SAME = 34; - const INVALID_MIN = 35; - const INVALID_MAX = 36; - const INVALID_LENGTH = 37; - const INVALID_FALSE = 38; - const INVALID_STRING_END = 39; - const INVALID_UUID = 40; - const INVALID_COUNT = 41; - const INVALID_NOT_EQ = 42; - const INVALID_NOT_SAME = 43; - const INVALID_TRAVERSABLE = 44; - const INVALID_ARRAY_ACCESSIBLE = 45; - const INVALID_KEY_ISSET = 46; - const INVALID_VALUE_IN_ARRAY = 47; - const INVALID_E164 = 48; - const INVALID_BASE64 = 49; - const INVALID_DIRECTORY = 101; - const INVALID_FILE = 102; - const INVALID_READABLE = 103; - const INVALID_WRITEABLE = 104; - const INVALID_CLASS = 105; - const INVALID_INTERFACE = 106; - const INVALID_EMAIL = 201; - const INTERFACE_NOT_IMPLEMENTED = 202; - const INVALID_URL = 203; - const INVALID_NOT_INSTANCE_OF = 204; - const VALUE_NOT_EMPTY = 205; - const INVALID_JSON_STRING = 206; - const INVALID_OBJECT = 207; - const INVALID_METHOD = 208; - const INVALID_SCALAR = 209; - const INVALID_LESS = 210; - const INVALID_LESS_OR_EQUAL = 211; - const INVALID_GREATER = 212; - const INVALID_GREATER_OR_EQUAL = 213; - const INVALID_DATE = 214; - const INVALID_CALLABLE = 215; - const INVALID_KEY_NOT_EXISTS = 216; - const INVALID_SATISFY = 217; - const INVALID_IP = 218; - const INVALID_BETWEEN = 219; - const INVALID_BETWEEN_EXCLUSIVE = 220; - const INVALID_EXTENSION = 222; - const INVALID_CONSTANT = 221; - const INVALID_VERSION = 223; - const INVALID_PROPERTY = 224; - const INVALID_RESOURCE = 225; + use ArrayTrait; + use CallableTrait; + use ClassTrait; + use CompareTrait; + use EnvironmentTrait; + use FileSystemTrait; + use ObjectTrait; + use ScalarTrait; + // constants linked for BC /** - * Exception to throw when an assertion failed. - * - * @var string + * @deprecated + * @see Assertion\INVALID_VALUE_IN_ARRAY */ - protected static $exceptionClass = 'Assert\InvalidArgumentException'; - + const INVALID_VALUE_IN_ARRAY = Assertion\INVALID_VALUE_IN_ARRAY; /** - * 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 $message - * @param int $code - * @param string|null $propertyPath - * @param array $constraints - * - * @return mixed + * @deprecated + * @see Assertion\INVALID_CHOICE */ - protected static function createException($value, $message, $code, $propertyPath = null, array $constraints = array()) - { - $exceptionClass = static::$exceptionClass; - - return new $exceptionClass($message, $code, $propertyPath, $value, $constraints); - } - + const INVALID_CHOICE = Assertion\INVALID_CHOICE; /** - * Assert that two values are equal (using == ). - * - * @param mixed $value - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_TRAVERSABLE */ - public static function eq($value, $value2, $message = null, $propertyPath = null) - { - if ($value != $value2) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" does not equal expected value "%s".', - static::stringify($value), - static::stringify($value2) - ); - - throw static::createException($value, $message, static::INVALID_EQ, $propertyPath, array('expected' => $value2)); - } - - return true; - } - + const INVALID_TRAVERSABLE = Assertion\INVALID_TRAVERSABLE; /** - * Assert that two values are the same (using ===). - * - * @param mixed $value - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_ARRAY */ - public static function same($value, $value2, $message = null, $propertyPath = null) - { - if ($value !== $value2) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not the same as expected value "%s".', - static::stringify($value), - static::stringify($value2) - ); - - throw static::createException($value, $message, static::INVALID_SAME, $propertyPath, array('expected' => $value2)); - } - - return true; - } - + const INVALID_ARRAY = Assertion\INVALID_ARRAY; /** - * Assert that two values are not equal (using == ). - * - * @param mixed $value1 - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_KEY_EXISTS */ - public static function notEq($value1, $value2, $message = null, $propertyPath = null) - { - if ($value1 == $value2) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is equal to expected value "%s".', - static::stringify($value1), - static::stringify($value2) - ); - throw static::createException($value1, $message, static::INVALID_NOT_EQ, $propertyPath, array('expected' => $value2)); - } - - return true; - } - + const INVALID_KEY_EXISTS = Assertion\INVALID_KEY_EXISTS; /** - * Assert that two values are not the same (using === ). - * - * @param mixed $value1 - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_KEY_NOT_EXISTS */ - public static function notSame($value1, $value2, $message = null, $propertyPath = null) - { - if ($value1 === $value2) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is the same as expected value "%s".', - static::stringify($value1), - static::stringify($value2) - ); - throw static::createException($value1, $message, static::INVALID_NOT_SAME, $propertyPath, array('expected' => $value2)); - } - - return true; - } - + const INVALID_KEY_NOT_EXISTS = Assertion\INVALID_KEY_NOT_EXISTS; /** - * Assert that value is not in array of choices. - * - * @param mixed $value - * @param array $choices - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_COUNT */ - public static function notInArray($value, array $choices, $message = null, $propertyPath = null) - { - if (true === \in_array($value, $choices)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is in given "%s".', - static::stringify($value), - static::stringify($choices) - ); - throw static::createException($value, $message, static::INVALID_VALUE_IN_ARRAY, $propertyPath); - } - - return true; - } - + const INVALID_COUNT = Assertion\INVALID_COUNT; /** - * Assert that value is a php integer. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_KEY_ISSET */ - public static function integer($value, $message = null, $propertyPath = null) - { - if (!\is_int($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not an integer.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_INTEGER, $propertyPath); - } - - return true; - } - + const INVALID_KEY_ISSET = Assertion\INVALID_KEY_ISSET; /** - * Assert that value is a php float. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_ARRAY_ACCESSIBLE */ - public static function float($value, $message = null, $propertyPath = null) - { - if (!\is_float($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not a float.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_FLOAT, $propertyPath); - } - - return true; - } - + const INVALID_ARRAY_ACCESSIBLE = Assertion\INVALID_ARRAY_ACCESSIBLE; /** - * Validates if an integer or integerish is a digit. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_CALLABLE */ - public static function digit($value, $message = null, $propertyPath = null) - { - if (!\ctype_digit((string) $value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not a digit.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_DIGIT, $propertyPath); - } - - return true; - } - + const INVALID_CALLABLE = Assertion\INVALID_CALLABLE; /** - * Assert that value is a php integer'ish. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_SATISFY */ - public static function integerish($value, $message = null, $propertyPath = null) - { - if ( - \is_resource($value) || - \is_object($value) || - \is_bool($value) || - \is_null($value) || - \is_array($value) || - (\is_string($value) && '' == $value) || - ( - \strval(\intval($value)) !== \strval($value) && - \strval(\intval($value)) !== \strval(\ltrim($value, '0')) && - '' !== \strval(\intval($value)) && - '' !== \strval(\ltrim($value, '0')) - ) - ) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not an integer or a number castable to integer.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_INTEGERISH, $propertyPath); - } - - return true; - } - + const INVALID_SATISFY = Assertion\INVALID_SATISFY; /** - * Assert that value is php boolean. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_NOT_INSTANCE_OF */ - public static function boolean($value, $message = null, $propertyPath = null) - { - if (!\is_bool($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not a boolean.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_BOOLEAN, $propertyPath); - } - - return true; - } - + const INVALID_NOT_INSTANCE_OF = Assertion\INVALID_NOT_INSTANCE_OF; /** - * Assert that value is a PHP scalar. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_INSTANCE_OF */ - public static function scalar($value, $message = null, $propertyPath = null) - { - if (!\is_scalar($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not a scalar.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_SCALAR, $propertyPath); - } - - return true; - } - + const INVALID_INSTANCE_OF = Assertion\INVALID_INSTANCE_OF; /** - * Assert that value is not empty. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_SUBCLASS_OF */ - public static function notEmpty($value, $message = null, $propertyPath = null) - { - if (empty($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is empty, but non empty value was expected.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_EMPTY, $propertyPath); - } - - return true; - } - + const INVALID_SUBCLASS_OF = Assertion\INVALID_SUBCLASS_OF; /** - * Assert that value is empty. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_CLASS */ - public static function noContent($value, $message = null, $propertyPath = null) - { - if (!empty($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not empty, but empty value was expected.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_NOT_EMPTY, $propertyPath); - } - - return true; - } - + const INVALID_CLASS = Assertion\INVALID_CLASS; /** - * Assert that value is null. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_INTERFACE */ - public static function null($value, $message = null, $propertyPath = null) - { - if (null !== $value) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not null, but null value was expected.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_NOT_NULL, $propertyPath); - } - - return true; - } - + const INVALID_INTERFACE = Assertion\INVALID_INTERFACE; /** - * Assert that value is not null. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INTERFACE_NOT_IMPLEMENTED */ - public static function notNull($value, $message = null, $propertyPath = null) - { - if (null === $value) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is null, but non null value was expected.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_NULL, $propertyPath); - } - - return true; - } - + const INTERFACE_NOT_IMPLEMENTED = Assertion\INTERFACE_NOT_IMPLEMENTED; /** - * Assert that value is a string. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\VALUE_EMPTY */ - public static function string($value, $message = null, $propertyPath = null) - { - if (!\is_string($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" expected to be string, type %s given.', - static::stringify($value), - \gettype($value) - ); - - throw static::createException($value, $message, static::INVALID_STRING, $propertyPath); - } - - return true; - } - + const VALUE_EMPTY = Assertion\VALUE_EMPTY; /** - * Assert that value matches a regex. - * - * @param mixed $value - * @param string $pattern - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\VALUE_NULL */ - public static function regex($value, $pattern, $message = null, $propertyPath = null) - { - static::string($value, $message, $propertyPath); - - if (!\preg_match($pattern, $value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" does not match expression.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_REGEX, $propertyPath, array('pattern' => $pattern)); - } - - return true; - } - + const VALUE_NULL = Assertion\VALUE_NULL; /** - * Assert that string has a given length. - * - * @param mixed $value - * @param int $length - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\VALUE_NOT_NULL */ - public static function length($value, $length, $message = null, $propertyPath = null, $encoding = 'utf8') - { - static::string($value, $message, $propertyPath); - - if (\mb_strlen($value, $encoding) !== $length) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" has to be %d exactly characters long, but length is %d.', - static::stringify($value), - $length, - \mb_strlen($value, $encoding) - ); - - $constraints = array('length' => $length, 'encoding' => $encoding); - throw static::createException($value, $message, static::INVALID_LENGTH, $propertyPath, $constraints); - } - - return true; - } - + const VALUE_NOT_NULL = Assertion\VALUE_NOT_NULL; /** - * Assert that a string is at least $minLength chars long. - * - * @param mixed $value - * @param int $minLength - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_EQ */ - public static function minLength($value, $minLength, $message = null, $propertyPath = null, $encoding = 'utf8') - { - static::string($value, $message, $propertyPath); - - if (\mb_strlen($value, $encoding) < $minLength) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is too short, it should have at least %d characters, but only has %d characters.', - static::stringify($value), - $minLength, - \mb_strlen($value, $encoding) - ); - - $constraints = array('min_length' => $minLength, 'encoding' => $encoding); - throw static::createException($value, $message, static::INVALID_MIN_LENGTH, $propertyPath, $constraints); - } - - return true; - } - + const INVALID_EQ = Assertion\INVALID_EQ; /** - * Assert that string value is not longer than $maxLength chars. - * - * @param mixed $value - * @param int $maxLength - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_SAME */ - public static function maxLength($value, $maxLength, $message = null, $propertyPath = null, $encoding = 'utf8') - { - static::string($value, $message, $propertyPath); - - if (\mb_strlen($value, $encoding) > $maxLength) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is too long, it should have no more than %d characters, but has %d characters.', - static::stringify($value), - $maxLength, - \mb_strlen($value, $encoding) - ); - - $constraints = array('max_length' => $maxLength, 'encoding' => $encoding); - throw static::createException($value, $message, static::INVALID_MAX_LENGTH, $propertyPath, $constraints); - } - - return true; - } - + const INVALID_SAME = Assertion\INVALID_SAME; /** - * Assert that string length is between min,max lengths. - * - * @param mixed $value - * @param int $minLength - * @param int $maxLength - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_NOT_EQ */ - public static function betweenLength($value, $minLength, $maxLength, $message = null, $propertyPath = null, $encoding = 'utf8') - { - static::string($value, $message, $propertyPath); - static::minLength($value, $minLength, $message, $propertyPath, $encoding); - static::maxLength($value, $maxLength, $message, $propertyPath, $encoding); - - return true; - } - + const INVALID_NOT_EQ = Assertion\INVALID_NOT_EQ; /** - * Assert that string starts with a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_NOT_SAME */ - public static function startsWith($string, $needle, $message = null, $propertyPath = null, $encoding = 'utf8') - { - static::string($string, $message, $propertyPath); - - if (0 !== \mb_strpos($string, $needle, null, $encoding)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" does not start with "%s".', - static::stringify($string), - static::stringify($needle) - ); - - $constraints = array('needle' => $needle, 'encoding' => $encoding); - throw static::createException($string, $message, static::INVALID_STRING_START, $propertyPath, $constraints); - } - - return true; - } - + const INVALID_NOT_SAME = Assertion\INVALID_NOT_SAME; /** - * Assert that string ends with a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\VALUE_NOT_EMPTY */ - public static function endsWith($string, $needle, $message = null, $propertyPath = null, $encoding = 'utf8') - { - static::string($string, $message, $propertyPath); - - $stringPosition = \mb_strlen($string, $encoding) - \mb_strlen($needle, $encoding); - - if (\mb_strripos($string, $needle, null, $encoding) !== $stringPosition) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" does not end with "%s".', - static::stringify($string), - static::stringify($needle) - ); - - $constraints = array('needle' => $needle, 'encoding' => $encoding); - throw static::createException($string, $message, static::INVALID_STRING_END, $propertyPath, $constraints); - } - - return true; - } - + const VALUE_NOT_EMPTY = Assertion\VALUE_NOT_EMPTY; /** - * Assert that string contains a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_NOT_BLANK */ - public static function contains($string, $needle, $message = null, $propertyPath = null, $encoding = 'utf8') - { - static::string($string, $message, $propertyPath); - - if (false === \mb_strpos($string, $needle, null, $encoding)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" does not contain "%s".', - static::stringify($string), - static::stringify($needle) - ); - - $constraints = array('needle' => $needle, 'encoding' => $encoding); - throw static::createException($string, $message, static::INVALID_STRING_CONTAINS, $propertyPath, $constraints); - } - - return true; - } - + const INVALID_NOT_BLANK = Assertion\INVALID_NOT_BLANK; /** - * Assert that value is in array of choices. - * - * @param mixed $value - * @param array $choices - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_EXTENSION */ - public static function choice($value, array $choices, $message = null, $propertyPath = null) - { - if (!\in_array($value, $choices, true)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not an element of the valid values: %s', - static::stringify($value), - \implode(', ', \array_map(array(\get_called_class(), 'stringify'), $choices)) - ); - - throw static::createException($value, $message, static::INVALID_CHOICE, $propertyPath, array('choices' => $choices)); - } - - return true; - } - + const INVALID_EXTENSION = Assertion\INVALID_EXTENSION; /** - * Assert that value is in array of choices. - * - * This is an alias of {@see choice()}. - * - * @aliasOf choice() - * - * @param mixed $value - * @param array $choices - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool + * @deprecated + * @see Assertion\INVALID_VERSION */ - public static function inArray($value, array $choices, $message = null, $propertyPath = null) - { - return static::choice($value, $choices, $message, $propertyPath); - } - + const INVALID_VERSION = Assertion\INVALID_VERSION; /** - * Assert that value is numeric. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_CONSTANT */ - public static function numeric($value, $message = null, $propertyPath = null) - { - if (!\is_numeric($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not numeric.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_NUMERIC, $propertyPath); - } - - return true; - } - + const INVALID_CONSTANT = Assertion\INVALID_CONSTANT; /** - * Assert that value is a resource. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_DIRECTORY */ - public static function isResource($value, $message = null, $propertyPath = null) - { - if (!\is_resource($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not a resource.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_RESOURCE, $propertyPath); - } - - return true; - } - + const INVALID_DIRECTORY = Assertion\INVALID_DIRECTORY; /** - * Assert that value is an array. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_FILE */ - public static function isArray($value, $message = null, $propertyPath = null) - { - if (!\is_array($value)) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not an array.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_ARRAY, $propertyPath); - } - - return true; - } - + const INVALID_FILE = Assertion\INVALID_FILE; /** - * Assert that value is an array or a traversable object. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_READABLE */ - public static function isTraversable($value, $message = null, $propertyPath = null) - { - if (!\is_array($value) && !$value instanceof \Traversable) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not an array and does not implement Traversable.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_TRAVERSABLE, $propertyPath); - } - - return true; - } - + const INVALID_READABLE = Assertion\INVALID_READABLE; /** - * Assert that value is an array or an array-accessible object. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_WRITEABLE */ - public static function isArrayAccessible($value, $message = null, $propertyPath = null) - { - if (!\is_array($value) && !$value instanceof \ArrayAccess) { - $message = \sprintf( - static::generateMessage($message) ?: 'Value "%s" is not an array and does not implement ArrayAccess.', - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_ARRAY_ACCESSIBLE, $propertyPath); - } - - return true; - } - + const INVALID_WRITEABLE = Assertion\INVALID_WRITEABLE; /** - * Assert that key exists in an array. - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_RESOURCE */ - public static function keyExists($value, $key, $message = null, $propertyPath = null) - { - static::isArray($value, $message, $propertyPath); - - if (!\array_key_exists($key, $value)) { - $message = \sprintf( - 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, array('key' => $key)); - } - - return true; - } - + const INVALID_RESOURCE = Assertion\INVALID_RESOURCE; /** - * Assert that key does not exist in an array. - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_OBJECT */ - public static function keyNotExists($value, $key, $message = null, $propertyPath = null) - { - 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, array('key' => $key)); - } - - return true; - } - + const INVALID_OBJECT = Assertion\INVALID_OBJECT; /** - * Assert that key exists in an array/array-accessible object using isset(). - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_METHOD */ - public static function keyIsset($value, $key, $message = null, $propertyPath = null) - { - 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, array('key' => $key)); - } - - return true; - } - + const INVALID_METHOD = Assertion\INVALID_METHOD; /** - * 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 - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_PROPERTY */ - public static function notEmptyKey($value, $key, $message = null, $propertyPath = null) - { - static::keyIsset($value, $key, $message, $propertyPath); - static::notEmpty($value[$key], $message, $propertyPath); - - return true; - } - + const INVALID_PROPERTY = Assertion\INVALID_PROPERTY; /** - * Assert that value is not blank. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_SCALAR */ - public static function notBlank($value, $message = null, $propertyPath = null) - { - 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; - } - + const INVALID_SCALAR = Assertion\INVALID_SCALAR; /** - * Assert that value is instance of given class-name. - * - * @param mixed $value - * @param string $className - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_BOOLEAN */ - public static function isInstanceOf($value, $className, $message = null, $propertyPath = null) - { - 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, array('class' => $className)); - } - - return true; - } - + const INVALID_BOOLEAN = Assertion\INVALID_BOOLEAN; /** - * 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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_TRUE */ - public static function notIsInstanceOf($value, $className, $message = null, $propertyPath = null) - { - 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, array('class' => $className)); - } - - return true; - } - + const INVALID_TRUE = Assertion\INVALID_TRUE; /** - * Assert that value is subclass of given class-name. - * - * @param mixed $value - * @param string $className - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_FALSE */ - public static function subclassOf($value, $className, $message = null, $propertyPath = null) - { - 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, array('class' => $className)); - } - - return true; - } - + const INVALID_FALSE = Assertion\INVALID_FALSE; /** - * 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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_BETWEEN */ - public static function range($value, $minValue, $maxValue, $message = null, $propertyPath = null) - { - 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, array('min' => $minValue, 'max' => $maxValue)); - } - - return true; - } - + const INVALID_BETWEEN = Assertion\INVALID_BETWEEN; /** - * 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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_BETWEEN_EXCLUSIVE */ - public static function min($value, $minValue, $message = null, $propertyPath = null) - { - 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, array('min' => $minValue)); - } - - return true; - } - + const INVALID_BETWEEN_EXCLUSIVE = Assertion\INVALID_BETWEEN_EXCLUSIVE; /** - * 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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_INTEGER */ - public static function max($value, $maxValue, $message = null, $propertyPath = null) - { - 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, array('max' => $maxValue)); - } - - return true; - } - + const INVALID_INTEGER = Assertion\INVALID_INTEGER; /** - * Assert that a file exists. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_DIGIT */ - public static function file($value, $message = null, $propertyPath = null) - { - 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; - } - + const INVALID_DIGIT = Assertion\INVALID_DIGIT; /** - * Assert that a directory exists. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_INTEGERISH */ - public static function directory($value, $message = null, $propertyPath = null) - { - 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; - } - + const INVALID_INTEGERISH = Assertion\INVALID_INTEGERISH; /** - * Assert that the value is something readable. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_FLOAT */ - public static function readable($value, $message = null, $propertyPath = null) - { - 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; - } - + const INVALID_FLOAT = Assertion\INVALID_FLOAT; /** - * Assert that the value is something writeable. - * - * @param string $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException - */ - public static function writeable($value, $message = null, $propertyPath = null) - { - 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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_RANGE */ - public static function email($value, $message = null, $propertyPath = null) - { - 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); - } else { - $host = \substr($value, \strpos($value, '@') + 1); - - // Likely not a FQDN, bug in PHP FILTER_VALIDATE_EMAIL prior to PHP 5.3.3 - if (\version_compare(PHP_VERSION, '5.3.3', '<') && false === \strpos($host, '.')) { - $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; - } - + const INVALID_RANGE = Assertion\INVALID_RANGE; /** - * 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 - * - * @return bool - * - * @throws \Assert\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, $propertyPath = null) - { - static::string($value, $message, $propertyPath); - - $protocols = array('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) - (/?|/\S+|\?\S*|\#\S*) # a /, nothing, a / with something, a query or a fragment - $~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 - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException - */ - public static function alnum($value, $message = null, $propertyPath = null) - { - try { - static::regex($value, '(^([a-zA-Z]{1}[a-zA-Z0-9]*)$)', $message, $propertyPath); - } catch (AssertionFailedException $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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException - */ - public static function true($value, $message = null, $propertyPath = null) - { - 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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException - */ - public static function false($value, $message = null, $propertyPath = null) - { - 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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException - */ - public static function classExists($value, $message = null, $propertyPath = null) - { - 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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_NUMERIC */ - public static function interfaceExists($value, $message = null, $propertyPath = null) - { - 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; - } - + const INVALID_NUMERIC = Assertion\INVALID_NUMERIC; /** - * Assert that the class implements the interface. - * - * @param mixed $class - * @param string $interfaceName - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_MIN */ - public static function implementsInterface($class, $interfaceName, $message = null, $propertyPath = null) - { - $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, array('interface' => $interfaceName)); - } - - return true; - } - + const INVALID_MIN = Assertion\INVALID_MIN; /** - * 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 - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_MAX */ - public static function isJsonString($value, $message = null, $propertyPath = null) - { - 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; - } - + const INVALID_MAX = Assertion\INVALID_MAX; /** - * 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 - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_LESS */ - public static function uuid($value, $message = null, $propertyPath = null) - { - $value = \str_replace(array('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; - } - + const INVALID_LESS = Assertion\INVALID_LESS; /** - * 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 - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_LESS_OR_EQUAL */ - public static function e164($value, $message = null, $propertyPath = null) - { - 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; - } - + const INVALID_LESS_OR_EQUAL = Assertion\INVALID_LESS_OR_EQUAL; /** - * Assert that the count of countable is equal to count. - * - * @param array|\Countable $countable - * @param int $count - * @param string|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_GREATER */ - public static function count($countable, $count, $message = null, $propertyPath = null) - { - if ($count !== \count($countable)) { - $message = \sprintf( - static::generateMessage($message) ?: 'List does not contain exactly "%d" elements.', - static::stringify($count) - ); - - throw static::createException($countable, $message, static::INVALID_COUNT, $propertyPath, array('count' => $count)); - } - - return true; - } - + const INVALID_GREATER = Assertion\INVALID_GREATER; /** - * static call handler to implement: - * - "null or assertion" delegation - * - "all" delegation. - * - * @param string $method - * @param array $args - * - * @return bool|mixed + * @deprecated + * @see Assertion\INVALID_GREATER_OR_EQUAL */ - 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(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(array($calledClass, $method), \array_merge(array($value), $args)); - } - - return true; - } - - throw new BadMethodCallException('No assertion Assertion#' . $method . ' exists.'); - } - + const INVALID_GREATER_OR_EQUAL = Assertion\INVALID_GREATER_OR_EQUAL; /** - * Determines if the values array has every choice as key and that this choice has content. - * - * @param array $values - * @param array $choices - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool + * @deprecated + * @see Assertion\INVALID_STRING */ - public static function choicesNotEmpty(array $values, array $choices, $message = null, $propertyPath = null) - { - static::notEmpty($values, $message, $propertyPath); - - foreach ($choices as $choice) { - static::notEmptyKey($values, $choice, $message, $propertyPath); - } - - return true; - } - + const INVALID_STRING = Assertion\INVALID_STRING; /** - * Determines that the named method is defined in the provided object. - * - * @param string $value - * @param mixed $object - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws + * @deprecated + * @see Assertion\INVALID_REGEX */ - public static function methodExists($value, $object, $message = null, $propertyPath = null) - { - 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); - } - - return true; - } - + const INVALID_REGEX = Assertion\INVALID_REGEX; /** - * Determines that the provided value is an object. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool + * @deprecated + * @see Assertion\INVALID_MIN_LENGTH */ - public static function isObject($value, $message = null, $propertyPath = null) - { - 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; - } - + const INVALID_MIN_LENGTH = Assertion\INVALID_MIN_LENGTH; /** - * Determines if the value is less than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool + * @deprecated + * @see Assertion\INVALID_MAX_LENGTH */ - public static function lessThan($value, $limit, $message = null, $propertyPath = null) - { - 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); - } - - return true; - } - + const INVALID_MAX_LENGTH = Assertion\INVALID_MAX_LENGTH; /** - * Determines if the value is less or equal than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool + * @deprecated + * @see Assertion\INVALID_STRING_START */ - public static function lessOrEqualThan($value, $limit, $message = null, $propertyPath = null) - { - 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); - } - - return true; - } - + const INVALID_STRING_START = Assertion\INVALID_STRING_START; /** - * Determines if the value is greater than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool + * @deprecated + * @see Assertion\INVALID_STRING_CONTAINS */ - public static function greaterThan($value, $limit, $message = null, $propertyPath = null) - { - 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); - } - - return true; - } - + const INVALID_STRING_CONTAINS = Assertion\INVALID_STRING_CONTAINS; /** - * Determines if the value is greater or equal than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool + * @deprecated + * @see Assertion\INVALID_ALNUM */ - public static function greaterOrEqualThan($value, $limit, $message = null, $propertyPath = null) - { - 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); - } - - return true; - } - + const INVALID_ALNUM = Assertion\INVALID_ALNUM; /** - * 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 $message - * @param string $propertyPath - * - * @return bool + * @deprecated + * @see Assertion\INVALID_LENGTH */ - public static function between($value, $lowerLimit, $upperLimit, $message = null, $propertyPath = null) - { - 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); - } - - return true; - } - + const INVALID_LENGTH = Assertion\INVALID_LENGTH; /** - * 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 $message - * @param string $propertyPath - * - * @return bool + * @deprecated + * @see Assertion\INVALID_STRING_END */ - public static function betweenExclusive($value, $lowerLimit, $upperLimit, $message = null, $propertyPath = null) - { - 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); - } - - return true; - } - + const INVALID_STRING_END = Assertion\INVALID_STRING_END; /** - * Assert that extension is loaded. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_UUID */ - public static function extensionLoaded($value, $message = null, $propertyPath = null) - { - 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; - } - + const INVALID_UUID = Assertion\INVALID_UUID; /** - * 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 - * @param string|null $propertyPath - * - * @return bool - * - * @see http://php.net/manual/function.date.php#refsect1-function.date-parameters + * @deprecated + * @see Assertion\INVALID_E164 */ - public static function date($value, $format, $message = null, $propertyPath = null) - { - 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, array('format' => $format)); - } - - return true; - } - + const INVALID_E164 = Assertion\INVALID_E164; /** - * Assert that the value is an object, or a class that exists. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_EMAIL */ - public static function objectOrClass($value, $message = null, $propertyPath = null) - { - if (!\is_object($value)) { - static::classExists($value, $message, $propertyPath); - } - - return true; - } - + const INVALID_EMAIL = Assertion\INVALID_EMAIL; /** - * 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 - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_URL */ - public static function propertyExists($value, $property, $message = null, $propertyPath = null) - { - 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); - } - - return true; - } - + const INVALID_URL = Assertion\INVALID_URL; /** - * Assert that the value is an object or class, and that the properties all exist. - * - * @param mixed $value - * @param array $properties - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_JSON_STRING */ - public static function propertiesExist($value, array $properties, $message = null, $propertyPath = null) - { - static::objectOrClass($value); - static::allString($properties, $message, $propertyPath); - - $invalidProperties = array(); - 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); - } - - return true; - } - + const INVALID_JSON_STRING = Assertion\INVALID_JSON_STRING; /** - * Assert comparison of two versions. - * - * @param string $version1 - * @param string $operator - * @param string $version2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_DATE */ - public static function version($version1, $operator, $version2, $message = null, $propertyPath = null) - { - 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); - } - - return true; - } - + const INVALID_DATE = Assertion\INVALID_DATE; /** - * Assert on PHP version. - * - * @param string $operator - * @param mixed $version - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException + * @deprecated + * @see Assertion\INVALID_IP */ - public static function phpVersion($operator, $version, $message = null, $propertyPath = null) - { - static::defined('PHP_VERSION'); - - return static::version(PHP_VERSION, $operator, $version, $message, $propertyPath); - } + const INVALID_IP = Assertion\INVALID_IP; + // end constants linked for BC /** - * 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 - * @param string|null $propertyPath - * - * @return bool + * Exception to throw when an assertion failed. * - * @throws \Assert\AssertionFailedException + * @var string */ - public static function extensionVersion($extension, $operator, $version, $message = null, $propertyPath = null) - { - static::extensionLoaded($extension, $message, $propertyPath); - - return static::version(\phpversion($extension), $operator, $version, $message, $propertyPath); - } + protected static $exceptionClass = 'Assert\InvalidArgumentException'; /** - * Determines that the provided value is callable. + * 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 string|null $propertyPath + * @param mixed $value + * @param string|callable $message + * @param int $code + * @param string|null $propertyPath + * @param array $constraints * - * @return bool + * @return mixed */ - public static function isCallable($value, $message = null, $propertyPath = null) + protected static function createException($value, $message, $code, $propertyPath = null, array $constraints = array()) { - 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); - } + $exceptionClass = static::$exceptionClass; - return true; + return new $exceptionClass($message, $code, $propertyPath, $value, $constraints); } /** - * Assert that the provided value is valid according to a callback. - * - * If the callback returns `false` the assertion will fail. + * static call handler to implement: + * - "null or assertion" delegation + * - "all" delegation. * - * @param mixed $value - * @param callable $callback - * @param string|callable|null $message - * @param string|null $propertyPath + * @param string $method + * @param array $args * - * @return bool + * @return bool|mixed */ - public static function satisfy($value, $callback, $message = null, $propertyPath = null) + public static function __callStatic($method, $args) { - 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) - ); + if (\strpos($method, 'nullOr') === 0) { + if (!\array_key_exists(0, $args)) { + throw new BadMethodCallException('Missing the first argument.'); + } - throw static::createException($value, $message, static::INVALID_SATISFY, $propertyPath); - } + if ($args[0] === null) { + return true; + } - return true; - } + $method = \substr($method, 6); - /** - * Assert that value is an IPv4 or IPv6 address - * (using input_filter/FILTER_VALIDATE_IP). - * - * @param string $value - * @param null|int $flag - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @see http://php.net/manual/filter.filters.flags.php - */ - public static function ip($value, $flag = null, $message = null, $propertyPath = null) - { - static::string($value, $message, $propertyPath); - if (!\filter_var($value, FILTER_VALIDATE_IP, $flag)) { - $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); + return \call_user_func_array(array(\get_called_class(), $method), $args); } - return true; - } + if (\strpos($method, 'all') === 0) { + if (!\array_key_exists(0, $args)) { + throw new BadMethodCallException('Missing the first argument.'); + } - /** - * Assert that value is an IPv4 address - * (using input_filter/FILTER_VALIDATE_IP). - * - * @param string $value - * @param null|int $flag - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @see http://php.net/manual/filter.filters.flags.php - */ - public static function ipv4($value, $flag = null, $message = null, $propertyPath = null) - { - static::ip($value, $flag | FILTER_FLAG_IPV4, static::generateMessage($message) ?: 'Value "%s" was expected to be a valid IPv4 address.', $propertyPath); + static::isTraversable($args[0]); - return true; - } + $method = \substr($method, 3); + $values = \array_shift($args); + $calledClass = \get_called_class(); - /** - * Assert that value is an IPv6 address - * (using input_filter/FILTER_VALIDATE_IP). - * - * @param string $value - * @param null|int $flag - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @see http://php.net/manual/filter.filters.flags.php - */ - public static function ipv6($value, $flag = null, $message = null, $propertyPath = null) - { - static::ip($value, $flag | FILTER_FLAG_IPV6, static::generateMessage($message) ?: 'Value "%s" was expected to be a valid IPv6 address.', $propertyPath); + foreach ($values as $value) { + \call_user_func_array(array($calledClass, $method), \array_merge(array($value), $args)); + } - return true; + return true; + } + + throw new BadMethodCallException('No assertion Assertion#' . $method . ' exists.'); } /** @@ -2525,57 +662,13 @@ protected static function stringify($value) $result = \get_class($value); } elseif (\is_resource($value)) { $result = \get_resource_type($value); - } elseif (null === $value) { + } elseif ($value === null) { $result = ''; } return $result; } - /** - * Assert that a constant is defined. - * - * @param mixed $constant - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException - */ - public static function defined($constant, $message = null, $propertyPath = null) - { - 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 - * @param string|null $propertyPath - * - * @return bool - * - * @throws \Assert\AssertionFailedException - */ - public static function base64($value, $message = null, $propertyPath = null) - { - 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; - } - /** * Generate the message. * @@ -2593,7 +686,7 @@ protected static function generateMessage($message = null) $reflection = new \ReflectionClass($traces[1]['class']); $method = $reflection->getMethod($traces[1]['function']); foreach ($method->getParameters() as $index => $parameter) { - if ('message' !== $parameter->getName()) { + if ($parameter->getName() !== 'message') { $parameters[$parameter->getName()] = \array_key_exists($index, $traces[1]['args']) ? $traces[1]['args'][$index] : $parameter->getDefaultValue(); diff --git a/lib/Assert/Assertion/ArrayTrait.php b/lib/Assert/Assertion/ArrayTrait.php new file mode 100644 index 00000000..bde7e06c --- /dev/null +++ b/lib/Assert/Assertion/ArrayTrait.php @@ -0,0 +1,328 @@ + $choices]); + } + + return true; + } + + /** + * Assert that value is an array or a traversable object. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function isTraversable($value, $message = null, $propertyPath = null) + { + if (!\is_array($value) && !$value instanceof \Traversable) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is not an array and does not implement Traversable.', + static::stringify($value) + ); + + throw static::createException($value, $message, INVALID_TRAVERSABLE, $propertyPath); + } + + return true; + } + + /** + * Assert that key exists in an array. + * + * @param mixed $value + * @param string|int $key + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function keyExists($value, $key, $message = null, $propertyPath = null) + { + static::isArray($value, $message, $propertyPath); + + if (!\array_key_exists($key, $value)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Array does not contain an element with key "%s"', + static::stringify($key) + ); + + throw static::createException($value, $message, INVALID_KEY_EXISTS, $propertyPath, ['key' => $key]); + } + + return true; + } + + /** + * Assert that value is an array. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function isArray($value, $message = null, $propertyPath = null) + { + if (!\is_array($value)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is not an array.', + static::stringify($value) + ); + + throw static::createException($value, $message, INVALID_ARRAY, $propertyPath); + } + + return true; + } + + /** + * Assert that key does not exist in an array. + * + * @param mixed $value + * @param string|int $key + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function keyNotExists($value, $key, $message = null, $propertyPath = null) + { + 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, INVALID_KEY_NOT_EXISTS, $propertyPath, + ['key' => $key]); + } + + return true; + } + + /** + * Assert that the count of countable is equal to count. + * + * @param array|\Countable $countable + * @param int $count + * @param string|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function count($countable, $count, $message = null, $propertyPath = null) + { + if ($count !== \count($countable)) { + $message = \sprintf( + static::generateMessage($message) ?: 'List does not contain exactly "%d" elements.', + static::stringify($count) + ); + + throw static::createException($countable, $message, INVALID_COUNT, $propertyPath, + ['count' => $count]); + } + + return true; + } + + /** + * Determines if the values array has every choice as key and that this choice has content. + * + * @param array $values + * @param array $choices + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + */ + public static function choicesNotEmpty(array $values, array $choices, $message = null, $propertyPath = null) + { + static::notEmpty($values, $message, $propertyPath); + + foreach ($choices as $choice) { + static::notEmptyKey($values, $choice, $message, $propertyPath); + } + + 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 + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function notEmptyKey($value, $key, $message = null, $propertyPath = null) + { + static::keyIsset($value, $key, $message, $propertyPath); + static::notEmpty($value[$key], $message, $propertyPath); + + 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 + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function keyIsset($value, $key, $message = null, $propertyPath = null) + { + 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, INVALID_KEY_ISSET, $propertyPath, ['key' => $key]); + } + + return true; + } + + /** + * Assert that value is an array or an array-accessible object. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function isArrayAccessible($value, $message = null, $propertyPath = null) + { + if (!\is_array($value) && !$value instanceof \ArrayAccess) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is not an array and does not implement ArrayAccess.', + static::stringify($value) + ); + + throw static::createException($value, $message, INVALID_ARRAY_ACCESSIBLE, $propertyPath); + } + + return true; + } +} diff --git a/lib/Assert/Assertion/BoolTrait.php b/lib/Assert/Assertion/BoolTrait.php new file mode 100644 index 00000000..7189fbbd --- /dev/null +++ b/lib/Assert/Assertion/BoolTrait.php @@ -0,0 +1,97 @@ + $className]); + } + + return true; + } + + /** + * Assert that the class exists. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function classExists($value, $message = null, $propertyPath = null) + { + if (!\class_exists($value)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Class "%s" does not exist.', + static::stringify($value) + ); + + throw static::createException($value, $message, INVALID_CLASS, $propertyPath); + } + + return true; + } + + /** + * Assert that the interface exists. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function interfaceExists($value, $message = null, $propertyPath = null) + { + if (!\interface_exists($value)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Interface "%s" does not exist.', + static::stringify($value) + ); + + throw static::createException($value, $message, INVALID_INTERFACE, $propertyPath); + } + + return true; + } + + /** + * Assert that the class implements the interface. + * + * @param mixed $class + * @param string $interfaceName + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function implementsInterface($class, $interfaceName, $message = null, $propertyPath = null) + { + $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, INTERFACE_NOT_IMPLEMENTED, $propertyPath, + ['interface' => $interfaceName]); + } + + 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 + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function isInstanceOf($value, $className, $message = null, $propertyPath = null) + { + 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, 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 + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function notIsInstanceOf($value, $className, $message = null, $propertyPath = null) + { + 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, INVALID_NOT_INSTANCE_OF, $propertyPath, + ['class' => $className]); + } + + return true; + } +} diff --git a/lib/Assert/Assertion/CompareTrait.php b/lib/Assert/Assertion/CompareTrait.php new file mode 100644 index 00000000..cde78da7 --- /dev/null +++ b/lib/Assert/Assertion/CompareTrait.php @@ -0,0 +1,262 @@ + $value2]); + } + + return true; + } + + /** + * Assert that two values are the same (using ===). + * + * @param mixed $value + * @param mixed $value2 + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function same($value, $value2, $message = null, $propertyPath = null) + { + if ($value !== $value2) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is not the same as expected value "%s".', + static::stringify($value), + static::stringify($value2) + ); + + throw static::createException($value, $message, INVALID_SAME, $propertyPath, + ['expected' => $value2]); + } + + return true; + } + + /** + * Assert that two values are not equal (using == ). + * + * @param mixed $value1 + * @param mixed $value2 + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function notEq($value1, $value2, $message = null, $propertyPath = null) + { + if ($value1 == $value2) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is equal to expected value "%s".', + static::stringify($value1), + static::stringify($value2) + ); + throw static::createException($value1, $message, INVALID_NOT_EQ, $propertyPath, + ['expected' => $value2]); + } + + return true; + } + + /** + * Assert that two values are not the same (using === ). + * + * @param mixed $value1 + * @param mixed $value2 + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function notSame($value1, $value2, $message = null, $propertyPath = null) + { + if ($value1 === $value2) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is the same as expected value "%s".', + static::stringify($value1), + static::stringify($value2) + ); + throw static::createException($value1, $message, INVALID_NOT_SAME, $propertyPath, + ['expected' => $value2]); + } + + return true; + } + + /** + * Assert that value is not empty. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function notEmpty($value, $message = null, $propertyPath = null) + { + if (empty($value)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is empty, but non empty value was expected.', + static::stringify($value) + ); + + throw static::createException($value, $message, VALUE_EMPTY, $propertyPath); + } + + return true; + } + + /** + * Assert that value is empty. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function noContent($value, $message = null, $propertyPath = null) + { + if (!empty($value)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is not empty, but empty value was expected.', + static::stringify($value) + ); + + throw static::createException($value, $message, VALUE_NOT_EMPTY, $propertyPath); + } + + return true; + } + + /** + * Assert that value is null. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function null($value, $message = null, $propertyPath = null) + { + if ($value !== null) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is not null, but null value was expected.', + static::stringify($value) + ); + + throw static::createException($value, $message, VALUE_NOT_NULL, $propertyPath); + } + + return true; + } + + /** + * Assert that value is not null. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function notNull($value, $message = null, $propertyPath = null) + { + if ($value === null) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is null, but non null value was expected.', + static::stringify($value) + ); + + throw static::createException($value, $message, VALUE_NULL, $propertyPath); + } + + return true; + } + + /** + * Assert that value is not blank. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function notBlank($value, $message = null, $propertyPath = null) + { + 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, INVALID_NOT_BLANK, $propertyPath); + } + + return true; + } +} diff --git a/lib/Assert/Assertion/EnvironmentTrait.php b/lib/Assert/Assertion/EnvironmentTrait.php new file mode 100644 index 00000000..294a669b --- /dev/null +++ b/lib/Assert/Assertion/EnvironmentTrait.php @@ -0,0 +1,140 @@ + $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, INVALID_RANGE, $propertyPath, + ['min' => $minValue, 'max' => $maxValue]); + } + + return true; + } + + /** + * Assert that value is numeric. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function numeric($value, $message = null, $propertyPath = null) + { + if (!\is_numeric($value)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" is not numeric.', + static::stringify($value) + ); + + throw static::createException($value, $message, INVALID_NUMERIC, $propertyPath); + } + + 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 + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function min($value, $minValue, $message = null, $propertyPath = null) + { + 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, 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 + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function max($value, $maxValue, $message = null, $propertyPath = null) + { + 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, INVALID_MAX, $propertyPath, ['max' => $maxValue]); + } + + return true; + } + + /** + * Determines if the value is less than given limit. + * + * @param mixed $value + * @param mixed $limit + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + */ + public static function lessThan($value, $limit, $message = null, $propertyPath = null) + { + 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, INVALID_LESS, $propertyPath); + } + + return true; + } + + /** + * Determines if the value is less or than given limit. + * + * @param mixed $value + * @param mixed $limit + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + */ + public static function lessOrEqualThan($value, $limit, $message = null, $propertyPath = null) + { + 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, INVALID_LESS_OR_EQUAL, $propertyPath); + } + + return true; + } + + /** + * Determines if the value is greater than given limit. + * + * @param mixed $value + * @param mixed $limit + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + */ + public static function greaterThan($value, $limit, $message = null, $propertyPath = null) + { + 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, INVALID_GREATER, $propertyPath); + } + + return true; + } + + /** + * Determines if the value is greater or equal than given limit. + * + * @param mixed $value + * @param mixed $limit + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + */ + public static function greaterOrEqualThan($value, $limit, $message = null, $propertyPath = null) + { + 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, INVALID_GREATER_OR_EQUAL, $propertyPath); + } + + 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 $message + * @param string $propertyPath + * + * @return bool + */ + public static function between($value, $lowerLimit, $upperLimit, $message = null, $propertyPath = null) + { + 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, INVALID_BETWEEN, $propertyPath); + } + + 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 $message + * @param string $propertyPath + * + * @return bool + */ + public static function betweenExclusive($value, $lowerLimit, $upperLimit, $message = null, $propertyPath = null) + { + 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, INVALID_BETWEEN_EXCLUSIVE, $propertyPath); + } + + return true; + } +} diff --git a/lib/Assert/Assertion/ObjectTrait.php b/lib/Assert/Assertion/ObjectTrait.php new file mode 100644 index 00000000..c27a11bb --- /dev/null +++ b/lib/Assert/Assertion/ObjectTrait.php @@ -0,0 +1,159 @@ + $length, 'encoding' => $encoding]; + throw static::createException($value, $message, INVALID_LENGTH, $propertyPath, $constraints); + } + + return true; + } + + /** + * Assert that value is a string. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function string($value, $message = null, $propertyPath = null) + { + if (!\is_string($value)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" expected to be string, type %s given.', + static::stringify($value), + \gettype($value) + ); + + throw static::createException($value, $message, INVALID_STRING, $propertyPath); + } + + return true; + } + + /** + * Assert that string length is between min,max lengths. + * + * @param mixed $value + * @param int $minLength + * @param int $maxLength + * @param string|callable|null $message + * @param string|null $propertyPath + * @param string $encoding + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function betweenLength( + $value, $minLength, $maxLength, $message = null, $propertyPath = null, $encoding = 'utf8' + ) { + static::string($value, $message, $propertyPath); + static::minLength($value, $minLength, $message, $propertyPath, $encoding); + static::maxLength($value, $maxLength, $message, $propertyPath, $encoding); + + return true; + } + + /** + * Assert that a string is at least $minLength chars long. + * + * @param mixed $value + * @param int $minLength + * @param string|callable|null $message + * @param string|null $propertyPath + * @param string $encoding + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function minLength($value, $minLength, $message = null, $propertyPath = null, $encoding = 'utf8') + { + static::string($value, $message, $propertyPath); + + if (\mb_strlen($value, $encoding) < $minLength) { + $message = \sprintf( + static::generateMessage($message) + ?: 'Value "%s" is too short, it should have at least %d characters, but only has %d characters.', + static::stringify($value), + $minLength, + \mb_strlen($value, $encoding) + ); + + $constraints = ['min_length' => $minLength, 'encoding' => $encoding]; + throw static::createException($value, $message, INVALID_MIN_LENGTH, $propertyPath, $constraints); + } + + return true; + } + + /** + * Assert that string value is not longer than $maxLength chars. + * + * @param mixed $value + * @param int $maxLength + * @param string|callable|null $message + * @param string|null $propertyPath + * @param string $encoding + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function maxLength($value, $maxLength, $message = null, $propertyPath = null, $encoding = 'utf8') + { + static::string($value, $message, $propertyPath); + + if (\mb_strlen($value, $encoding) > $maxLength) { + $message = \sprintf( + static::generateMessage($message) + ?: 'Value "%s" is too long, it should have no more than %d characters, but has %d characters.', + static::stringify($value), + $maxLength, + \mb_strlen($value, $encoding) + ); + + $constraints = ['max_length' => $maxLength, 'encoding' => $encoding]; + throw static::createException($value, $message, INVALID_MAX_LENGTH, $propertyPath, $constraints); + } + + return true; + } + + /** + * Assert that string starts with a sequence of chars. + * + * @param mixed $string + * @param string $needle + * @param string|callable|null $message + * @param string|null $propertyPath + * @param string $encoding + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function startsWith($string, $needle, $message = null, $propertyPath = null, $encoding = 'utf8') + { + static::string($string, $message, $propertyPath); + + if (\mb_strpos($string, $needle, null, $encoding) !== 0) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" does not start with "%s".', + static::stringify($string), + static::stringify($needle) + ); + + $constraints = ['needle' => $needle, 'encoding' => $encoding]; + throw static::createException($string, $message, INVALID_STRING_START, $propertyPath, $constraints); + } + + return true; + } + + /** + * Assert that string ends with a sequence of chars. + * + * @param mixed $string + * @param string $needle + * @param string|callable|null $message + * @param string|null $propertyPath + * @param string $encoding + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function endsWith($string, $needle, $message = null, $propertyPath = null, $encoding = 'utf8') + { + static::string($string, $message, $propertyPath); + + $stringPosition = \mb_strlen($string, $encoding) - \mb_strlen($needle, $encoding); + + if (\mb_strripos($string, $needle, null, $encoding) !== $stringPosition) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" does not end with "%s".', + static::stringify($string), + static::stringify($needle) + ); + + $constraints = ['needle' => $needle, 'encoding' => $encoding]; + throw static::createException($string, $message, INVALID_STRING_END, $propertyPath, $constraints); + } + + return true; + } + + /** + * Assert that string contains a sequence of chars. + * + * @param mixed $string + * @param string $needle + * @param string|callable|null $message + * @param string|null $propertyPath + * @param string $encoding + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function contains($string, $needle, $message = null, $propertyPath = null, $encoding = 'utf8') + { + static::string($string, $message, $propertyPath); + + if (\mb_strpos($string, $needle, null, $encoding) === false) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" does not contain "%s".', + static::stringify($string), + static::stringify($needle) + ); + + $constraints = ['needle' => $needle, 'encoding' => $encoding]; + throw static::createException($string, $message, INVALID_STRING_CONTAINS, $propertyPath, + $constraints); + } + + return true; + } + + /** + * Assert that value is an email adress (using input_filter/FILTER_VALIDATE_EMAIL). + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function email($value, $message = null, $propertyPath = null) + { + 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, INVALID_EMAIL, $propertyPath); + } else { + $host = \substr($value, \strpos($value, '@') + 1); + + // Likely not a FQDN, bug in PHP FILTER_VALIDATE_EMAIL prior to PHP 5.3.3 + if (\version_compare(PHP_VERSION, '5.3.3', '<') && \strpos($host, '.') === false) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" was expected to be a valid e-mail address.', + static::stringify($value) + ); + + throw static::createException($value, $message, 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 + * + * @return bool + * + * @throws \Assert\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, $propertyPath = null) + { + 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) + (/?|/\S+|\?\S*|\#\S*) # a /, nothing, a / with something, a query or a fragment + $~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, INVALID_URL, $propertyPath); + } + + return true; + } + + /** + * Assert that value is alphanumeric. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function alnum($value, $message = null, $propertyPath = null) + { + try { + static::regex($value, '(^([a-zA-Z]{1}[a-zA-Z0-9]*)$)', $message, $propertyPath); + } catch (AssertionFailedException $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, INVALID_ALNUM, $propertyPath); + } + + return true; + } + + /** + * Assert that value matches a regex. + * + * @param mixed $value + * @param string $pattern + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function regex($value, $pattern, $message = null, $propertyPath = null) + { + static::string($value, $message, $propertyPath); + + if (!\preg_match($pattern, $value)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" does not match expression.', + static::stringify($value) + ); + + throw static::createException($value, $message, INVALID_REGEX, $propertyPath, + ['pattern' => $pattern]); + } + + 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 + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function isJsonString($value, $message = null, $propertyPath = null) + { + 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, 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 + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function uuid($value, $message = null, $propertyPath = null) + { + $value = \str_replace(['urn:', 'uuid:', '{', '}'], '', $value); + + if ($value === '00000000-0000-0000-0000-000000000000') { + 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, 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 + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function e164($value, $message = null, $propertyPath = null) + { + 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, INVALID_E164, $propertyPath); + } + + return true; + } + + /** + * Assert that value is an IPv4 address + * (using input_filter/FILTER_VALIDATE_IP). + * + * @param string $value + * @param null|int $flag + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @see http://php.net/manual/filter.filters.flags.php + */ + public static function ipv4($value, $flag = null, $message = null, $propertyPath = null) + { + 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 IPv4 or IPv6 address + * (using input_filter/FILTER_VALIDATE_IP). + * + * @param string $value + * @param null|int $flag + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @see http://php.net/manual/filter.filters.flags.php + */ + public static function ip($value, $flag = null, $message = null, $propertyPath = null) + { + static::string($value, $message, $propertyPath); + if (!\filter_var($value, FILTER_VALIDATE_IP, $flag)) { + $message = \sprintf( + static::generateMessage($message) ?: 'Value "%s" was expected to be a valid IP address.', + static::stringify($value) + ); + throw static::createException($value, $message, INVALID_IP, $propertyPath); + } + + return true; + } + + /** + * Assert that value is an IPv6 address + * (using input_filter/FILTER_VALIDATE_IP). + * + * @param string $value + * @param null|int $flag + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @see http://php.net/manual/filter.filters.flags.php + */ + public static function ipv6($value, $flag = null, $message = null, $propertyPath = null) + { + 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 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 + * @param string|null $propertyPath + * + * @return bool + * + * @see http://php.net/manual/function.date.php#refsect1-function.date-parameters + */ + public static function date($value, $format, $message = null, $propertyPath = null) + { + 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, INVALID_DATE, $propertyPath, ['format' => $format]); + } + + return true; + } +} diff --git a/tests/Assert/Tests/AssertTest.php b/tests/Assert/Tests/AssertTest.php index 44289330..a39d7397 100644 --- a/tests/Assert/Tests/AssertTest.php +++ b/tests/Assert/Tests/AssertTest.php @@ -20,2037 +20,64 @@ class AssertTest extends TestCase { - public static function dataInvalidFloat() - { - return array( - array(1), - array(false), - array('test'), - array(null), - array('1.23'), - array('10'), - ); - } - - /** - * @dataProvider dataInvalidFloat - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_FLOAT - * - * @param mixed $nonFloat - */ - public function testInvalidFloat($nonFloat) - { - Assertion::float($nonFloat); - } - - public function testValidFloat() - { - $this->assertTrue(Assertion::float(1.0)); - $this->assertTrue(Assertion::float(0.1)); - $this->assertTrue(Assertion::float(-1.1)); - } - - public static function dataInvalidInteger() - { - return array( - array(1.23), - array(false), - array('test'), - array(null), - array('1.23'), - array('10'), - array(new \DateTime()), - ); - } - - /** - * @dataProvider dataInvalidInteger - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_INTEGER - * - * @param mixed $nonInteger - */ - public function testInvalidInteger($nonInteger) - { - Assertion::integer($nonInteger); - } - - public function testValidInteger() - { - $this->assertTrue(Assertion::integer(10)); - $this->assertTrue(Assertion::integer(0)); - } - - public function dataValidIntergerish() - { - return array( - array(10), - array('10'), - array(-10), - array('-10'), - array(0123), - array('0123'), - array(0), - array('0'), - array(00123), - array('00123'), - array(00), - array('00'), - array('0040'), - ); - } - - /** - * @param $value - * - * @throws AssertionFailedException - * @dataProvider dataValidIntergerish - */ - public function testValidIntegerish($value) - { - $this->assertTrue(Assertion::integerish($value)); - } - - public static function dataInvalidIntegerish() - { - return array( - 'A float' => array(1.23), - 'Boolean true' => array(true), - 'Boolean false' => array(false), - 'A text string' => array('test'), - 'A null' => array(null), - 'A float in a string' => array('1.23'), - 'A negative float in a string' => array('-1.23'), - 'A file pointer' => array(\fopen(__FILE__, 'r')), - 'A float in a string with a leading space' => array(' 1.23'), - 'An integer in a string with a leading space' => array(' 123'), - 'A negative integer in a string with a leading space' => array(' -123'), - 'An integer in a string with a trailing space' => array('456 '), - 'A negative integer in a string with a trailing space' => array('-456 '), - 'An array' => array(array()), - 'An object' => array(new \stdClass()), - 'A float that is less than 1' => array(0.1), - 'A float that is less than 0.1' => array(0.01), - 'A float that is less than 0.01' => array(0.001), - 'A float in a string that is less than 1' => array('0.1'), - 'A float in a string that is less than 0.1' => array('0.01'), - 'A float in a string that is less than 0.01' => array('0.001'), - 'An empty string' => array(''), - 'A single space string' => array(' '), - 'A multiple spaced string' => array(' '), - ); - } - - /** - * @dataProvider dataInvalidIntegerish - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_INTEGERISH - * - * @param mixed $nonInteger - */ - public function testInvalidIntegerish($nonInteger) - { - Assertion::integerish($nonInteger); - } - - public function testValidBoolean() - { - $this->assertTrue(Assertion::boolean(true)); - $this->assertTrue(Assertion::boolean(false)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_BOOLEAN - */ - public function testInvalidBoolean() - { - Assertion::boolean(1); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_SCALAR - */ - public function testInvalidScalar() - { - Assertion::scalar(new \stdClass()); - } - - public function testValidScalar() - { - $this->assertTrue(Assertion::scalar('foo')); - $this->assertTrue(Assertion::scalar(52)); - $this->assertTrue(Assertion::scalar(12.34)); - $this->assertTrue(Assertion::scalar(false)); - } - - public static function dataInvalidNotEmpty() - { - return array( - array(''), - array(false), - array(0), - array(null), - array(array()), - ); - } - - /** - * @dataProvider dataInvalidNotEmpty - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::VALUE_EMPTY - * - * @param mixed $value - */ - public function testInvalidNotEmpty($value) - { - Assertion::notEmpty($value); - } - - public function testNotEmpty() - { - $this->assertTrue(Assertion::notEmpty('test')); - $this->assertTrue(Assertion::notEmpty(1)); - $this->assertTrue(Assertion::notEmpty(true)); - $this->assertTrue(Assertion::notEmpty(array('foo'))); - } - - public function testEmpty() - { - $this->assertTrue(Assertion::noContent('')); - $this->assertTrue(Assertion::noContent(0)); - $this->assertTrue(Assertion::noContent(false)); - $this->assertTrue(Assertion::noContent(array())); - } - - public static function dataInvalidEmpty() - { - return array( - array('foo'), - array(true), - array(12), - array(array('foo')), - array(new \stdClass()), - ); - } - - /** - * @dataProvider dataInvalidEmpty - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::VALUE_NOT_EMPTY - * - * @param mixed $value - */ - public function testInvalidEmpty($value) - { - Assertion::noContent($value); - } - - public static function dataInvalidNull() - { - return array( - array('foo'), - array(''), - array(false), - array(12), - array(0), - array(array()), - ); - } - - /** - * @dataProvider dataInvalidNull - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::VALUE_NOT_NULL - * - * @param mixed $value - */ - public function testInvalidNull($value) - { - Assertion::null($value); - } - - public function testNull() - { - $this->assertTrue(Assertion::null(null)); - } - - public function testNotNull() - { - $this->assertTrue(Assertion::notNull('1')); - $this->assertTrue(Assertion::notNull(1)); - $this->assertTrue(Assertion::notNull(0)); - $this->assertTrue(Assertion::notNull(array())); - $this->assertTrue(Assertion::notNull(false)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::VALUE_NULL - */ - public function testInvalidNotNull() - { - Assertion::notNull(null); - } - - public function testString() - { - $this->assertTrue(Assertion::string('test-string')); - $this->assertTrue(Assertion::string('')); - } - - /** - * @dataProvider dataInvalidString - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_STRING - * - * @param mixed $invalidString - */ - public function testInvalidString($invalidString) - { - Assertion::string($invalidString); - } - - public static function dataInvalidString() - { - return array( - array(1.23), - array(false), - array(new \ArrayObject()), - array(null), - array(10), - array(true), - ); - } - - public function testValidRegex() - { - $this->assertTrue(Assertion::regex('some string', '/.*/')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_REGEX - */ - public function testInvalidRegex() - { - Assertion::regex('foo', '(bar)'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_STRING - */ - public function testInvalidRegexValueNotString() - { - Assertion::regex(array('foo'), '(bar)'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_MIN_LENGTH - */ - public function testInvalidMinLength() - { - Assertion::minLength('foo', 4); - } - - public function testValidMinLength() - { - $this->assertTrue(Assertion::minLength('foo', 3)); - $this->assertTrue(Assertion::minLength('foo', 1)); - $this->assertTrue(Assertion::minLength('foo', 0)); - $this->assertTrue(Assertion::minLength('', 0)); - $this->assertTrue(Assertion::minLength('址址', 2)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_MAX_LENGTH - */ - public function testInvalidMaxLength() - { - Assertion::maxLength('foo', 2); - } - - public function testValidMaxLength() - { - $this->assertTrue(Assertion::maxLength('foo', 10)); - $this->assertTrue(Assertion::maxLength('foo', 3)); - $this->assertTrue(Assertion::maxLength('', 0)); - $this->assertTrue(Assertion::maxLength('址址', 2)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_MIN_LENGTH - */ - public function testInvalidBetweenLengthMin() - { - Assertion::betweenLength('foo', 4, 100); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_MAX_LENGTH - */ - public function testInvalidBetweenLengthMax() - { - Assertion::betweenLength('foo', 0, 2); - } - - public function testValidBetweenLength() - { - $this->assertTrue(Assertion::betweenLength('foo', 0, 3)); - $this->assertTrue(Assertion::betweenLength('址址', 2, 2)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_STRING_START - */ - public function testInvalidStartsWith() - { - Assertion::startsWith('foo', 'bar'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_STRING_START - */ - public function testInvalidStartsWithDueToWrongEncoding() - { - Assertion::startsWith('址', '址址', null, null, 'ASCII'); - } - - public function testValidStartsWith() - { - $this->assertTrue(Assertion::startsWith('foo', 'foo')); - $this->assertTrue(Assertion::startsWith('foo', 'fo')); - $this->assertTrue(Assertion::startsWith('foo', 'f')); - $this->assertTrue(Assertion::startsWith('址foo', '址')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_STRING_END - */ - public function testInvalidEndsWith() - { - Assertion::endsWith('foo', 'bar'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_STRING_END - */ - public function testInvalidEndsWithDueToWrongEncoding() - { - Assertion::endsWith('址', '址址', null, null, 'ASCII'); - } - - public function testValidEndsWith() - { - $this->assertTrue(Assertion::endsWith('foo', 'foo')); - $this->assertTrue(Assertion::endsWith('sonderbar', 'bar')); - $this->assertTrue(Assertion::endsWith('opp', 'p')); - $this->assertTrue(Assertion::endsWith('foo址', '址')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_STRING_CONTAINS - */ - public function testInvalidContains() - { - Assertion::contains('foo', 'bar'); - } - - public function testValidContains() - { - $this->assertTrue(Assertion::contains('foo', 'foo')); - $this->assertTrue(Assertion::contains('foo', 'oo')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_CHOICE - */ - public function testInvalidChoice() - { - Assertion::choice('foo', array('bar', 'baz')); - } - - public function testValidChoice() - { - $this->assertTrue(Assertion::choice('foo', array('foo'))); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_CHOICE - */ - public function testInvalidInArray() - { - Assertion::inArray('bar', array('baz')); - } - - public function testValidInArray() - { - $this->assertTrue(Assertion::inArray('foo', array('foo'))); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_NUMERIC - */ - public function testInvalidNumeric() - { - Assertion::numeric('foo'); - } - - public function testValidNumeric() - { - $this->assertTrue(Assertion::numeric('1')); - $this->assertTrue(Assertion::numeric(1)); - $this->assertTrue(Assertion::numeric(1.23)); - } - - public static function dataInvalidArray() - { - return array( - array(null), - array(false), - array('test'), - array(1), - array(1.23), - array(new \stdClass()), - array(\fopen('php://memory', 'r')), - ); - } - - /** - * @dataProvider dataInvalidArray - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_ARRAY - * - * @param mixed $value - */ - public function testInvalidArray($value) - { - Assertion::isArray($value); - } - - public function testValidArray() - { - $this->assertTrue(Assertion::isArray(array())); - $this->assertTrue(Assertion::isArray(array(1, 2, 3))); - $this->assertTrue(Assertion::isArray(array(array(), array()))); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_KEY_EXISTS - */ - public function testInvalidKeyExists() - { - Assertion::keyExists(array('foo' => 'bar'), 'baz'); - } - - public function testValidKeyExists() - { - $this->assertTrue(Assertion::keyExists(array('foo' => 'bar'), 'foo')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_KEY_NOT_EXISTS - */ - public function testInvalidKeyNotExists() - { - Assertion::keyNotExists(array('foo' => 'bar'), 'foo'); - } - - public function testValidKeyNotExists() - { - $this->assertTrue(Assertion::keyNotExists(array('foo' => 'bar'), 'baz')); - } - - public static function dataInvalidNotBlank() - { - return array( - array(''), - array(' '), - array("\t"), - array("\n"), - array("\r"), - array(false), - array(null), - array(array()), - ); - } - - /** - * @dataProvider dataInvalidNotBlank - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_NOT_BLANK - * - * @param mixed $notBlank - */ - public function testInvalidNotBlank($notBlank) - { - Assertion::notBlank($notBlank); - } - - public function testValidNotBlank() - { - $this->assertTrue(Assertion::notBlank('foo')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_NOT_INSTANCE_OF - */ - public function testInvalidNotInstanceOf() - { - Assertion::notIsInstanceOf(new \stdClass(), 'stdClass'); - } - - public function testValidNotIsInstanceOf() - { - $this->assertTrue(Assertion::notIsInstanceOf(new \stdClass(), 'PDO')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_INSTANCE_OF - */ - public function testInvalidInstanceOf() - { - Assertion::isInstanceOf(new \stdClass(), 'PDO'); - } - - public function testValidInstanceOf() - { - $this->assertTrue(Assertion::isInstanceOf(new \stdClass(), 'stdClass')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_SUBCLASS_OF - */ - public function testInvalidSubclassOf() - { - Assertion::subclassOf(new \stdClass(), 'PDO'); - } - - public function testValidSubclassOf() - { - $this->assertTrue(Assertion::subclassOf(new Fixtures\ChildStdClass(), 'stdClass')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_RANGE - */ - public function testInvalidRange() - { - Assertion::range(1, 2, 3); - Assertion::range(1.5, 2, 3); - } - - public function testValidRange() - { - $this->assertTrue(Assertion::range(1, 1, 2)); - $this->assertTrue(Assertion::range(2, 1, 2)); - $this->assertTrue(Assertion::range(2, 0, 100)); - $this->assertTrue(Assertion::range(2.5, 2.25, 2.75)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_EMAIL - */ - public function testInvalidEmail() - { - Assertion::email('foo'); - } - - public function testValidEmail() - { - $this->assertTrue(Assertion::email('123hello+world@email.provider.com')); - } - - /** - * @dataProvider dataInvalidUrl - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_URL - * - * @param string $url - */ - public function testInvalidUrl($url) - { - Assertion::url($url); - } - - public static function dataInvalidUrl() - { - return array( - array('google.com'), - array('://google.com'), - array('http ://google.com'), - array('http:/google.com'), - array('http://goog_le.com'), - array('http://google.com::aa'), - array('http://google.com:aa'), - array('ftp://google.fr'), - array('faked://google.fr'), - array('http://127.0.0.1:aa/'), - array('ftp://[::1]/'), - array('http://[::1'), - array('http://hello.☎/'), - array('http://:password@symfony.com'), - array('http://:password@@symfony.com'), - array('http://username:passwordsymfony.com'), - array('http://usern@me:password@symfony.com'), - ); - } - - /** - * @dataProvider dataValidUrl - * - * @param string $url - */ - public function testValidUrl($url) - { - $this->assertTrue(Assertion::url($url)); - } - - public static function dataValidUrl() - { - return array( - array('http://a.pl'), - array('http://www.google.com'), - array('http://www.google.com.'), - array('http://www.google.museum'), - array('https://google.com/'), - array('https://google.com:80/'), - array('http://www.example.coop/'), - array('http://www.test-example.com/'), - array('http://www.symfony.com/'), - array('http://symfony.fake/blog/'), - array('http://symfony.com/?'), - array('http://symfony.com/search?type=&q=url+validator'), - array('http://symfony.com/#'), - array('http://symfony.com/#?'), - array('http://www.symfony.com/doc/current/book/validation.html#supported-constraints'), - array('http://very.long.domain.name.com/'), - array('http://localhost/'), - array('http://myhost123/'), - array('http://127.0.0.1/'), - array('http://127.0.0.1:80/'), - array('http://[::1]/'), - array('http://[::1]:80/'), - array('http://[1:2:3::4:5:6:7]/'), - array('http://sãopaulo.com/'), - array('http://xn--sopaulo-xwa.com/'), - array('http://sãopaulo.com.br/'), - array('http://xn--sopaulo-xwa.com.br/'), - array('http://пример.испытание/'), - array('http://xn--e1afmkfd.xn--80akhbyknj4f/'), - array('http://مثال.إختبار/'), - array('http://xn--mgbh0fb.xn--kgbechtv/'), - array('http://例子.测试/'), - array('http://xn--fsqu00a.xn--0zwm56d/'), - array('http://例子.測試/'), - array('http://xn--fsqu00a.xn--g6w251d/'), - array('http://例え.テスト/'), - array('http://xn--r8jz45g.xn--zckzah/'), - array('http://مثال.آزمایشی/'), - array('http://xn--mgbh0fb.xn--hgbk6aj7f53bba/'), - array('http://실례.테스트/'), - array('http://xn--9n2bp8q.xn--9t4b11yi5a/'), - array('http://العربية.idn.icann.org/'), - array('http://xn--ogb.idn.icann.org/'), - array('http://xn--e1afmkfd.xn--80akhbyknj4f.xn--e1afmkfd/'), - array('http://xn--espaa-rta.xn--ca-ol-fsay5a/'), - array('http://xn--d1abbgf6aiiy.xn--p1ai/'), - array('http://☎.com/'), - array('http://username:password@symfony.com'), - array('http://user.name:password@symfony.com'), - array('http://username:pass.word@symfony.com'), - array('http://user.name:pass.word@symfony.com'), - array('http://user-name@symfony.com'), - array('http://symfony.com?'), - array('http://symfony.com?query=1'), - array('http://symfony.com/?query=1'), - array('http://symfony.com#'), - array('http://symfony.com#fragment'), - array('http://symfony.com/#fragment'), - ); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_DIGIT - */ - public function testInvalidDigit() - { - Assertion::digit(-1); - } - - public function testValidDigit() - { - $this->assertTrue(Assertion::digit(1)); - $this->assertTrue(Assertion::digit(0)); - $this->assertTrue(Assertion::digit('0')); - } - - public function testValidAlnum() - { - $this->assertTrue(Assertion::alnum('a')); - $this->assertTrue(Assertion::alnum('a1')); - $this->assertTrue(Assertion::alnum('aasdf1234')); - $this->assertTrue(Assertion::alnum('a1b2c3')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_ALNUM - */ - public function testInvalidAlnum() - { - Assertion::alnum('1a'); - } - - public function testValidTrue() - { - $this->assertTrue(Assertion::true(1 == 1)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_TRUE - */ - public function testInvalidTrue() - { - Assertion::true(false); - } - - public function testValidFalse() - { - $this->assertTrue(Assertion::false(1 == 0)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_FALSE - */ - public function testInvalidFalse() - { - Assertion::false(true); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_CLASS - */ - public function testInvalidClass() - { - Assertion::classExists('Foo'); - } - - public function testValidClass() - { - $this->assertTrue(Assertion::classExists('\\Exception')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_SAME - */ - public function testSame() - { - $this->assertTrue(Assertion::same(1, 1)); - $this->assertTrue(Assertion::same('foo', 'foo')); - $this->assertTrue(Assertion::same($obj = new \stdClass(), $obj)); - - Assertion::same(new \stdClass(), new \stdClass()); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_EQ - */ - public function testEq() - { - $this->assertTrue(Assertion::eq(1, '1')); - $this->assertTrue(Assertion::eq('foo', true)); - $this->assertTrue(Assertion::eq($obj = new \stdClass(), $obj)); - - Assertion::eq('2', 1); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_NOT_EQ - */ - public function testNotEq() - { - $this->assertTrue(Assertion::notEq('1', false)); - $this->assertTrue(Assertion::notEq(new \stdClass(), array())); - - Assertion::notEq('1', 1); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_NOT_SAME - */ - public function testNotSame() - { - $this->assertTrue(Assertion::notSame('1', 2)); - $this->assertTrue(Assertion::notSame(new \stdClass(), array())); - - Assertion::notSame(1, 1); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_VALUE_IN_ARRAY - */ - public function testNotInArray() - { - $this->assertTrue(Assertion::notInArray(6, \range(1, 5))); - $this->assertTrue(Assertion::notInArray('a', \range('b', 'z'))); - - Assertion::notInArray(1, \range(1, 5)); - } - - public function testMin() - { - $this->assertTrue(Assertion::min(1, 1)); - $this->assertTrue(Assertion::min(2, 1)); - $this->assertTrue(Assertion::min(2.5, 1)); - } - - /** - * @dataProvider dataInvalidMin - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_MIN - * @expectedExceptionMessageRegExp /Number "(0\.5|0)" was expected to be at least "(1|2\.5)"/ - * - * @param float|int $value - * @param float|int $min - */ - public function testInvalidMin($value, $min) - { - Assertion::min($value, $min); - } - - public function dataInvalidMin() - { - return array( - array(0, 1), - array(0.5, 2.5), - ); - } - - public function testMax() - { - $this->assertTrue(Assertion::max(1, 1)); - $this->assertTrue(Assertion::max(0.5, 1)); - $this->assertTrue(Assertion::max(0, 1)); - } - - /** - * @dataProvider dataInvalidMax - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_MAX - * @expectedExceptionMessageRegExp /Number "(2.5|2)" was expected to be at most "(1|0\.5)"/ - * - * @param float|int $value - * @param float|int $min - */ - public function testInvalidMax($value, $min) - { - Assertion::max($value, $min); - } - - public function dataInvalidMax() - { - return array( - array(2, 1), - array(2.5, 0.5), - ); - } - - public function testNullOr() - { - $this->assertTrue(Assertion::nullOrMax(null, 1)); - $this->assertTrue(Assertion::nullOrMax(null, 2)); - } - - /** - * @expectedException \BadMethodCallException - * @expectedExceptionMessage Missing the first argument. - */ - public function testNullOrWithNoValueThrows() - { - Assertion::nullOrMax(); - } - - public function testLength() - { - $this->assertTrue(Assertion::length('asdf', 4)); - $this->assertTrue(Assertion::length('', 0)); - } - - public static function dataLengthUtf8Characters() - { - return array( - array('址', 1), - array('ل', 1), - ); - } - - /** - * @dataProvider dataLengthUtf8Characters - * - * @param string $value - * @param int $expected - */ - public function testLengthUtf8Characters($value, $expected) - { - $this->assertTrue(Assertion::length($value, $expected)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_LENGTH - */ - public function testLengthFailed() - { - Assertion::length('asdf', 3); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_LENGTH - */ - public function testLengthFailedForWrongEncoding() - { - Assertion::length('址', 1, null, null, 'ASCII'); - } - - public function testLengthValidForGivenEncoding() - { - $this->assertTrue(Assertion::length('址', 1, null, null, 'utf8')); - } - - public function testFile() - { - $this->assertTrue(Assertion::file(__FILE__)); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::VALUE_EMPTY - */ - public function testFileWithEmptyFilename() - { - Assertion::file(''); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_FILE - */ - public function testFileDoesNotExists() - { - Assertion::file(__DIR__ . '/does-not-exists'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_DIRECTORY - */ - public function testDirectory() - { - $this->assertTrue(Assertion::directory(__DIR__)); - - Assertion::directory(__DIR__ . '/does-not-exist'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_READABLE - */ - public function testReadable() - { - $this->assertTrue(Assertion::readable(__FILE__)); - - Assertion::readable(__DIR__ . '/does-not-exist'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_WRITEABLE - */ - public function testWriteable() - { - $this->assertTrue(Assertion::writeable(\sys_get_temp_dir())); - - Assertion::writeable(__DIR__ . '/does-not-exist'); - } - - /** - * @expectedException \BadMethodCallException - * @expectedExceptionMessage No assertion - */ - public function testFailedNullOrMethodCall() - { - Assertion::nullOrAssertionDoesNotExist(''); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INTERFACE_NOT_IMPLEMENTED - */ - public function testImplementsInterface() - { - $this->assertTrue(Assertion::implementsInterface('\ArrayIterator', '\Traversable')); - - Assertion::implementsInterface('\Exception', '\Traversable'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INTERFACE_NOT_IMPLEMENTED - */ - public function testImplementsInterfaceWithClassObject() - { - $class = new \ArrayObject(); - - $this->assertTrue(Assertion::implementsInterface($class, '\Traversable')); - - Assertion::implementsInterface($class, '\SplObserver'); - } - - /** - * @dataProvider isJsonStringDataprovider - * - * @param $content - */ - public function testIsJsonString($content) - { - $this->assertTrue(Assertion::isJsonString($content)); - } - - public static function isJsonStringDataprovider() - { - return array( - '»null« value' => array(\json_encode(null)), - '»false« value' => array(\json_encode(false)), - 'array value' => array('["false"]'), - 'object value' => array('{"tux":"false"}'), - ); - } - - /** - * @dataProvider isJsonStringInvalidStringDataprovider - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_JSON_STRING - * - * @param $invalidString - */ - public function testIsJsonStringExpectingException($invalidString) - { - Assertion::isJsonString($invalidString); - } - - public static function isJsonStringInvalidStringDataprovider() - { - return array( - 'no json string' => array('invalid json encoded string'), - 'error in json string' => array('{invalid json encoded string}'), - ); - } - - /** - * @dataProvider providesValidUuids - * - * @param string $uuid - */ - public function testValidUuids($uuid) - { - $this->assertTrue(Assertion::uuid($uuid)); - } - - /** - * @dataProvider providesInvalidUuids - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_UUID - * - * @param string $uuid - */ - public function testInvalidUuids($uuid) - { - Assertion::uuid($uuid); - } - - public static function providesValidUuids() - { - return array( - array('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'), - array('ff6f8cb0-c57d-21e1-9b21-0800200c9a66'), - array('ff6f8cb0-c57d-31e1-9b21-0800200c9a66'), - array('ff6f8cb0-c57d-41e1-9b21-0800200c9a66'), - array('ff6f8cb0-c57d-51e1-9b21-0800200c9a66'), - array('FF6F8CB0-C57D-11E1-9B21-0800200C9A66'), - array('00000000-0000-0000-0000-000000000000'), - ); - } - - public static function providesInvalidUuids() - { - return array( - array('zf6f8cb0-c57d-11e1-9b21-0800200c9a66'), - array('af6f8cb0c57d11e19b210800200c9a66'), - array('ff6f8cb0-c57da-51e1-9b21-0800200c9a66'), - array('af6f8cb-c57d-11e1-9b21-0800200c9a66'), - array('3f6f8cb0-c57d-11e1-9b21-0800200c9a6'), - ); - } - - /** - * @dataProvider providesValidE164s - * - * @param string $e164 - */ - public function testValidE164s($e164) - { - $this->assertTrue(Assertion::e164($e164)); - } - - /** - * @dataProvider providesInvalidE164s - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_E164 - * - * @param string $e164 - */ - public function testInvalidE164s($e164) - { - Assertion::e164($e164); - } - - public static function providesValidE164s() - { - return array( - array('+33626525690'), - array('33626525690'), - array('+16174552211'), - ); - } - - public static function providesInvalidE164s() - { - return array( - array('+3362652569e'), - array('+3361231231232652569'), - ); - } - - public function testValidNotEmptyKey() - { - $this->assertTrue(Assertion::notEmptyKey(array('keyExists' => 'notEmpty'), 'keyExists')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::VALUE_EMPTY - */ - public function testInvalidNotEmptyKeyEmptyKey() - { - Assertion::notEmptyKey(array('keyExists' => ''), 'keyExists'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_KEY_ISSET - */ - public function testInvalidNotEmptyKeyKeyNotExists() - { - Assertion::notEmptyKey(array('key' => 'notEmpty'), 'keyNotExists'); - } - - public function testAllWithSimpleAssertion() - { - $this->assertTrue(Assertion::allTrue(array(true, true))); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_TRUE - */ - public function testAllWithSimpleAssertionThrowsExceptionOnElementThatFailsAssertion() - { - Assertion::allTrue(array(true, false)); - } - - public function testAllWithComplexAssertion() - { - $this->assertTrue(Assertion::allIsInstanceOf(array(new \stdClass(), new \stdClass()), 'stdClass')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_INSTANCE_OF - */ - public function testAllWithComplexAssertionThrowsExceptionOnElementThatFailsAssertion() - { - Assertion::allIsInstanceOf(array(new \stdClass(), new \stdClass()), 'PDO', 'Assertion failed', 'foos'); - } - - /** - * @expectedException \BadMethodCallException - */ - public function testAllWithNoValueThrows() - { - Assertion::allTrue(); - } - - public function testValidCount() - { - $this->assertTrue(Assertion::count(array('Hi'), 1)); - $this->assertTrue(Assertion::count(new Fixtures\OneCountable(), 1)); - } - - public static function dataInvalidCount() - { - return array( - array(array('Hi', 'There'), 3), - array(new Fixtures\OneCountable(), 2), - ); - } - - /** - * @dataProvider dataInvalidCount - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_COUNT - * @expectedExceptionMessageRegExp /List does not contain exactly "\d+" elements./ - * - * @param mixed $countable - * @param int $count - */ - public function testInvalidCount($countable, $count) - { - Assertion::count($countable, $count); - } - - public function testChoicesNotEmpty() - { - $this->assertTrue( - Assertion::choicesNotEmpty( - array('tux' => 'linux', 'Gnu' => 'dolphin'), - array('tux') - ) - ); - } - - /** - * @dataProvider invalidChoicesProvider - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::VALUE_EMPTY - * - * @param $values - * @param $choices - */ - public function testChoicesNotEmptyExpectingExceptionEmptyValue($values, $choices) - { - Assertion::choicesNotEmpty($values, $choices); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_KEY_ISSET - */ - public function testChoicesNotEmptyExpectingExceptionInvalidKeyIsset() - { - Assertion::choicesNotEmpty(array('tux' => ''), array('invalidChoice')); - } - - public function invalidChoicesProvider() - { - return array( - 'empty values' => array(array(), array('tux'), Assertion::VALUE_EMPTY), - 'empty recodes in $values' => array(array('tux' => ''), array('tux'), Assertion::VALUE_EMPTY), - ); - } - - public function testIsObject() - { - $this->assertTrue(Assertion::isObject(new \stdClass())); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_OBJECT - */ - public function testIsObjectExpectingException() - { - Assertion::isObject('notAnObject'); - } - - public function testMethodExists() - { - $this->assertTrue(Assertion::methodExists('methodExists', new Assertion())); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_METHOD - */ - public function testMethodExistsFailure() - { - Assertion::methodExists('methodNotExists', new Assertion()); - } - - public function testThatAssertionExceptionCanAccessValueAndSupplyConstraints() - { - try { - Assertion::range(0, 10, 20); - - $this->fail('Exception expected'); - } catch (AssertionFailedException $e) { - $this->assertEquals(0, $e->getValue()); - $this->assertEquals(array('min' => 10, 'max' => 20), $e->getConstraints()); - } - } - - public function testLessThan() - { - $this->assertTrue(Assertion::lessThan(1, 2)); - $this->assertTrue(Assertion::lessThan('aaa', 'bbb')); - $this->assertTrue(Assertion::lessThan('aaa', 'aaaa')); - $this->assertTrue(Assertion::lessThan(new \DateTime('today'), new \DateTime('tomorrow'))); - } - - public function invalidLessProvider() - { - return array( - array(2, 1), - array(2, 2), - array('aaa', 'aaa'), - array('aaaa', 'aaa'), - array(new \DateTime('today'), new \DateTime('yesterday')), - array(new \DateTime('today'), new \DateTime('today')), - ); - } - - /** - * @dataProvider invalidLessProvider - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_LESS - * - * @param mixed $value - * @param mixed $limit - */ - public function testLessThanThrowsException($value, $limit) - { - Assertion::lessThan($value, $limit); - } - - public function testLessOrEqualThan() - { - $this->assertTrue(Assertion::lessOrEqualThan(1, 2)); - $this->assertTrue(Assertion::lessOrEqualThan(1, 1)); - $this->assertTrue(Assertion::lessOrEqualThan('aaa', 'bbb')); - $this->assertTrue(Assertion::lessOrEqualThan('aaa', 'aaaa')); - $this->assertTrue(Assertion::lessOrEqualThan('aaa', 'aaa')); - $this->assertTrue(Assertion::lessOrEqualThan(new \DateTime('today'), new \DateTime('tomorrow'))); - $this->assertTrue(Assertion::lessOrEqualThan(new \DateTime('today'), new \DateTime('today'))); - } - - public function invalidLessOrEqualProvider() - { - return array( - array(2, 1), - array('aaaa', 'aaa'), - array(new \DateTime('today'), new \DateTime('yesterday')), - ); - } - - /** - * @dataProvider invalidLessOrEqualProvider - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_LESS_OR_EQUAL - * - * @param mixed $value - * @param mixed $limit - */ - public function testLessOrEqualThanThrowsException($value, $limit) - { - Assertion::lessOrEqualThan($value, $limit); - } - - public function testGreaterThan() - { - $this->assertTrue(Assertion::greaterThan(2, 1)); - $this->assertTrue(Assertion::greaterThan('bbb', 'aaa')); - $this->assertTrue(Assertion::greaterThan('aaaa', 'aaa')); - $this->assertTrue(Assertion::greaterThan(new \DateTime('tomorrow'), new \DateTime('today'))); - } - - public function invalidGreaterProvider() - { - return array( - array(1, 2), - array(2, 2), - array('aaa', 'aaa'), - array('aaa', 'aaaa'), - array(new \DateTime('yesterday'), new \DateTime('today')), - array(new \DateTime('today'), new \DateTime('today')), - ); - } - - /** - * @dataProvider validDateProvider - * - * @param string $value - * @param string $format - */ - public function testValidDate($value, $format) - { - $this->assertTrue(Assertion::date($value, $format)); - } - - public function validDateProvider() - { - return array( - array('2012-03-13', 'Y-m-d'), - array('29.02.2012 12:03:36.432563', 'd.m.Y H:i:s.u'), - array('13.08.2015 17:08:23 Thu Thursday th 224 August Aug 8 15 17 432563 UTC UTC', 'd.m.Y H:i:s D l S z F M n y H u e T'), - array('1439486158', 'U'), - ); - } - - /** - * @dataProvider invalidGreaterProvider - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_GREATER - * - * @param mixed $value - * @param mixed $limit - */ - public function testGreaterThanThrowsException($value, $limit) - { - Assertion::greaterThan($value, $limit); - } - - public function testGreaterOrEqualThan() - { - $this->assertTrue(Assertion::greaterOrEqualThan(2, 1)); - $this->assertTrue(Assertion::greaterOrEqualThan(1, 1)); - $this->assertTrue(Assertion::greaterOrEqualThan('bbb', 'aaa')); - $this->assertTrue(Assertion::greaterOrEqualThan('aaaa', 'aaa')); - $this->assertTrue(Assertion::greaterOrEqualThan('aaa', 'aaa')); - $this->assertTrue(Assertion::greaterOrEqualThan(new \DateTime('tomorrow'), new \DateTime('today'))); - $this->assertTrue(Assertion::greaterOrEqualThan(new \DateTime('today'), new \DateTime('today'))); - } - - public function invalidGreaterOrEqualProvider() - { - return array( - array(1, 2), - array('aaa', 'aaaa'), - array(new \DateTime('yesterday'), new \DateTime('tomorrow')), - ); - } - - /** - * @dataProvider invalidGreaterOrEqualProvider - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_GREATER_OR_EQUAL - * - * @param mixed $value - * @param mixed $limit - */ - public function testGreaterOrEqualThanThrowsException($value, $limit) - { - Assertion::greaterOrEqualThan($value, $limit); - } - - /** - * @dataProvider invalidDateProvider - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_DATE - * - * @param string $value - * @param string $format - */ - public function testInvalidDate($value, $format) - { - Assertion::date($value, $format); - } - - public function invalidDateProvider() - { - return array( - array('this is not the date', 'Y-m-d'), - array('2011-02-29', 'Y-m-d'), - array('2012.02.29 12:60:36.432563', 'Y.m.d H:i:s.u'), - ); - } - - public function testValidTraversable() - { - $this->assertTrue(Assertion::isTraversable(new \ArrayObject())); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_TRAVERSABLE - */ - public function testInvalidTraversable() - { - Assertion::isTraversable('not traversable'); - } - - public function testValidArrayAccessible() - { - $this->assertTrue(Assertion::isArrayAccessible(new \ArrayObject())); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_ARRAY_ACCESSIBLE - */ - public function testInvalidArrayAccessible() - { - Assertion::isArrayAccessible('not array accessible'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_CALLABLE - */ - public function testInvalidCallable() - { - Assertion::isCallable('nonExistingFunction'); - } - - public function testValidCallable() - { - $this->assertTrue(Assertion::isCallable('\is_callable')); - $this->assertTrue(Assertion::isCallable(__NAMESPACE__ . '\\Fixtures\\someCallable')); - $this->assertTrue(Assertion::isCallable(array(__NAMESPACE__ . '\\Fixtures\\OneCountable', 'count'))); - $this->assertTrue( - Assertion::isCallable( - function () { - } - ) - ); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_SATISFY - */ - public function testInvalidSatisfy() - { - Assertion::satisfy( - null, - function ($value) { - return !\is_null($value); - } - ); - } - - public function testValidSatisfy() - { - // Should not fail with true return - $this->assertTrue( - Assertion::satisfy( - null, - function ($value) { - return \is_null($value); - } - ) - ); - - // Should not fail with void return - $this->assertTrue( - Assertion::satisfy( - true, - function ($value) { - if (!\is_bool($value)) { - return false; - } - } - ) - ); - } - - /** - * @dataProvider validIpProvider - * - * @param string $value - */ - public function testValidIp($value) - { - $this->assertTrue(Assertion::ip($value)); - } - - public function validIpProvider() - { - return array( - array('0.0.0.0'), - array('14.32.152.216'), - array('255.255.255.255'), - array('2001:db8:85a3:8d3:1319:8a2e:370:7348'), - ); - } - - /** - * @dataProvider invalidIpProvider - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_IP - * - * @param string $value - * @param int|null $flag - */ - public function testInvalidIp($value, $flag = null) - { - Assertion::ip($value, $flag); - } - - public function invalidIpProvider() - { - return array( - array('invalid ip address'), - array('14.32.152,216'), - array('14.32.256.216'), - array('192.168.0.10', FILTER_FLAG_NO_PRIV_RANGE), - array('127.0.0.1', FILTER_FLAG_NO_RES_RANGE), - array('2001:db8:85a3:8d3:1319:8g2e:370:7348'), - array('fdb9:75b9:9e69:5d08:1:1:1:1', FILTER_FLAG_NO_PRIV_RANGE), - ); - } - - public function testValidIpv4() - { - $this->assertTrue(Assertion::ipv4('109.188.127.26')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_IP - */ - public function testInvalidIpv4() - { - Assertion::ipv4('2001:db8:85a3:8d3:1319:8a2e:370:7348'); - } - - public function testValidIpv6() - { - $this->assertTrue(Assertion::ipv6('2001:db8:85a3:8d3:1319:8a2e:370:7348')); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_IP - */ - public function testInvalidIpv6() - { - Assertion::ipv6('109.188.127.26'); - } - - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_INTERFACE - */ - public function testInvalidInterfaceExists() - { - Assertion::interfaceExists('Foo'); - } - - public function testValidInterfaceExists() - { - $this->assertTrue(Assertion::interfaceExists('\\Countable')); - } - - /** - * @dataProvider providerInvalidBetween - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_BETWEEN - * - * @param mixed $value - * @param mixed $lowerLimit - * @param mixed $upperLimit - */ - public function testInvalidBetween($value, $lowerLimit, $upperLimit) + public function testNullOr() { - Assertion::between($value, $lowerLimit, $upperLimit); + $this->assertTrue(Assertion::nullOrMax(null, 1)); + $this->assertTrue(Assertion::nullOrMax(null, 2)); } /** - * @return array + * @expectedException \BadMethodCallException + * @expectedExceptionMessage Missing the first argument. */ - public function providerInvalidBetween() + public function testNullOrWithNoValueThrows() { - return array( - array(1, 2, 3), - array(3, 1, 2), - array('aaa', 'bbb', 'ccc'), - array('ddd', 'bbb', 'ccc'), - array(new \DateTime('yesterday'), new \DateTime('today'), new \DateTime('tomorrow')), - array(new \DateTime('tomorrow'), new \DateTime('yesterday'), new \DateTime('today')), - ); + Assertion::nullOrMax(); } /** - * @dataProvider providerValidBetween - * - * @param mixed $value - * @param mixed $lowerLimit - * @param mixed $upperLimit + * @expectedException \BadMethodCallException + * @expectedExceptionMessage No assertion */ - public function testValidBetween($value, $lowerLimit, $upperLimit) + public function testFailedNullOrMethodCall() { - $this->assertTrue(Assertion::between($value, $lowerLimit, $upperLimit)); + Assertion::nullOrAssertionDoesNotExist(''); } - /** - * @return array - */ - public function providerValidBetween() + public function testAllWithSimpleAssertion() { - return array( - array(2, 1, 3), - array(1, 1, 1), - array('bbb', 'aaa', 'ccc'), - array('aaa', 'aaa', 'aaa'), - array(new \DateTime('today'), new \DateTime('yesterday'), new \DateTime('tomorrow')), - array(new \DateTime('today'), new \DateTime('today'), new \DateTime('today')), - ); + $this->assertTrue(Assertion::allTrue(array(true, true))); } /** - * @dataProvider providerInvalidBetweenExclusive * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_BETWEEN_EXCLUSIVE - * - * @param mixed $value - * @param mixed $lowerLimit - * @param mixed $upperLimit - */ - public function testInvalidBetweenExclusive($value, $lowerLimit, $upperLimit) - { - Assertion::betweenExclusive($value, $lowerLimit, $upperLimit); - } - - /** - * @return array - */ - public function providerInvalidBetweenExclusive() - { - return array( - array(1, 1, 2), - array(2, 1, 2), - array('aaa', 'aaa', 'bbb'), - array('bbb', 'aaa', 'bbb'), - array(new \DateTime('today'), new \DateTime('today'), new \DateTime('tomorrow')), - array(new \DateTime('tomorrow'), new \DateTime('today'), new \DateTime('tomorrow')), - ); - } - - /** - * @dataProvider providerValidBetweenExclusive - * - * @param mixed $value - * @param mixed $lowerLimit - * @param mixed $upperLimit - */ - public function testValidBetweenExclusive($value, $lowerLimit, $upperLimit) - { - $this->assertTrue(Assertion::betweenExclusive($value, $lowerLimit, $upperLimit)); - } - - /** - * @return array + * @expectedExceptionCode \Assert\Assertion\INVALID_TRUE */ - public function providerValidBetweenExclusive() + public function testAllWithSimpleAssertionThrowsExceptionOnElementThatFailsAssertion() { - return array( - array(2, 1, 3), - array('bbb', 'aaa', 'ccc'), - array(new \DateTime('today'), new \DateTime('yesterday'), new \DateTime('tomorrow')), - ); + Assertion::allTrue(array(true, false)); } - /** - * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_FLOAT - * @expectedExceptionMessage 1234567... - */ - public function testStringifyTruncatesStringValuesLongerThan100CharactersAppropriately() + public function testAllWithComplexAssertion() { - $string = \str_repeat('1234567890', 11); - - $this->assertTrue(Assertion::float($string)); + $this->assertTrue(Assertion::allIsInstanceOf(array(new \stdClass(), new \stdClass()), 'stdClass')); } /** * @expectedException \Assert\AssertionFailedException - * @expectedExceptionCode \Assert\Assertion::INVALID_FLOAT - * @expectedExceptionMessage stream - */ - public function testStringifyReportsResourceType() - { - $this->assertTrue(Assertion::float(\fopen('php://stdin', 'rb'))); - } - - public function testExtensionLoaded() - { - $this->assertTrue(Assertion::extensionLoaded('date')); - } - - /** - * @expectedException \Assert\InvalidArgumentException - */ - public function testExtensionNotLoaded() - { - Assertion::extensionLoaded('NOT_LOADED'); - } - - public function testValidConstant() - { - $this->assertTrue(Assertion::defined('PHP_VERSION')); - } - - /** - * @expectedException \Assert\InvalidArgumentException - */ - public function testInvalidConstant() - { - Assertion::defined('NOT_A_CONSTANT'); - } - - public function testValidVersion() - { - $this->assertTrue(Assertion::version('1.0.0', '<', '2.0.0')); - } - - /** - * @expectedException \Assert\InvalidArgumentException - */ - public function testInvalidVersion() - { - Assertion::version('1.0.0', 'eq', '2.0.0'); - } - - /** - * @expectedException \Assert\InvalidArgumentException - */ - public function testInvalidVersionOperator() - { - Assertion::version('1.0.0', null, '2.0.0'); - } - - public function testValidPhpVersion() - { - $this->assertTrue(Assertion::phpVersion('>', '4.0.0')); - } - - /** - * @expectedException \Assert\InvalidArgumentException - */ - public function testInvalidPhpVersion() - { - Assertion::phpVersion('<', '5.0.0'); - } - - public function testValidExtensionVersion() - { - $this->assertTrue(Assertion::extensionVersion('json', '>', '1.0.0')); - } - - /** - * @expectedException \Assert\InvalidArgumentException - */ - public function testInvalidExtensionVersion() - { - Assertion::extensionVersion('json', '<', '0.1.0'); - } - - public function testObjectOrClass() - { - self::assertTrue(Assertion::objectOrClass(new \stdClass())); - self::assertTrue(Assertion::objectOrClass('stdClass')); - } - - /** - * @expectedException \Assert\InvalidArgumentException - */ - public function testNotObjectOrClass() - { - Assertion::objectOrClass('InvalidClassName'); - } - - public function testPropertyExists() - { - self::assertTrue(Assertion::propertyExists(new \Exception(), 'message')); - } - - /** - * @expectedException \Assert\InvalidArgumentException - * @expectedExceptionCode \Assert\Assertion::INVALID_PROPERTY - */ - public function testInvalidPropertyExists() - { - Assertion::propertyExists(new \Exception(), 'invalidProperty'); - } - - public function testPropertiesExist() - { - self::assertTrue(Assertion::propertiesExist(new \Exception(), array('message', 'code', 'previous'))); - } - - public function invalidPropertiesExistProvider() - { - return array( - array(array('invalidProperty')), - array(array('invalidProperty', 'anotherInvalidProperty')), - ); - } - - /** - * @dataProvider invalidPropertiesExistProvider - * @expectedException \Assert\InvalidArgumentException - * @expectedExceptionCode \Assert\Assertion::INVALID_PROPERTY - * - * @param array $properties + * @expectedExceptionCode \Assert\Assertion\INVALID_INSTANCE_OF */ - public function testInvalidPropertiesExist($properties) - { - Assertion::propertiesExist(new \Exception(), $properties); - } - - public function testIsResource() + public function testAllWithComplexAssertionThrowsExceptionOnElementThatFailsAssertion() { - self::assertTrue(Assertion::isResource(\curl_init())); + Assertion::allIsInstanceOf(array(new \stdClass(), new \stdClass()), 'PDO', 'Assertion failed', 'foos'); } /** - * @expectedException \Assert\InvalidArgumentException + * @expectedException \BadMethodCallException */ - public function testIsNotResource() + public function testAllWithNoValueThrows() { - Assertion::isResource(new \stdClass()); + Assertion::allTrue(); } public function testBase64() diff --git a/tests/Assert/Tests/Assertion/ArrayTraitTest.php b/tests/Assert/Tests/Assertion/ArrayTraitTest.php new file mode 100644 index 00000000..ce50b54f --- /dev/null +++ b/tests/Assert/Tests/Assertion/ArrayTraitTest.php @@ -0,0 +1,242 @@ +assertTrue(Assertion::notInArray(6, \range(1, 5))); + $this->assertTrue(Assertion::notInArray('a', \range('b', 'z'))); + + Assertion::notInArray(1, \range(1, 5)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_CHOICE + */ + public function testInvalidInArray() + { + Assertion::inArray('bar', array('baz')); + } + + public function testValidInArray() + { + $this->assertTrue(Assertion::inArray('foo', array('foo'))); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_CHOICE + */ + public function testInvalidChoice() + { + Assertion::choice('foo', array('bar', 'baz')); + } + + public function testValidChoice() + { + $this->assertTrue(Assertion::choice('foo', array('foo'))); + } + + public function testValidTraversable() + { + $this->assertTrue(Assertion::isTraversable(new \ArrayObject())); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_TRAVERSABLE + */ + public function testInvalidTraversable() + { + Assertion::isTraversable('not traversable'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_KEY_EXISTS + */ + public function testInvalidKeyExists() + { + Assertion::keyExists(array('foo' => 'bar'), 'baz'); + } + + public function testValidKeyExists() + { + $this->assertTrue(Assertion::keyExists(array('foo' => 'bar'), 'foo')); + } + + public static function dataInvalidArray() + { + return array( + array(null), + array(false), + array('test'), + array(1), + array(1.23), + array(new \stdClass()), + array(\fopen('php://memory', 'r')), + ); + } + + /** + * @dataProvider dataInvalidArray + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_ARRAY + * + * @param mixed $value + */ + public function testInvalidArray($value) + { + Assertion::isArray($value); + } + + public function testValidArray() + { + $this->assertTrue(Assertion::isArray(array())); + $this->assertTrue(Assertion::isArray(array(1, 2, 3))); + $this->assertTrue(Assertion::isArray(array(array(), array()))); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_KEY_NOT_EXISTS + */ + public function testInvalidKeyNotExists() + { + Assertion::keyNotExists(array('foo' => 'bar'), 'foo'); + } + + public function testValidKeyNotExists() + { + $this->assertTrue(Assertion::keyNotExists(array('foo' => 'bar'), 'baz')); + } + + public function testValidCount() + { + $this->assertTrue(Assertion::count(array('Hi'), 1)); + $this->assertTrue(Assertion::count(new OneCountable(), 1)); + } + + public static function dataInvalidCount() + { + return array( + array(array('Hi', 'There'), 3), + array(new OneCountable(), 2), + ); + } + + /** + * @dataProvider dataInvalidCount + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_COUNT + * @expectedExceptionMessageRegExp /List does not contain exactly "\d+" elements./ + * + * @param mixed $countable + * @param int $count + */ + public function testInvalidCount($countable, $count) + { + Assertion::count($countable, $count); + } + + public function testChoicesNotEmpty() + { + $this->assertTrue(Assertion::choicesNotEmpty( + array('tux' => 'linux', 'Gnu' => 'dolphin'), + array('tux') + )); + } + + /** + * @dataProvider invalidChoicesProvider + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\VALUE_EMPTY + * + * @param $values + * @param $choices + */ + public function testChoicesNotEmptyExpectingExceptionEmptyValue($values, $choices) + { + Assertion::choicesNotEmpty($values, $choices); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_KEY_ISSET + */ + public function testChoicesNotEmptyExpectingExceptionInvalidKeyIsset() + { + Assertion::choicesNotEmpty(array('tux' => ''), array('invalidChoice')); + } + + public function invalidChoicesProvider() + { + return array( + 'empty values' => array(array(), array('tux'), Assertion\VALUE_EMPTY), + 'empty recodes in $values' => array(array('tux' => ''), array('tux'), Assertion\VALUE_EMPTY), + ); + } + + public function testValidNotEmptyKey() + { + $this->assertTrue(Assertion::notEmptyKey(array('keyExists' => 'notEmpty'), 'keyExists')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\VALUE_EMPTY + */ + public function testInvalidNotEmptyKeyEmptyKey() + { + Assertion::notEmptyKey(array('keyExists' => ''), 'keyExists'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_KEY_ISSET + */ + public function testInvalidNotEmptyKeyKeyNotExists() + { + Assertion::notEmptyKey(array('key' => 'notEmpty'), 'keyNotExists'); + } + + public function testValidArrayAccessible() + { + $this->assertTrue(Assertion::isArrayAccessible(new \ArrayObject())); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_ARRAY_ACCESSIBLE + */ + public function testInvalidArrayAccessible() + { + Assertion::isArrayAccessible('not array accessible'); + } +} diff --git a/tests/Assert/Tests/Assertion/BoolTraitTest.php b/tests/Assert/Tests/Assertion/BoolTraitTest.php new file mode 100644 index 00000000..75aa63fc --- /dev/null +++ b/tests/Assert/Tests/Assertion/BoolTraitTest.php @@ -0,0 +1,93 @@ +assertTrue(Assertion::boolean(true)); + $this->assertTrue(Assertion::boolean(false)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_BOOLEAN + */ + public function testInvalidBoolean() + { + Assertion::boolean(1); + } + + public function testValidTrue() + { + $this->assertTrue(Assertion::true(1 > 0)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_TRUE + */ + public function testInvalidTrue() + { + Assertion::true(false); + } + + public function testValidFalse() + { + $this->assertTrue(Assertion::false(1 == 0)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_FALSE + */ + public function testInvalidFalse() + { + Assertion::false(true); + } +} diff --git a/tests/Assert/Tests/Assertion/CallableTraitTest.php b/tests/Assert/Tests/Assertion/CallableTraitTest.php new file mode 100644 index 00000000..d011427a --- /dev/null +++ b/tests/Assert/Tests/Assertion/CallableTraitTest.php @@ -0,0 +1,69 @@ +assertTrue(Assertion::satisfy(null, function ($value) { + return \is_null($value); + })); + + // Should not fail with void return + $this->assertTrue(Assertion::satisfy(true, function ($value) { + if (!\is_bool($value)) { + return false; + } + })); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_CALLABLE + */ + public function testInvalidCallable() + { + Assertion::isCallable('nonExistingFunction'); + } + + public function testValidCallable() + { + $this->assertTrue(Assertion::isCallable('\is_callable')); + $this->assertTrue(Assertion::isCallable('\\Assert\\Tests\\Fixtures\\someCallable')); + $this->assertTrue(Assertion::isCallable(array('\\Assert\\Tests\\Fixtures\\OneCountable', 'count'))); + $this->assertTrue(Assertion::isCallable(function () { + })); + } +} diff --git a/tests/Assert/Tests/Assertion/ClassTraitTest.php b/tests/Assert/Tests/Assertion/ClassTraitTest.php new file mode 100644 index 00000000..e14b2035 --- /dev/null +++ b/tests/Assert/Tests/Assertion/ClassTraitTest.php @@ -0,0 +1,120 @@ +assertTrue(Assertion::subclassOf(new ChildStdClass(), 'stdClass')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_CLASS + */ + public function testInvalidClass() + { + Assertion::classExists('Foo'); + } + + public function testValidClass() + { + $this->assertTrue(Assertion::classExists('\\Exception')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_INTERFACE + */ + public function testInvalidInterfaceExists() + { + Assertion::interfaceExists('Foo'); + } + + public function testValidInterfaceExists() + { + $this->assertTrue(Assertion::interfaceExists('\\Countable')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INTERFACE_NOT_IMPLEMENTED + */ + public function testImplementsInterface() + { + $this->assertTrue(Assertion::implementsInterface('\ArrayIterator', '\Traversable')); + + Assertion::implementsInterface('\Exception', '\Traversable'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INTERFACE_NOT_IMPLEMENTED + */ + public function testImplementsInterfaceWithClassObject() + { + $class = new \ArrayObject(); + + $this->assertTrue(Assertion::implementsInterface($class, '\Traversable')); + + Assertion::implementsInterface($class, '\SplObserver'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_INSTANCE_OF + */ + public function testInvalidInstanceOf() + { + Assertion::isInstanceOf(new \stdClass(), 'PDO'); + } + + public function testValidInstanceOf() + { + $this->assertTrue(Assertion::isInstanceOf(new \stdClass(), 'stdClass')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_NOT_INSTANCE_OF + */ + public function testInvalidNotInstanceOf() + { + Assertion::notIsInstanceOf(new \stdClass(), 'stdClass'); + } + + public function testValidNotIsInstanceOf() + { + $this->assertTrue(Assertion::notIsInstanceOf(new \stdClass(), 'PDO')); + } +} diff --git a/tests/Assert/Tests/Assertion/CompareTraitTest.php b/tests/Assert/Tests/Assertion/CompareTraitTest.php new file mode 100644 index 00000000..40d07862 --- /dev/null +++ b/tests/Assert/Tests/Assertion/CompareTraitTest.php @@ -0,0 +1,215 @@ +assertTrue(Assertion::eq(1, '1')); + $this->assertTrue(Assertion::eq('foo', true)); + $this->assertTrue(Assertion::eq($obj = new \stdClass(), $obj)); + + Assertion::eq('2', 1); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_SAME + */ + public function testSame() + { + $this->assertTrue(Assertion::same(1, 1)); + $this->assertTrue(Assertion::same('foo', 'foo')); + $this->assertTrue(Assertion::same($obj = new \stdClass(), $obj)); + + Assertion::same(new \stdClass(), new \stdClass()); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_NOT_EQ + */ + public function testNotEq() + { + $this->assertTrue(Assertion::notEq('1', false)); + $this->assertTrue(Assertion::notEq(new \stdClass(), array())); + + Assertion::notEq('1', 1); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_NOT_SAME + */ + public function testNotSame() + { + $this->assertTrue(Assertion::notSame('1', 2)); + $this->assertTrue(Assertion::notSame(new \stdClass(), array())); + + Assertion::notSame(1, 1); + } + + public static function dataInvalidNotEmpty() + { + return array( + array(''), + array(false), + array(0), + array(null), + array(array()), + ); + } + + /** + * @dataProvider dataInvalidNotEmpty + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\VALUE_EMPTY + * + * @param mixed $value + */ + public function testInvalidNotEmpty($value) + { + Assertion::notEmpty($value); + } + + public function testNotEmpty() + { + $this->assertTrue(Assertion::notEmpty('test')); + $this->assertTrue(Assertion::notEmpty(1)); + $this->assertTrue(Assertion::notEmpty(true)); + $this->assertTrue(Assertion::notEmpty(array('foo'))); + } + + public function testEmpty() + { + $this->assertTrue(Assertion::noContent('')); + $this->assertTrue(Assertion::noContent(0)); + $this->assertTrue(Assertion::noContent(false)); + $this->assertTrue(Assertion::noContent(array())); + } + + public static function dataInvalidEmpty() + { + return array( + array('foo'), + array(true), + array(12), + array(array('foo')), + array(new \stdClass()), + ); + } + + /** + * @dataProvider dataInvalidEmpty + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\VALUE_NOT_EMPTY + * + * @param mixed $value + */ + public function testInvalidEmpty($value) + { + Assertion::noContent($value); + } + + public static function dataInvalidNull() + { + return array( + array('foo'), + array(''), + array(false), + array(12), + array(0), + array(array()), + ); + } + + /** + * @dataProvider dataInvalidNull + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\VALUE_NOT_NULL + * + * @param mixed $value + */ + public function testInvalidNull($value) + { + Assertion::null($value); + } + + public function testNull() + { + $this->assertTrue(Assertion::null(null)); + } + + public function testNotNull() + { + $this->assertTrue(Assertion::notNull('1')); + $this->assertTrue(Assertion::notNull(1)); + $this->assertTrue(Assertion::notNull(0)); + $this->assertTrue(Assertion::notNull(array())); + $this->assertTrue(Assertion::notNull(false)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\VALUE_NULL + */ + public function testInvalidNotNull() + { + Assertion::notNull(null); + } + + public static function dataInvalidNotBlank() + { + return array( + array(''), + array(' '), + array("\t"), + array("\n"), + array("\r"), + array(false), + array(null), + array(array()), + ); + } + + /** + * @dataProvider dataInvalidNotBlank + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_NOT_BLANK + * + * @param mixed $notBlank + */ + public function testInvalidNotBlank($notBlank) + { + Assertion::notBlank($notBlank); + } + + public function testValidNotBlank() + { + $this->assertTrue(Assertion::notBlank('foo')); + } +} diff --git a/tests/Assert/Tests/Assertion/EnvironmentTraitTest.php b/tests/Assert/Tests/Assertion/EnvironmentTraitTest.php new file mode 100644 index 00000000..d210c0a7 --- /dev/null +++ b/tests/Assert/Tests/Assertion/EnvironmentTraitTest.php @@ -0,0 +1,99 @@ +assertTrue(Assertion::phpVersion('>', '4.0.0')); + } + + /** + * @expectedException \Assert\InvalidArgumentException + */ + public function testInvalidPhpVersion() + { + Assertion::phpVersion('<', '5.0.0'); + } + + public function testValidConstant() + { + $this->assertTrue(Assertion::defined('PHP_VERSION')); + } + + /** + * @expectedException \Assert\InvalidArgumentException + */ + public function testInvalidConstant() + { + Assertion::defined('NOT_A_CONSTANT'); + } + + public function testValidVersion() + { + $this->assertTrue(Assertion::version('1.0.0', '<', '2.0.0')); + } + + /** + * @expectedException \Assert\InvalidArgumentException + */ + public function testInvalidVersion() + { + Assertion::version('1.0.0', 'eq', '2.0.0'); + } + + /** + * @expectedException \Assert\InvalidArgumentException + */ + public function testInvalidVersionOperator() + { + Assertion::version('1.0.0', null, '2.0.0'); + } + + public function testValidExtensionVersion() + { + $this->assertTrue(Assertion::extensionVersion('json', '>', '1.0.0')); + } + + /** + * @expectedException \Assert\InvalidArgumentException + */ + public function testInvalidExtensionVersion() + { + Assertion::extensionVersion('json', '<', '0.1.0'); + } + + public function testExtensionLoaded() + { + $this->assertTrue(Assertion::extensionLoaded('date')); + } + + /** + * @expectedException \Assert\InvalidArgumentException + */ + public function testExtensionNotLoaded() + { + Assertion::extensionLoaded('NOT_LOADED'); + } +} diff --git a/tests/Assert/Tests/Assertion/FileSystemTraitTest.php b/tests/Assert/Tests/Assertion/FileSystemTraitTest.php new file mode 100644 index 00000000..2cfcc892 --- /dev/null +++ b/tests/Assert/Tests/Assertion/FileSystemTraitTest.php @@ -0,0 +1,95 @@ +assertTrue(Assertion::file(__FILE__)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\VALUE_EMPTY + */ + public function testFileWithEmptyFilename() + { + Assertion::file(''); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_FILE + */ + public function testFileDoesNotExists() + { + Assertion::file(__DIR__ . '/does-not-exists'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_DIRECTORY + */ + public function testDirectory() + { + $this->assertTrue(Assertion::directory(__DIR__)); + + Assertion::directory(__DIR__ . '/does-not-exist'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_READABLE + */ + public function testReadable() + { + $this->assertTrue(Assertion::readable(__FILE__)); + + Assertion::readable(__DIR__ . '/does-not-exist'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_WRITEABLE + */ + public function testWriteable() + { + $this->assertTrue(Assertion::writeable(\sys_get_temp_dir())); + + Assertion::writeable(__DIR__ . '/does-not-exist'); + } + + public function testIsResource() + { + self::assertTrue(Assertion::isResource(\curl_init())); + } + + /** + * @expectedException \Assert\InvalidArgumentException + */ + public function testIsNotResource() + { + Assertion::isResource(new \stdClass()); + } +} diff --git a/tests/Assert/Tests/Assertion/NumberTraitTest.php b/tests/Assert/Tests/Assertion/NumberTraitTest.php new file mode 100644 index 00000000..eab3d976 --- /dev/null +++ b/tests/Assert/Tests/Assertion/NumberTraitTest.php @@ -0,0 +1,478 @@ +assertTrue(Assertion::integer(10)); + $this->assertTrue(Assertion::integer(0)); + } + + public static function dataInvalidFloat() + { + return array( + array(1), + array(false), + array('test'), + array(null), + array('1.23'), + array('10'), + ); + } + + /** + * @dataProvider dataInvalidFloat + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_FLOAT + * + * @param mixed $nonFloat + */ + public function testInvalidFloat($nonFloat) + { + Assertion::float($nonFloat); + } + + public function testValidFloat() + { + $this->assertTrue(Assertion::float(1.0)); + $this->assertTrue(Assertion::float(0.1)); + $this->assertTrue(Assertion::float(-1.1)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_FLOAT + * @expectedExceptionMessage 1234567... + */ + public function testStringifyTruncatesStringValuesLongerThan100CharactersAppropriately() + { + $string = \str_repeat('1234567890', 11); + + $this->assertTrue(Assertion::float($string)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_FLOAT + * @expectedExceptionMessage stream + */ + public function testStringifyReportsResourceType() + { + $this->assertTrue(Assertion::float(\fopen('php://stdin', 'rb'))); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_DIGIT + */ + public function testInvalidDigit() + { + Assertion::digit(-1); + } + + public function testValidDigit() + { + $this->assertTrue(Assertion::digit(1)); + $this->assertTrue(Assertion::digit(0)); + $this->assertTrue(Assertion::digit('0')); + } + + public function testValidIntegerish() + { + $this->assertTrue(Assertion::integerish(10)); + $this->assertTrue(Assertion::integerish('10')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_RANGE + */ + public function testInvalidRange() + { + Assertion::range(1, 2, 3); + Assertion::range(1.5, 2, 3); + } + + public function testValidRange() + { + $this->assertTrue(Assertion::range(1, 1, 2)); + $this->assertTrue(Assertion::range(2, 1, 2)); + $this->assertTrue(Assertion::range(2, 0, 100)); + $this->assertTrue(Assertion::range(2.5, 2.25, 2.75)); + } + + public function testThatAssertionExceptionCanAccessValueAndSupplyConstraints() + { + try { + Assertion::range(0, 10, 20); + + $this->fail('Exception expected'); + } catch (AssertionFailedException $e) { + $this->assertEquals(0, $e->getValue()); + $this->assertEquals(array('min' => 10, 'max' => 20), $e->getConstraints()); + } + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_NUMERIC + */ + public function testInvalidNumeric() + { + Assertion::numeric('foo'); + } + + public function testValidNumeric() + { + $this->assertTrue(Assertion::numeric('1')); + $this->assertTrue(Assertion::numeric(1)); + $this->assertTrue(Assertion::numeric(1.23)); + } + + public function testMin() + { + $this->assertTrue(Assertion::min(1, 1)); + $this->assertTrue(Assertion::min(2, 1)); + $this->assertTrue(Assertion::min(2.5, 1)); + } + + /** + * @dataProvider dataInvalidMin + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_MIN + * @expectedExceptionMessageRegExp /Number "(0\.5|0)" was expected to be at least "(1|2\.5)"/ + * + * @param float|int $value + * @param float|int $min + */ + public function testInvalidMin($value, $min) + { + Assertion::min($value, $min); + } + + public function dataInvalidMin() + { + return array( + array(0, 1), + array(0.5, 2.5), + ); + } + + public function testMax() + { + $this->assertTrue(Assertion::max(1, 1)); + $this->assertTrue(Assertion::max(0.5, 1)); + $this->assertTrue(Assertion::max(0, 1)); + } + + /** + * @dataProvider dataInvalidMax + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_MAX + * @expectedExceptionMessageRegExp /Number "(2.5|2)" was expected to be at most "(1|0\.5)"/ + * + * @param float|int $value + * @param float|int $min + */ + public function testInvalidMax($value, $min) + { + Assertion::max($value, $min); + } + + public function dataInvalidMax() + { + return array( + array(2, 1), + array(2.5, 0.5), + ); + } + + public function testLessThan() + { + $this->assertTrue(Assertion::lessThan(1, 2)); + $this->assertTrue(Assertion::lessThan('aaa', 'bbb')); + $this->assertTrue(Assertion::lessThan('aaa', 'aaaa')); + $this->assertTrue(Assertion::lessThan(new \DateTime('today'), new \DateTime('tomorrow'))); + } + + public function invalidLessProvider() + { + return array( + array(2, 1), + array(2, 2), + array('aaa', 'aaa'), + array('aaaa', 'aaa'), + array(new \DateTime('today'), new \DateTime('yesterday')), + array(new \DateTime('today'), new \DateTime('today')), + ); + } + + /** + * @dataProvider invalidLessProvider + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_LESS + * + * @param mixed $value + * @param mixed $limit + */ + public function testLessThanThrowsException($value, $limit) + { + Assertion::lessThan($value, $limit); + } + + public function testLessOrEqualThan() + { + $this->assertTrue(Assertion::lessOrEqualThan(1, 2)); + $this->assertTrue(Assertion::lessOrEqualThan(1, 1)); + $this->assertTrue(Assertion::lessOrEqualThan('aaa', 'bbb')); + $this->assertTrue(Assertion::lessOrEqualThan('aaa', 'aaaa')); + $this->assertTrue(Assertion::lessOrEqualThan('aaa', 'aaa')); + $this->assertTrue(Assertion::lessOrEqualThan(new \DateTime('today'), new \DateTime('tomorrow'))); + $this->assertTrue(Assertion::lessOrEqualThan(new \DateTime('today'), new \DateTime('today'))); + } + + public function invalidLessOrEqualProvider() + { + return array( + array(2, 1), + array('aaaa', 'aaa'), + array(new \DateTime('today'), new \DateTime('yesterday')), + ); + } + + /** + * @dataProvider invalidLessOrEqualProvider + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_LESS_OR_EQUAL + * + * @param mixed $value + * @param mixed $limit + */ + public function testLessOrEqualThanThrowsException($value, $limit) + { + Assertion::lessOrEqualThan($value, $limit); + } + + public function testGreaterThan() + { + $this->assertTrue(Assertion::greaterThan(2, 1)); + $this->assertTrue(Assertion::greaterThan('bbb', 'aaa')); + $this->assertTrue(Assertion::greaterThan('aaaa', 'aaa')); + $this->assertTrue(Assertion::greaterThan(new \DateTime('tomorrow'), new \DateTime('today'))); + } + + public function invalidGreaterProvider() + { + return array( + array(1, 2), + array(2, 2), + array('aaa', 'aaa'), + array('aaa', 'aaaa'), + array(new \DateTime('yesterday'), new \DateTime('today')), + array(new \DateTime('today'), new \DateTime('today')), + ); + } + + /** + * @dataProvider invalidGreaterProvider + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_GREATER + * + * @param mixed $value + * @param mixed $limit + */ + public function testGreaterThanThrowsException($value, $limit) + { + Assertion::greaterThan($value, $limit); + } + + public function testGreaterOrEqualThan() + { + $this->assertTrue(Assertion::greaterOrEqualThan(2, 1)); + $this->assertTrue(Assertion::greaterOrEqualThan(1, 1)); + $this->assertTrue(Assertion::greaterOrEqualThan('bbb', 'aaa')); + $this->assertTrue(Assertion::greaterOrEqualThan('aaaa', 'aaa')); + $this->assertTrue(Assertion::greaterOrEqualThan('aaa', 'aaa')); + $this->assertTrue(Assertion::greaterOrEqualThan(new \DateTime('tomorrow'), new \DateTime('today'))); + $this->assertTrue(Assertion::greaterOrEqualThan(new \DateTime('today'), new \DateTime('today'))); + } + + public function invalidGreaterOrEqualProvider() + { + return array( + array(1, 2), + array('aaa', 'aaaa'), + array(new \DateTime('yesterday'), new \DateTime('tomorrow')), + ); + } + + /** + * @dataProvider invalidGreaterOrEqualProvider + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_GREATER_OR_EQUAL + * + * @param mixed $value + * @param mixed $limit + */ + public function testGreaterOrEqualThanThrowsException($value, $limit) + { + Assertion::greaterOrEqualThan($value, $limit); + } + + /** + * @dataProvider providerInvalidBetween + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_BETWEEN + * + * @param mixed $value + * @param mixed $lowerLimit + * @param mixed $upperLimit + */ + public function testInvalidBetween($value, $lowerLimit, $upperLimit) + { + Assertion::between($value, $lowerLimit, $upperLimit); + } + + /** + * @return array + */ + public function providerInvalidBetween() + { + return array( + array(1, 2, 3), + array(3, 1, 2), + array('aaa', 'bbb', 'ccc'), + array('ddd', 'bbb', 'ccc'), + array(new \DateTime('yesterday'), new \DateTime('today'), new \DateTime('tomorrow')), + array(new \DateTime('tomorrow'), new \DateTime('yesterday'), new \DateTime('today')), + ); + } + + /** + * @dataProvider providerValidBetween + * + * @param mixed $value + * @param mixed $lowerLimit + * @param mixed $upperLimit + */ + public function testValidBetween($value, $lowerLimit, $upperLimit) + { + $this->assertTrue(Assertion::between($value, $lowerLimit, $upperLimit)); + } + + /** + * @return array + */ + public function providerValidBetween() + { + return array( + array(2, 1, 3), + array(1, 1, 1), + array('bbb', 'aaa', 'ccc'), + array('aaa', 'aaa', 'aaa'), + array(new \DateTime('today'), new \DateTime('yesterday'), new \DateTime('tomorrow')), + array(new \DateTime('today'), new \DateTime('today'), new \DateTime('today')), + ); + } + + /** + * @dataProvider providerInvalidBetweenExclusive + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_BETWEEN_EXCLUSIVE + * + * @param mixed $value + * @param mixed $lowerLimit + * @param mixed $upperLimit + */ + public function testInvalidBetweenExclusive($value, $lowerLimit, $upperLimit) + { + Assertion::betweenExclusive($value, $lowerLimit, $upperLimit); + } + + /** + * @return array + */ + public function providerInvalidBetweenExclusive() + { + return array( + array(1, 1, 2), + array(2, 1, 2), + array('aaa', 'aaa', 'bbb'), + array('bbb', 'aaa', 'bbb'), + array(new \DateTime('today'), new \DateTime('today'), new \DateTime('tomorrow')), + array(new \DateTime('tomorrow'), new \DateTime('today'), new \DateTime('tomorrow')), + ); + } + + /** + * @dataProvider providerValidBetweenExclusive + * + * @param mixed $value + * @param mixed $lowerLimit + * @param mixed $upperLimit + */ + public function testValidBetweenExclusive($value, $lowerLimit, $upperLimit) + { + $this->assertTrue(Assertion::betweenExclusive($value, $lowerLimit, $upperLimit)); + } + + /** + * @return array + */ + public function providerValidBetweenExclusive() + { + return array( + array(2, 1, 3), + array('bbb', 'aaa', 'ccc'), + array(new \DateTime('today'), new \DateTime('yesterday'), new \DateTime('tomorrow')), + ); + } +} diff --git a/tests/Assert/Tests/Assertion/ObjectTraitTest.php b/tests/Assert/Tests/Assertion/ObjectTraitTest.php new file mode 100644 index 00000000..97a1cdde --- /dev/null +++ b/tests/Assert/Tests/Assertion/ObjectTraitTest.php @@ -0,0 +1,107 @@ +assertTrue(Assertion::methodExists('methodExists', new Assertion())); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_METHOD + */ + public function testMethodExistsFailure() + { + Assertion::methodExists('methodNotExists', new Assertion()); + } + + public function testIsObject() + { + $this->assertTrue(Assertion::isObject(new \stdClass())); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_OBJECT + */ + public function testIsObjectExpectingException() + { + Assertion::isObject('notAnObject'); + } + + public function testPropertyExists() + { + self::assertTrue(Assertion::propertyExists(new \Exception(), 'message')); + } + + /** + * @expectedException \Assert\InvalidArgumentException + * @expectedExceptionCode \Assert\Assertion\INVALID_PROPERTY + */ + public function testInvalidPropertyExists() + { + Assertion::propertyExists(new \Exception(), 'invalidProperty'); + } + + public function testObjectOrClass() + { + self::assertTrue(Assertion::objectOrClass(new \stdClass())); + self::assertTrue(Assertion::objectOrClass('stdClass')); + } + + /** + * @expectedException \Assert\InvalidArgumentException + */ + public function testNotObjectOrClass() + { + Assertion::objectOrClass('InvalidClassName'); + } + + public function testPropertiesExist() + { + self::assertTrue(Assertion::propertiesExist(new \Exception(), array('message', 'code', 'previous'))); + } + + public function invalidPropertiesExistProvider() + { + return array( + array(array('invalidProperty')), + array(array('invalidProperty', 'anotherInvalidProperty')), + ); + } + + /** + * @dataProvider invalidPropertiesExistProvider + * @expectedException \Assert\InvalidArgumentException + * @expectedExceptionCode \Assert\Assertion\INVALID_PROPERTY + * + * @param array $properties + */ + public function testInvalidPropertiesExist($properties) + { + Assertion::propertiesExist(new \Exception(), $properties); + } +} diff --git a/tests/Assert/Tests/Assertion/ScalarTraitTest.php b/tests/Assert/Tests/Assertion/ScalarTraitTest.php new file mode 100644 index 00000000..7e96f7c9 --- /dev/null +++ b/tests/Assert/Tests/Assertion/ScalarTraitTest.php @@ -0,0 +1,43 @@ +assertTrue(Assertion::scalar('foo')); + $this->assertTrue(Assertion::scalar(52)); + $this->assertTrue(Assertion::scalar(12.34)); + $this->assertTrue(Assertion::scalar(false)); + } +} diff --git a/tests/Assert/Tests/Assertion/StringTraitTest.php b/tests/Assert/Tests/Assertion/StringTraitTest.php new file mode 100644 index 00000000..f2e7b655 --- /dev/null +++ b/tests/Assert/Tests/Assertion/StringTraitTest.php @@ -0,0 +1,632 @@ +assertTrue(Assertion::length('asdf', 4)); + $this->assertTrue(Assertion::length('', 0)); + } + + public static function dataLengthUtf8Characters() + { + return array( + array('址', 1), + array('ل', 1), + ); + } + + /** + * @dataProvider dataLengthUtf8Characters + * + * @param string $value + * @param int $expected + */ + public function testLengthUtf8Characters($value, $expected) + { + $this->assertTrue(Assertion::length($value, $expected)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_LENGTH + */ + public function testLengthFailed() + { + Assertion::length('asdf', 3); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_LENGTH + */ + public function testLengthFailedForWrongEncoding() + { + Assertion::length('址', 1, null, null, 'ASCII'); + } + + public function testLengthValidForGivenEncoding() + { + $this->assertTrue(Assertion::length('址', 1, null, null, 'utf8')); + } + + public function testString() + { + $this->assertTrue(Assertion::string('test-string')); + $this->assertTrue(Assertion::string('')); + } + + /** + * @dataProvider dataInvalidString + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_STRING + * + * @param mixed $invalidString + */ + public function testInvalidString($invalidString) + { + Assertion::string($invalidString); + } + + public static function dataInvalidString() + { + return array( + array(1.23), + array(false), + array(new \ArrayObject()), + array(null), + array(10), + array(true), + ); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_MIN_LENGTH + */ + public function testInvalidBetweenLengthMin() + { + Assertion::betweenLength('foo', 4, 100); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_MAX_LENGTH + */ + public function testInvalidBetweenLengthMax() + { + Assertion::betweenLength('foo', 0, 2); + } + + public function testValidBetweenLength() + { + $this->assertTrue(Assertion::betweenLength('foo', 0, 3)); + $this->assertTrue(Assertion::betweenLength('址址', 2, 2)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_MIN_LENGTH + */ + public function testInvalidMinLength() + { + Assertion::minLength('foo', 4); + } + + public function testValidMinLength() + { + $this->assertTrue(Assertion::minLength('foo', 3)); + $this->assertTrue(Assertion::minLength('foo', 1)); + $this->assertTrue(Assertion::minLength('foo', 0)); + $this->assertTrue(Assertion::minLength('', 0)); + $this->assertTrue(Assertion::minLength('址址', 2)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_MAX_LENGTH + */ + public function testInvalidMaxLength() + { + Assertion::maxLength('foo', 2); + } + + public function testValidMaxLength() + { + $this->assertTrue(Assertion::maxLength('foo', 10)); + $this->assertTrue(Assertion::maxLength('foo', 3)); + $this->assertTrue(Assertion::maxLength('', 0)); + $this->assertTrue(Assertion::maxLength('址址', 2)); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_STRING_START + */ + public function testInvalidStartsWith() + { + Assertion::startsWith('foo', 'bar'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_STRING_START + */ + public function testInvalidStartsWithDueToWrongEncoding() + { + Assertion::startsWith('址', '址址', null, null, 'ASCII'); + } + + public function testValidStartsWith() + { + $this->assertTrue(Assertion::startsWith('foo', 'foo')); + $this->assertTrue(Assertion::startsWith('foo', 'fo')); + $this->assertTrue(Assertion::startsWith('foo', 'f')); + $this->assertTrue(Assertion::startsWith('址foo', '址')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_STRING_END + */ + public function testInvalidEndsWith() + { + Assertion::endsWith('foo', 'bar'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_STRING_END + */ + public function testInvalidEndsWithDueToWrongEncoding() + { + Assertion::endsWith('址', '址址', null, null, 'ASCII'); + } + + public function testValidEndsWith() + { + $this->assertTrue(Assertion::endsWith('foo', 'foo')); + $this->assertTrue(Assertion::endsWith('sonderbar', 'bar')); + $this->assertTrue(Assertion::endsWith('opp', 'p')); + $this->assertTrue(Assertion::endsWith('foo址', '址')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_STRING_CONTAINS + */ + public function testInvalidContains() + { + Assertion::contains('foo', 'bar'); + } + + public function testValidContains() + { + $this->assertTrue(Assertion::contains('foo', 'foo')); + $this->assertTrue(Assertion::contains('foo', 'oo')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_EMAIL + */ + public function testInvalidEmail() + { + Assertion::email('foo'); + } + + public function testValidEmail() + { + $this->assertTrue(Assertion::email('123hello+world@email.provider.com')); + } + + /** + * @dataProvider dataInvalidUrl + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_URL + * + * @param string $url + */ + public function testInvalidUrl($url) + { + Assertion::url($url); + } + + public static function dataInvalidUrl() + { + return array( + array('google.com'), + array('://google.com'), + array('http ://google.com'), + array('http:/google.com'), + array('http://goog_le.com'), + array('http://google.com::aa'), + array('http://google.com:aa'), + array('ftp://google.fr'), + array('faked://google.fr'), + array('http://127.0.0.1:aa/'), + array('ftp://[::1]/'), + array('http://[::1'), + array('http://hello.☎/'), + array('http://:password@symfony.com'), + array('http://:password@@symfony.com'), + array('http://username:passwordsymfony.com'), + array('http://usern@me:password@symfony.com'), + ); + } + + /** + * @dataProvider dataValidUrl + * + * @param string $url + */ + public function testValidUrl($url) + { + $this->assertTrue(Assertion::url($url)); + } + + public static function dataValidUrl() + { + return array( + array('http://a.pl'), + array('http://www.google.com'), + array('http://www.google.com.'), + array('http://www.google.museum'), + array('https://google.com/'), + array('https://google.com:80/'), + array('http://www.example.coop/'), + array('http://www.test-example.com/'), + array('http://www.symfony.com/'), + array('http://symfony.fake/blog/'), + array('http://symfony.com/?'), + array('http://symfony.com/search?type=&q=url+validator'), + array('http://symfony.com/#'), + array('http://symfony.com/#?'), + array('http://www.symfony.com/doc/current/book/validation.html#supported-constraints'), + array('http://very.long.domain.name.com/'), + array('http://localhost/'), + array('http://myhost123/'), + array('http://127.0.0.1/'), + array('http://127.0.0.1:80/'), + array('http://[::1]/'), + array('http://[::1]:80/'), + array('http://[1:2:3::4:5:6:7]/'), + array('http://sãopaulo.com/'), + array('http://xn--sopaulo-xwa.com/'), + array('http://sãopaulo.com.br/'), + array('http://xn--sopaulo-xwa.com.br/'), + array('http://пример.испытание/'), + array('http://xn--e1afmkfd.xn--80akhbyknj4f/'), + array('http://مثال.إختبار/'), + array('http://xn--mgbh0fb.xn--kgbechtv/'), + array('http://例子.测试/'), + array('http://xn--fsqu00a.xn--0zwm56d/'), + array('http://例子.測試/'), + array('http://xn--fsqu00a.xn--g6w251d/'), + array('http://例え.テスト/'), + array('http://xn--r8jz45g.xn--zckzah/'), + array('http://مثال.آزمایشی/'), + array('http://xn--mgbh0fb.xn--hgbk6aj7f53bba/'), + array('http://실례.테스트/'), + array('http://xn--9n2bp8q.xn--9t4b11yi5a/'), + array('http://العربية.idn.icann.org/'), + array('http://xn--ogb.idn.icann.org/'), + array('http://xn--e1afmkfd.xn--80akhbyknj4f.xn--e1afmkfd/'), + array('http://xn--espaa-rta.xn--ca-ol-fsay5a/'), + array('http://xn--d1abbgf6aiiy.xn--p1ai/'), + array('http://☎.com/'), + array('http://username:password@symfony.com'), + array('http://user-name@symfony.com'), + array('http://symfony.com?'), + array('http://symfony.com?query=1'), + array('http://symfony.com/?query=1'), + array('http://symfony.com#'), + array('http://symfony.com#fragment'), + array('http://symfony.com/#fragment'), + ); + } + + public function testValidAlnum() + { + $this->assertTrue(Assertion::alnum('a')); + $this->assertTrue(Assertion::alnum('a1')); + $this->assertTrue(Assertion::alnum('aasdf1234')); + $this->assertTrue(Assertion::alnum('a1b2c3')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_ALNUM + */ + public function testInvalidAlnum() + { + Assertion::alnum('1a'); + } + + public function testValidRegex() + { + $this->assertTrue(Assertion::regex('some string', '/.*/')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_REGEX + */ + public function testInvalidRegex() + { + Assertion::regex('foo', '(bar)'); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_STRING + */ + public function testInvalidRegexValueNotString() + { + Assertion::regex(array('foo'), '(bar)'); + } + + /** + * @dataProvider isJsonStringDataprovider + * + * @param $content + */ + public function testIsJsonString($content) + { + $this->assertTrue(Assertion::isJsonString($content)); + } + + public static function isJsonStringDataprovider() + { + return array( + '»null« value' => array(\json_encode(null)), + '»false« value' => array(\json_encode(false)), + 'array value' => array('["false"]'), + 'object value' => array('{"tux":"false"}'), + ); + } + + /** + * @dataProvider isJsonStringInvalidStringDataprovider + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_JSON_STRING + * + * @param $invalidString + */ + public function testIsJsonStringExpectingException($invalidString) + { + Assertion::isJsonString($invalidString); + } + + public static function isJsonStringInvalidStringDataprovider() + { + return array( + 'no json string' => array('invalid json encoded string'), + 'error in json string' => array('{invalid json encoded string}'), + ); + } + + /** + * @dataProvider providesValidUuids + * + * @param string $uuid + */ + public function testValidUuids($uuid) + { + $this->assertTrue(Assertion::uuid($uuid)); + } + + /** + * @dataProvider providesInvalidUuids + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_UUID + * + * @param string $uuid + */ + public function testInvalidUuids($uuid) + { + Assertion::uuid($uuid); + } + + public static function providesValidUuids() + { + return array( + array('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'), + array('ff6f8cb0-c57d-21e1-9b21-0800200c9a66'), + array('ff6f8cb0-c57d-31e1-9b21-0800200c9a66'), + array('ff6f8cb0-c57d-41e1-9b21-0800200c9a66'), + array('ff6f8cb0-c57d-51e1-9b21-0800200c9a66'), + array('FF6F8CB0-C57D-11E1-9B21-0800200C9A66'), + array('00000000-0000-0000-0000-000000000000'), + ); + } + + public static function providesInvalidUuids() + { + return array( + array('zf6f8cb0-c57d-11e1-9b21-0800200c9a66'), + array('af6f8cb0c57d11e19b210800200c9a66'), + array('ff6f8cb0-c57da-51e1-9b21-0800200c9a66'), + array('af6f8cb-c57d-11e1-9b21-0800200c9a66'), + array('3f6f8cb0-c57d-11e1-9b21-0800200c9a6'), + ); + } + + /** + * @dataProvider providesValidE164s + * + * @param string $e164 + */ + public function testValidE164s($e164) + { + $this->assertTrue(Assertion::e164($e164)); + } + + /** + * @dataProvider providesInvalidE164s + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_E164 + * + * @param string $e164 + */ + public function testInvalidE164s($e164) + { + Assertion::e164($e164); + } + + public static function providesValidE164s() + { + return array( + array('+33626525690'), + array('33626525690'), + array('+16174552211'), + ); + } + + public static function providesInvalidE164s() + { + return array( + array('+3362652569e'), + array('+3361231231232652569'), + ); + } + + /** + * @dataProvider validDateProvider + * + * @param string $value + * @param string $format + */ + public function testValidDate($value, $format) + { + $this->assertTrue(Assertion::date($value, $format)); + } + + public function validDateProvider() + { + return array( + array('2012-03-13', 'Y-m-d'), + array('29.02.2012 12:03:36.432563', 'd.m.Y H:i:s.u'), + array('13.08.2015 17:08:23 Thu Thursday th 224 August Aug 8 15 17 432563 UTC UTC', 'd.m.Y H:i:s D l S z F M n y H u e T'), + array('1439486158', 'U'), + ); + } + + /** + * @dataProvider invalidDateProvider + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_DATE + * + * @param string $value + * @param string $format + */ + public function testInvalidDate($value, $format) + { + Assertion::date($value, $format); + } + + public function invalidDateProvider() + { + return array( + array('this is not the date', 'Y-m-d'), + array('2011-02-29', 'Y-m-d'), + array('2012.02.29 12:60:36.432563', 'Y.m.d H:i:s.u'), + ); + } + + /** + * @dataProvider validIpProvider + * + * @param string $value + */ + public function testValidIp($value) + { + $this->assertTrue(Assertion::ip($value)); + } + + public function validIpProvider() + { + return array( + array('0.0.0.0'), + array('14.32.152.216'), + array('255.255.255.255'), + array('2001:db8:85a3:8d3:1319:8a2e:370:7348'), + ); + } + + /** + * @dataProvider invalidIpProvider + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_IP + * + * @param string $value + * @param int|null $flag + */ + public function testInvalidIp($value, $flag = null) + { + Assertion::ip($value, $flag); + } + + public function invalidIpProvider() + { + return array( + array('invalid ip address'), + array('14.32.152,216'), + array('14.32.256.216'), + array('192.168.0.10', FILTER_FLAG_NO_PRIV_RANGE), + array('127.0.0.1', FILTER_FLAG_NO_RES_RANGE), + array('2001:db8:85a3:8d3:1319:8g2e:370:7348'), + array('fdb9:75b9:9e69:5d08:1:1:1:1', FILTER_FLAG_NO_PRIV_RANGE), + ); + } + + public function testValidIpv4() + { + $this->assertTrue(Assertion::ipv4('109.188.127.26')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_IP + */ + public function testInvalidIpv4() + { + Assertion::ipv4('2001:db8:85a3:8d3:1319:8a2e:370:7348'); + } + + public function testValidIpv6() + { + $this->assertTrue(Assertion::ipv6('2001:db8:85a3:8d3:1319:8a2e:370:7348')); + } + + /** + * @expectedException \Assert\AssertionFailedException + * @expectedExceptionCode \Assert\Assertion\INVALID_IP + */ + public function testInvalidIpv6() + { + Assertion::ipv6('109.188.127.26'); + } +} diff --git a/tests/Assert/Tests/PR142_AllowOverridingStringifyTest.php b/tests/Assert/Tests/PR142_AllowOverridingStringifyTest.php index a4ca1644..d50547fb 100644 --- a/tests/Assert/Tests/PR142_AllowOverridingStringifyTest.php +++ b/tests/Assert/Tests/PR142_AllowOverridingStringifyTest.php @@ -43,7 +43,7 @@ public function testInvalidStringWithOverriddenStringify($invalidString, $except try { Fixtures\PR142_OverrideStringify::string($invalidString); } catch (AssertionFailedException $ex) { - $this->assertSame(Assertion::INVALID_STRING, $ex->getCode()); + $this->assertSame(Assertion\INVALID_STRING, $ex->getCode()); $this->assertSame($exceptionMessage, $ex->getMessage()); } }