From a04077098097847db1823890816d1d632206066a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20FIDRY?= Date: Fri, 25 May 2018 21:51:29 +0200 Subject: [PATCH] Harden the tests (#237) - Fix the coverage of some files (whitelist the files that should not be covered) - Make `MapFile` return the unchanged path if no mapping is found for the given path: this allows to simplify some code - Update the `ComposerOrchestrator` to not change the original `vendor/autoload.php` file if not necessary and make the changer prettier and more accurate (pure styling, no semantic change) when the file is changed - Remove the config JSON imports support - Fix some typos - Add a lot of tests and rework some --- .gitignore | 1 + Makefile | 13 +- fixtures/PhpScoper/FakeScoper.php | 46 + fixtures/composer-dump/dir000/composer.json | 5 + fixtures/composer-dump/dir001/composer.json | 5 + fixtures/composer-dump/dir001/composer.lock | 73 + fixtures/composer-dump/dir002/composer.json | 5 + fixtures/composer-dump/dir002/composer.lock | 73 + .../dir002/vendor/beberlei/assert/LICENSE | 11 + .../vendor/beberlei/assert/composer.json | 54 + .../beberlei/assert/lib/Assert/Assert.php | 99 + .../beberlei/assert/lib/Assert/Assertion.php | 2607 +++++++++++++++++ .../assert/lib/Assert/AssertionChain.php | 230 ++ .../lib/Assert/AssertionFailedException.php | 24 + .../lib/Assert/InvalidArgumentException.php | 65 + .../assert/lib/Assert/LazyAssertion.php | 216 ++ .../lib/Assert/LazyAssertionException.php | 52 + .../beberlei/assert/lib/Assert/functions.php | 80 + infection.json.dist | 2 +- phpunit.xml.dist | 6 + src/Box.php | 14 +- src/Composer/ComposerOrchestrator.php | 23 +- src/Configuration.php | 12 +- src/Console/Command/Build.php | 2 +- src/Console/Command/Compile.php | 6 +- src/Console/Command/Configurable.php | 3 + src/Console/ConfigurationHelper.php | 18 - src/Json/Json.php | 28 +- src/Json/JsonValidationException.php | 49 +- src/MapFile.php | 2 +- src/PhpSettingsHandler.php | 2 +- src/RequirementChecker/RequirementsDumper.php | 11 +- src/Test/FileSystemTestCase.php | 23 + src/functions.php | 6 +- tests/Compactor/PhpScoperTest.php | 10 + tests/Composer/ComposerOrchestratorTest.php | 423 +++ tests/ConfigurationFileNoConfigTest.php | 22 +- tests/ConfigurationFileTest.php | 50 +- tests/ConfigurationTest.php | 39 +- tests/ConfigurationTestCase.php | 25 - tests/Console/Command/CompileTest.php | 482 +++ tests/Console/Command/ConfigurableTest.php | 163 +- tests/Console/Command/InfoTest.php | 9 +- tests/FunctionsTest.php | 112 + tests/Json/JsonTest.php | 306 ++ tests/Json/JsonValidationExceptionTest.php | 80 + .../RequirementsDumperTest.php | 140 + .../Exception/NoConfigurationFoundTest.php | 49 + 48 files changed, 5576 insertions(+), 200 deletions(-) create mode 100644 fixtures/PhpScoper/FakeScoper.php create mode 100644 fixtures/composer-dump/dir000/composer.json create mode 100644 fixtures/composer-dump/dir001/composer.json create mode 100644 fixtures/composer-dump/dir001/composer.lock create mode 100644 fixtures/composer-dump/dir002/composer.json create mode 100644 fixtures/composer-dump/dir002/composer.lock create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/LICENSE create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/composer.json create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/Assert.php create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/Assertion.php create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/AssertionChain.php create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/AssertionFailedException.php create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/InvalidArgumentException.php create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/LazyAssertion.php create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/LazyAssertionException.php create mode 100644 fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/functions.php create mode 100644 tests/Composer/ComposerOrchestratorTest.php create mode 100644 tests/FunctionsTest.php create mode 100644 tests/Json/JsonTest.php create mode 100644 tests/Json/JsonValidationExceptionTest.php create mode 100644 tests/RequirementChecker/RequirementsDumperTest.php create mode 100644 tests/Throwable/Exception/NoConfigurationFoundTest.php diff --git a/.gitignore b/.gitignore index 30b86ae17..592fd51e2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ !/bin/dump-requirements-checker.php /dist/ /fixtures/default_stub.php +/fixtures/composer-dump/dir001/vendor/ /fixtures/build/dir010/*.phar /fixtures/check-requirements/*/actual-output /fixtures/check-requirements/*/*.phar diff --git a/Makefile b/Makefile index 3a42b0a16..8b1da16ca 100644 --- a/Makefile +++ b/Makefile @@ -52,7 +52,8 @@ tu: tu_requirement_checker tu_box .PHONY: tu_box tu_box: ## Run the unit tests -tu_box: bin/phpunit fixtures/default_stub.php .requirement-checker +TU_BOX_DEPS = bin/phpunit fixtures/default_stub.php .requirement-checker fixtures/composer-dump/dir001/vendor +tu_box: $(TU_BOX_DEPS) $(PHPNOGC) bin/phpunit .PHONY: tu_requirement_checker @@ -69,7 +70,7 @@ tc: bin/phpunit .PHONY: tm tm: ## Run Infection -tm: bin/phpunit fixtures/default_stub.php tu_requirement_checker .requirement-checker +tm: $(TU_BOX_DEPS) $(PHPNOGC) bin/infection .PHONY: e2e @@ -164,6 +165,14 @@ vendor-bin/php-cs-fixer/vendor/bin/php-cs-fixer: vendor/bamarni composer bin php-cs-fixer install touch $@ +fixtures/composer-dump/dir001/composer.lock: fixtures/composer-dump/dir001/composer.json + composer install --working-dir fixtures/composer-dump/dir001 + touch $@ + +fixtures/composer-dump/dir001/vendor: fixtures/composer-dump/dir001/composer.lock + composer install --working-dir fixtures/composer-dump/dir001 + touch $@ + .PHONY: fixtures/default_stub.php fixtures/default_stub.php: bin/generate_default_stub diff --git a/fixtures/PhpScoper/FakeScoper.php b/fixtures/PhpScoper/FakeScoper.php new file mode 100644 index 000000000..79287bcae --- /dev/null +++ b/fixtures/PhpScoper/FakeScoper.php @@ -0,0 +1,46 @@ + + * Théo Fidry + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace KevinGH\Box\PhpScoper; + +use KevinGH\Box\NotCallable; + +final class FakeScoper implements Scoper +{ + use NotCallable; + + /** + * {@inheritdoc} + */ + public function scope(string $filePath, string $contents): string + { + $this->__call(__METHOD__, func_get_args()); + } + + /** + * {@inheritdoc} + */ + public function getWhitelist(): array + { + $this->__call(__METHOD__, func_get_args()); + } + + /** + * {@inheritdoc} + */ + public function getPrefix(): string + { + $this->__call(__METHOD__, func_get_args()); + } +} diff --git a/fixtures/composer-dump/dir000/composer.json b/fixtures/composer-dump/dir000/composer.json new file mode 100644 index 000000000..55e3270ba --- /dev/null +++ b/fixtures/composer-dump/dir000/composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "beberlei/assert": "^2.8" + } +} diff --git a/fixtures/composer-dump/dir001/composer.json b/fixtures/composer-dump/dir001/composer.json new file mode 100644 index 000000000..55e3270ba --- /dev/null +++ b/fixtures/composer-dump/dir001/composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "beberlei/assert": "^2.8" + } +} diff --git a/fixtures/composer-dump/dir001/composer.lock b/fixtures/composer-dump/dir001/composer.lock new file mode 100644 index 000000000..06db72267 --- /dev/null +++ b/fixtures/composer-dump/dir001/composer.lock @@ -0,0 +1,73 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "1d99bd9d9e845a4ad2d9015aaef5220f", + "packages": [ + { + "name": "beberlei/assert", + "version": "v2.9.5", + "source": { + "type": "git", + "url": "https://github.com/beberlei/assert.git", + "reference": "c07fe163d6a3b3e4b1275981ec004397954afa89" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/beberlei/assert/zipball/c07fe163d6a3b3e4b1275981ec004397954afa89", + "reference": "c07fe163d6a3b3e4b1275981ec004397954afa89", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=5.3" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.1.1", + "phpunit/phpunit": "^4.8.35|^5.7" + }, + "type": "library", + "autoload": { + "psr-4": { + "Assert\\": "lib/Assert" + }, + "files": [ + "lib/Assert/functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-2-Clause" + ], + "authors": [ + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de", + "role": "Lead Developer" + }, + { + "name": "Richard Quadling", + "email": "rquadling@gmail.com", + "role": "Collaborator" + } + ], + "description": "Thin assertion library for input validation in business models.", + "keywords": [ + "assert", + "assertion", + "validation" + ], + "time": "2018-04-16T11:18:27+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [] +} diff --git a/fixtures/composer-dump/dir002/composer.json b/fixtures/composer-dump/dir002/composer.json new file mode 100644 index 000000000..55e3270ba --- /dev/null +++ b/fixtures/composer-dump/dir002/composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "beberlei/assert": "^2.8" + } +} diff --git a/fixtures/composer-dump/dir002/composer.lock b/fixtures/composer-dump/dir002/composer.lock new file mode 100644 index 000000000..06db72267 --- /dev/null +++ b/fixtures/composer-dump/dir002/composer.lock @@ -0,0 +1,73 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "1d99bd9d9e845a4ad2d9015aaef5220f", + "packages": [ + { + "name": "beberlei/assert", + "version": "v2.9.5", + "source": { + "type": "git", + "url": "https://github.com/beberlei/assert.git", + "reference": "c07fe163d6a3b3e4b1275981ec004397954afa89" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/beberlei/assert/zipball/c07fe163d6a3b3e4b1275981ec004397954afa89", + "reference": "c07fe163d6a3b3e4b1275981ec004397954afa89", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=5.3" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.1.1", + "phpunit/phpunit": "^4.8.35|^5.7" + }, + "type": "library", + "autoload": { + "psr-4": { + "Assert\\": "lib/Assert" + }, + "files": [ + "lib/Assert/functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-2-Clause" + ], + "authors": [ + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de", + "role": "Lead Developer" + }, + { + "name": "Richard Quadling", + "email": "rquadling@gmail.com", + "role": "Collaborator" + } + ], + "description": "Thin assertion library for input validation in business models.", + "keywords": [ + "assert", + "assertion", + "validation" + ], + "time": "2018-04-16T11:18:27+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [] +} diff --git a/fixtures/composer-dump/dir002/vendor/beberlei/assert/LICENSE b/fixtures/composer-dump/dir002/vendor/beberlei/assert/LICENSE new file mode 100644 index 000000000..43672e7e6 --- /dev/null +++ b/fixtures/composer-dump/dir002/vendor/beberlei/assert/LICENSE @@ -0,0 +1,11 @@ +Copyright (c) 2011-2013, Benjamin Eberlei +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +- Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. diff --git a/fixtures/composer-dump/dir002/vendor/beberlei/assert/composer.json b/fixtures/composer-dump/dir002/vendor/beberlei/assert/composer.json new file mode 100644 index 000000000..3345cb273 --- /dev/null +++ b/fixtures/composer-dump/dir002/vendor/beberlei/assert/composer.json @@ -0,0 +1,54 @@ +{ + "name": "beberlei/assert", + "description": "Thin assertion library for input validation in business models.", + "authors": [ + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de", + "role": "Lead Developer" + }, + { + "name": "Richard Quadling", + "email": "rquadling@gmail.com", + "role": "Collaborator" + } + ], + "license": "BSD-2-Clause", + "keywords": [ + "assert", + "assertion", + "validation" + ], + "config": { + "sort-packages": true + }, + "require": { + "php": ">=5.3", + "ext-mbstring": "*" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.1.1", + "phpunit/phpunit": "^4.8.35|^5.7" + }, + "autoload": { + "psr-4": { + "Assert\\": "lib/Assert" + }, + "files": [ + "lib/Assert/functions.php" + ] + }, + "autoload-dev": { + "psr-4": { + "Assert\\Tests\\": "tests/Assert/Tests" + }, + "files": [ + "tests/Assert/Tests/Fixtures/functions.php" + ] + }, + "scripts": { + "assert:generate-docs": "php bin/generate_method_docs.php", + "assert:cs-lint": "php-cs-fixer fix --diff -vvv --dry-run", + "assert:cs-fix": "php-cs-fixer fix . -vvv || true" + } +} diff --git a/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/Assert.php b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/Assert.php new file mode 100644 index 000000000..5b1133d36 --- /dev/null +++ b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/Assert.php @@ -0,0 +1,99 @@ +notEmpty()->integer(); + * Assert::that($value)->nullOr()->string()->startsWith("Foo"); + * + * The assertion chain can be stateful, that means be careful when you reuse + * it. You should never pass around the chain. + * + * @param mixed $value + * @param string $defaultMessage + * @param string $defaultPropertyPath + * + * @return \Assert\AssertionChain + */ + public static function that($value, $defaultMessage = null, $defaultPropertyPath = null) + { + $assertionChain = new AssertionChain($value, $defaultMessage, $defaultPropertyPath); + + return $assertionChain + ->setAssertionClassName(static::$assertionClass) + ; + } + + /** + * Start validation on a set of values, returns {@link AssertionChain}. + * + * @param mixed $values + * @param string $defaultMessage + * @param string $defaultPropertyPath + * + * @return \Assert\AssertionChain + */ + public static function thatAll($values, $defaultMessage = null, $defaultPropertyPath = null) + { + return static::that($values, $defaultMessage, $defaultPropertyPath)->all(); + } + + /** + * Start validation and allow NULL, returns {@link AssertionChain}. + * + * @param mixed $value + * @param string $defaultMessage + * @param string $defaultPropertyPath + * + * @return \Assert\AssertionChain + */ + public static function thatNullOr($value, $defaultMessage = null, $defaultPropertyPath = null) + { + return static::that($value, $defaultMessage, $defaultPropertyPath)->nullOr(); + } + + /** + * Create a lazy assertion object. + * + * @return \Assert\LazyAssertion + */ + public static function lazy() + { + $lazyAssertion = new LazyAssertion(); + + return $lazyAssertion + ->setAssertClass(\get_called_class()) + ->setExceptionClass(static::$lazyAssertionExceptionClass) + ; + } +} diff --git a/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/Assertion.php b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/Assertion.php new file mode 100644 index 000000000..9eb35ef4f --- /dev/null +++ b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/Assertion.php @@ -0,0 +1,2607 @@ + + * + * @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. + * @method static bool allBoolean(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is php boolean for all values. + * @method static bool allChoice(mixed $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices for all values. + * @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 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 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. + * @method static bool allExtensionVersion(string $extension, string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed for all values. + * @method static bool allFalse(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False for all values. + * @method static bool allFile(string $value, string|callable $message = null, string $propertyPath = null) Assert that a file exists for all values. + * @method static bool allFloat(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php float for all values. + * @method static bool allGreaterOrEqualThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit for all values. + * @method static bool allGreaterThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit for all values. + * @method static bool allImplementsInterface(mixed $class, string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface for all values. + * @method static bool allInArray(mixed $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice() for all values. + * @method static bool allInteger(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer for all values. + * @method static bool allIntegerish(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish for all values. + * @method static bool allInterfaceExists(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the interface exists for all values. + * @method static bool allIp(string $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address for all values. + * @method static bool allIpv4(string $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address for all values. + * @method static bool allIpv6(string $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address for all values. + * @method static bool allIsArray(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array for all values. + * @method static bool allIsArrayAccessible(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object for all values. + * @method static bool allIsCallable(mixed $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable for all values. + * @method static bool allIsInstanceOf(mixed $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name for all values. + * @method static bool allIsJsonString(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string for all values. + * @method static bool allIsObject(mixed $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object for all values. + * @method static bool allIsResource(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a resource for all values. + * @method static bool allIsTraversable(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object for all values. + * @method static bool allKeyExists(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array for all values. + * @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 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. + * @method static bool allMethodExists(string $value, mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object for all values. + * @method static bool allMin(mixed $value, mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit for all values. + * @method static bool allMinLength(mixed $value, int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long for all values. + * @method static bool allNoContent(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is empty for all values. + * @method static bool allNotBlank(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is not blank for all values. + * @method static bool allNotEmpty(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is not empty for all values. + * @method static bool allNotEmptyKey(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty for all values. + * @method static bool allNotEq(mixed $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using == ) for all values. + * @method static bool allNotInArray(mixed $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices for all values. + * @method static bool allNotIsInstanceOf(mixed $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name for all values. + * @method static bool allNotNull(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is not null for all values. + * @method static bool allNotSame(mixed $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using === ) for all values. + * @method static bool allNull(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is null for all values. + * @method static bool allNumeric(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is numeric for all values. + * @method static bool allObjectOrClass(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists for all values. + * @method static bool allPhpVersion(string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version for all values. + * @method static bool allPropertiesExist(mixed $value, array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist for all values. + * @method static bool allPropertyExists(mixed $value, string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists for all values. + * @method static bool allRange(mixed $value, mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers for all values. + * @method static bool allReadable(string $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something readable for all values. + * @method static bool allRegex(mixed $value, string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex for all values. + * @method static bool allSame(mixed $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===) for all values. + * @method static bool allSatisfy(mixed $value, callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback for all values. + * @method static bool allScalar(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar for all values. + * @method static bool allStartsWith(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars for all values. + * @method static bool allString(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a string for all values. + * @method static bool allSubclassOf(mixed $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name for all values. + * @method static bool allTrue(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True for all values. + * @method static bool allUrl(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an URL for all values. + * @method static bool allUuid(string $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID for all values. + * @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. + * @method static bool nullOrBoolean(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is php boolean or that the value is null. + * @method static bool nullOrChoice(mixed $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices or that the value is null. + * @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 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 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. + * @method static bool nullOrExtensionVersion(string $extension, string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed or that the value is null. + * @method static bool nullOrFalse(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False or that the value is null. + * @method static bool nullOrFile(string $value, string|callable $message = null, string $propertyPath = null) Assert that a file exists or that the value is null. + * @method static bool nullOrFloat(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php float or that the value is null. + * @method static bool nullOrGreaterOrEqualThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit or that the value is null. + * @method static bool nullOrGreaterThan(mixed $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit or that the value is null. + * @method static bool nullOrImplementsInterface(mixed $class, string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface or that the value is null. + * @method static bool nullOrInArray(mixed $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice() or that the value is null. + * @method static bool nullOrInteger(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer or that the value is null. + * @method static bool nullOrIntegerish(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish or that the value is null. + * @method static bool nullOrInterfaceExists(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the interface exists or that the value is null. + * @method static bool nullOrIp(string $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address or that the value is null. + * @method static bool nullOrIpv4(string $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address or that the value is null. + * @method static bool nullOrIpv6(string $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address or that the value is null. + * @method static bool nullOrIsArray(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or that the value is null. + * @method static bool nullOrIsArrayAccessible(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object or that the value is null. + * @method static bool nullOrIsCallable(mixed $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable or that the value is null. + * @method static bool nullOrIsInstanceOf(mixed $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name or that the value is null. + * @method static bool nullOrIsJsonString(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string or that the value is null. + * @method static bool nullOrIsObject(mixed $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object or that the value is null. + * @method static bool nullOrIsResource(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a resource or that the value is null. + * @method static bool nullOrIsTraversable(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object or that the value is null. + * @method static bool nullOrKeyExists(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array or that the value is null. + * @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 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. + * @method static bool nullOrMethodExists(string $value, mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object or that the value is null. + * @method static bool nullOrMin(mixed $value, mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit or that the value is null. + * @method static bool nullOrMinLength(mixed $value, int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long or that the value is null. + * @method static bool nullOrNoContent(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is empty or that the value is null. + * @method static bool nullOrNotBlank(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is not blank or that the value is null. + * @method static bool nullOrNotEmpty(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is not empty or that the value is null. + * @method static bool nullOrNotEmptyKey(mixed $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty or that the value is null. + * @method static bool nullOrNotEq(mixed $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using == ) or that the value is null. + * @method static bool nullOrNotInArray(mixed $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices or that the value is null. + * @method static bool nullOrNotIsInstanceOf(mixed $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name or that the value is null. + * @method static bool nullOrNotNull(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is not null or that the value is null. + * @method static bool nullOrNotSame(mixed $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using === ) or that the value is null. + * @method static bool nullOrNull(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is null or that the value is null. + * @method static bool nullOrNumeric(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is numeric or that the value is null. + * @method static bool nullOrObjectOrClass(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists or that the value is null. + * @method static bool nullOrPhpVersion(string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version or that the value is null. + * @method static bool nullOrPropertiesExist(mixed $value, array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist or that the value is null. + * @method static bool nullOrPropertyExists(mixed $value, string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists or that the value is null. + * @method static bool nullOrRange(mixed $value, mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers or that the value is null. + * @method static bool nullOrReadable(string $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something readable or that the value is null. + * @method static bool nullOrRegex(mixed $value, string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex or that the value is null. + * @method static bool nullOrSame(mixed $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===) or that the value is null. + * @method static bool nullOrSatisfy(mixed $value, callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback or that the value is null. + * @method static bool nullOrScalar(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar or that the value is null. + * @method static bool nullOrStartsWith(mixed $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars or that the value is null. + * @method static bool nullOrString(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is a string or that the value is null. + * @method static bool nullOrSubclassOf(mixed $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name or that the value is null. + * @method static bool nullOrTrue(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True or that the value is null. + * @method static bool nullOrUrl(mixed $value, string|callable $message = null, string $propertyPath = null) Assert that value is an URL or that the value is null. + * @method static bool nullOrUuid(string $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID or that the value is null. + * @method static bool nullOrVersion(string $version1, string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions or that the value is null. + * @method static bool nullOrWriteable(string $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable or that the value is null. + */ +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; + + /** + * Exception to throw when an assertion failed. + * + * @var string + */ + protected static $exceptionClass = 'Assert\InvalidArgumentException'; + + /** + * 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 + */ + protected static function createException($value, $message, $code, $propertyPath = null, array $constraints = array()) + { + $exceptionClass = static::$exceptionClass; + + return new $exceptionClass($message, $code, $propertyPath, $value, $constraints); + } + + /** + * 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 + */ + 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; + } + + /** + * 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, static::INVALID_SAME, $propertyPath, array('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, static::INVALID_NOT_EQ, $propertyPath, array('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, static::INVALID_NOT_SAME, $propertyPath, array('expected' => $value2)); + } + + return true; + } + + /** + * 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 + */ + 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; + } + + /** + * Assert that value is a php integer. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * Assert that value is a php float. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * 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 + */ + 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; + } + + /** + * 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 + */ + 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; + } + + /** + * Assert that value is php boolean. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * Assert that value is a PHP scalar. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * 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, static::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, static::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 (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; + } + + /** + * 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 (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; + } + + /** + * 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, static::INVALID_STRING, $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, static::INVALID_REGEX, $propertyPath, array('pattern' => $pattern)); + } + + return true; + } + + /** + * 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 + */ + 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; + } + + /** + * 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 = array('min_length' => $minLength, 'encoding' => $encoding); + throw static::createException($value, $message, static::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 = array('max_length' => $maxLength, 'encoding' => $encoding); + throw static::createException($value, $message, static::INVALID_MAX_LENGTH, $propertyPath, $constraints); + } + + 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 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 (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; + } + + /** + * 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 = array('needle' => $needle, 'encoding' => $encoding); + throw static::createException($string, $message, static::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 (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; + } + + /** + * 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 + */ + 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; + } + + /** + * Assert that value is in array of choices. + * + * This is an alias of {@see choice()}. + * + * @param mixed $value + * @param array $choices + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + */ + public static function inArray($value, array $choices, $message = null, $propertyPath = null) + { + return static::choice($value, $choices, $message, $propertyPath); + } + + /** + * 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, static::INVALID_NUMERIC, $propertyPath); + } + + return true; + } + + /** + * Assert that value is a resource. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * 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, static::INVALID_ARRAY, $propertyPath); + } + + 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, static::INVALID_TRAVERSABLE, $propertyPath); + } + + 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, static::INVALID_ARRAY_ACCESSIBLE, $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, static::INVALID_KEY_EXISTS, $propertyPath, array('key' => $key)); + } + + return true; + } + + /** + * Assert that key does not exist in an array. + * + * @param mixed $value + * @param string|int $key + * @param string|callable|null $message + * @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, static::INVALID_KEY_NOT_EXISTS, $propertyPath, array('key' => $key)); + } + + 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, static::INVALID_KEY_ISSET, $propertyPath, array('key' => $key)); + } + + return true; + } + + /** + * Assert that key exists in an array/array-accessible object and its value is not empty. + * + * @param mixed $value + * @param string|int $key + * @param string|callable|null $message + * @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 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, static::INVALID_NOT_BLANK, $propertyPath); + } + + return true; + } + + /** + * Assert that value is instance of given class-name. + * + * @param mixed $value + * @param string $className + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @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, static::INVALID_INSTANCE_OF, $propertyPath, array('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, static::INVALID_NOT_INSTANCE_OF, $propertyPath, array('class' => $className)); + } + + return 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 + */ + 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; + } + + /** + * 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 + */ + 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; + } + + /** + * 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, static::INVALID_MIN, $propertyPath, array('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, static::INVALID_MAX, $propertyPath, array('max' => $maxValue)); + } + + return true; + } + + /** + * Assert that a file exists. + * + * @param string $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * Assert that a directory exists. + * + * @param string $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * Assert that the value is something readable. + * + * @param string $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * 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 + */ + 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; + } + + /** + * 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 + */ + 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; + } + + /** + * 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, static::INTERFACE_NOT_IMPLEMENTED, $propertyPath, array('interface' => $interfaceName)); + } + + return true; + } + + /** + * Assert that the given string is a valid json string. + * + * NOTICE: + * Since this does a json_decode to determine its validity + * you probably should consider, when using the variable + * content afterwards, just to decode and check for yourself instead + * of using this assertion. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @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, static::INVALID_JSON_STRING, $propertyPath); + } + + return true; + } + + /** + * Assert that the given string is a valid UUID. + * + * Uses code from {@link https://github.com/ramsey/uuid} that is MIT licensed. + * + * @param string $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * 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, static::INVALID_E164, $propertyPath); + } + + 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 (%d given).'), + static::stringify($count), + static::stringify(\count($countable)) + ); + + throw static::createException($countable, $message, static::INVALID_COUNT, $propertyPath, array('count' => $count)); + } + + return true; + } + + /** + * static call handler to implement: + * - "null or assertion" delegation + * - "all" delegation. + * + * @param string $method + * @param array $args + * + * @return bool|mixed + */ + 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.'); + } + + /** + * 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; + } + + /** + * 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 + */ + 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; + } + + /** + * Determines that the provided value is an object. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + */ + 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; + } + + /** + * 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, static::INVALID_LESS, $propertyPath); + } + + return true; + } + + /** + * 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 + */ + 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; + } + + /** + * 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, static::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, static::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, static::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, static::INVALID_BETWEEN_EXCLUSIVE, $propertyPath); + } + + return true; + } + + /** + * Assert that extension is loaded. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * 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, static::INVALID_DATE, $propertyPath, array('format' => $format)); + } + + return true; + } + + /** + * 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 + */ + public static function objectOrClass($value, $message = null, $propertyPath = null) + { + if (!\is_object($value)) { + static::classExists($value, $message, $propertyPath); + } + + return true; + } + + /** + * Assert that the value is an object or class, and that the property exists. + * + * @param mixed $value + * @param string $property + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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; + } + + /** + * 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 + */ + 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; + } + + /** + * 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 + */ + 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; + } + + /** + * Assert on PHP version. + * + * @param string $operator + * @param mixed $version + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + public static function phpVersion($operator, $version, $message = null, $propertyPath = null) + { + static::defined('PHP_VERSION'); + + return static::version(PHP_VERSION, $operator, $version, $message, $propertyPath); + } + + /** + * Assert that extension is loaded and a specific version is installed. + * + * @param string $extension + * @param string $operator + * @param mixed $version + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + * + * @throws \Assert\AssertionFailedException + */ + 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); + } + + /** + * Determines that the provided value is callable. + * + * @param mixed $value + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + */ + public static function isCallable($value, $message = null, $propertyPath = null) + { + if (!\is_callable($value)) { + $message = \sprintf( + static::generateMessage($message ?: 'Provided "%s" is not a callable.'), + static::stringify($value) + ); + + throw static::createException($value, $message, static::INVALID_CALLABLE, $propertyPath); + } + + return true; + } + + /** + * Assert that the provided value is valid according to a callback. + * + * If the callback returns `false` the assertion will fail. + * + * @param mixed $value + * @param callable $callback + * @param string|callable|null $message + * @param string|null $propertyPath + * + * @return bool + */ + public static function satisfy($value, $callback, $message = null, $propertyPath = null) + { + static::isCallable($callback); + + if (false === \call_user_func($callback, $value)) { + $message = \sprintf( + static::generateMessage($message ?: 'Provided "%s" is invalid according to custom rule.'), + static::stringify($value) + ); + + throw static::createException($value, $message, static::INVALID_SATISFY, $propertyPath); + } + + return true; + } + + /** + * Assert that value is an IPv4 or IPv6 address + * (using input_filter/FILTER_VALIDATE_IP). + * + * @param string $value + * @param 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 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 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; + } + + /** + * Make a string version of a value. + * + * @param mixed $value + * + * @return string + */ + protected static function stringify($value) + { + $result = \gettype($value); + + if (\is_bool($value)) { + $result = $value ? '' : ''; + } elseif (\is_scalar($value)) { + $val = (string) $value; + + if (\strlen($val) > 100) { + $val = \substr($val, 0, 97) . '...'; + } + + $result = $val; + } elseif (\is_array($value)) { + $result = ''; + } elseif (\is_object($value)) { + $result = \get_class($value); + } elseif (\is_resource($value)) { + $result = \get_resource_type($value); + } elseif (null === $value) { + $result = ''; + } + + return $result; + } + + /** + * 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. + * + * @param string|callable|null $message + * + * @return string|null + */ + protected static function generateMessage($message = null) + { + if (\is_callable($message)) { + $traces = \debug_backtrace(0); + + $parameters = array(); + + $reflection = new \ReflectionClass($traces[1]['class']); + $method = $reflection->getMethod($traces[1]['function']); + foreach ($method->getParameters() as $index => $parameter) { + if ('message' !== $parameter->getName()) { + $parameters[$parameter->getName()] = \array_key_exists($index, $traces[1]['args']) + ? $traces[1]['args'][$index] + : $parameter->getDefaultValue(); + } + } + + $parameters['::assertion'] = \sprintf('%s%s%s', $traces[1]['class'], $traces[1]['type'], $traces[1]['function']); + + $message = \call_user_func_array($message, array($parameters)); + } + + return \is_null($message) ? null : (string) $message; + } +} diff --git a/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/AssertionChain.php b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/AssertionChain.php new file mode 100644 index 000000000..ee7282501 --- /dev/null +++ b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/AssertionChain.php @@ -0,0 +1,230 @@ + + * + * @method AssertionChain alnum(string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric. + * @method AssertionChain base64(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined. + * @method AssertionChain between(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. + * @method AssertionChain betweenExclusive(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. + * @method AssertionChain betweenLength(int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min,max lengths. + * @method AssertionChain boolean(string|callable $message = null, string $propertyPath = null) Assert that value is php boolean. + * @method AssertionChain choice(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. + * @method AssertionChain choicesNotEmpty(array $choices, string|callable $message = null, string $propertyPath = null) Determines if the values array has every choice as key and that this choice has content. + * @method AssertionChain classExists(string|callable $message = null, string $propertyPath = null) Assert that the class exists. + * @method AssertionChain contains(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars. + * @method AssertionChain count(int $count, string $message = null, string $propertyPath = null) Assert that the count of countable is equal to count. + * @method AssertionChain date(string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format. + * @method AssertionChain defined(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined. + * @method AssertionChain digit(string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit. + * @method AssertionChain directory(string|callable $message = null, string $propertyPath = null) Assert that a directory exists. + * @method AssertionChain e164(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number. + * @method AssertionChain email(string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL). + * @method AssertionChain endsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars. + * @method AssertionChain eq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using == ). + * @method AssertionChain extensionLoaded(string|callable $message = null, string $propertyPath = null) Assert that extension is loaded. + * @method AssertionChain extensionVersion(string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed. + * @method AssertionChain false(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False. + * @method AssertionChain file(string|callable $message = null, string $propertyPath = null) Assert that a file exists. + * @method AssertionChain float(string|callable $message = null, string $propertyPath = null) Assert that value is a php float. + * @method AssertionChain greaterOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit. + * @method AssertionChain greaterThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit. + * @method AssertionChain implementsInterface(string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface. + * @method AssertionChain inArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice(). + * @method AssertionChain integer(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer. + * @method AssertionChain integerish(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish. + * @method AssertionChain interfaceExists(string|callable $message = null, string $propertyPath = null) Assert that the interface exists. + * @method AssertionChain ip(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address. + * @method AssertionChain ipv4(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address. + * @method AssertionChain ipv6(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address. + * @method AssertionChain isArray(string|callable $message = null, string $propertyPath = null) Assert that value is an array. + * @method AssertionChain isArrayAccessible(string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object. + * @method AssertionChain isCallable(string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable. + * @method AssertionChain isInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name. + * @method AssertionChain isJsonString(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string. + * @method AssertionChain isObject(string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object. + * @method AssertionChain isResource(string|callable $message = null, string $propertyPath = null) Assert that value is a resource. + * @method AssertionChain isTraversable(string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object. + * @method AssertionChain keyExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array. + * @method AssertionChain keyIsset(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset(). + * @method AssertionChain keyNotExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array. + * @method AssertionChain length(int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length. + * @method AssertionChain lessOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit. + * @method AssertionChain lessThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit. + * @method AssertionChain max(mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit. + * @method AssertionChain maxLength(int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars. + * @method AssertionChain methodExists(mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object. + * @method AssertionChain min(mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit. + * @method AssertionChain minLength(int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long. + * @method AssertionChain noContent(string|callable $message = null, string $propertyPath = null) Assert that value is empty. + * @method AssertionChain notBlank(string|callable $message = null, string $propertyPath = null) Assert that value is not blank. + * @method AssertionChain notEmpty(string|callable $message = null, string $propertyPath = null) Assert that value is not empty. + * @method AssertionChain notEmptyKey(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty. + * @method AssertionChain notEq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using == ). + * @method AssertionChain notInArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices. + * @method AssertionChain notIsInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name. + * @method AssertionChain notNull(string|callable $message = null, string $propertyPath = null) Assert that value is not null. + * @method AssertionChain notSame(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using === ). + * @method AssertionChain null(string|callable $message = null, string $propertyPath = null) Assert that value is null. + * @method AssertionChain numeric(string|callable $message = null, string $propertyPath = null) Assert that value is numeric. + * @method AssertionChain objectOrClass(string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists. + * @method AssertionChain phpVersion(mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version. + * @method AssertionChain propertiesExist(array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist. + * @method AssertionChain propertyExists(string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists. + * @method AssertionChain range(mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers. + * @method AssertionChain readable(string|callable $message = null, string $propertyPath = null) Assert that the value is something readable. + * @method AssertionChain regex(string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex. + * @method AssertionChain same(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===). + * @method AssertionChain satisfy(callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback. + * @method AssertionChain scalar(string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar. + * @method AssertionChain startsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars. + * @method AssertionChain string(string|callable $message = null, string $propertyPath = null) Assert that value is a string. + * @method AssertionChain subclassOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name. + * @method AssertionChain true(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True. + * @method AssertionChain url(string|callable $message = null, string $propertyPath = null) Assert that value is an URL. + * @method AssertionChain uuid(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID. + * @method AssertionChain version(string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions. + * @method AssertionChain writeable(string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable. + */ +class AssertionChain +{ + private $value; + private $defaultMessage; + private $defaultPropertyPath; + + /** + * Return each assertion as always valid. + * + * @var bool + */ + private $alwaysValid = false; + + /** + * Perform assertion on every element of array or traversable. + * + * @var bool + */ + private $all = false; + + /** @var string|Assertion Class to use for assertion calls */ + private $assertionClassName = 'Assert\Assertion'; + + public function __construct($value, $defaultMessage = null, $defaultPropertyPath = null) + { + $this->value = $value; + $this->defaultMessage = $defaultMessage; + $this->defaultPropertyPath = $defaultPropertyPath; + } + + /** + * Call assertion on the current value in the chain. + * + * @param string $methodName + * @param array $args + * + * @return \Assert\AssertionChain + */ + public function __call($methodName, $args) + { + if (true === $this->alwaysValid) { + return $this; + } + + if (!\method_exists($this->assertionClassName, $methodName)) { + throw new \RuntimeException("Assertion '" . $methodName . "' does not exist."); + } + + $reflClass = new ReflectionClass($this->assertionClassName); + $method = $reflClass->getMethod($methodName); + + \array_unshift($args, $this->value); + $params = $method->getParameters(); + + foreach ($params as $idx => $param) { + if (isset($args[$idx])) { + continue; + } + + if ('message' == $param->getName()) { + $args[$idx] = $this->defaultMessage; + } + + if ('propertyPath' == $param->getName()) { + $args[$idx] = $this->defaultPropertyPath; + } + } + + if ($this->all) { + $methodName = 'all' . $methodName; + } + + \call_user_func_array(array($this->assertionClassName, $methodName), $args); + + return $this; + } + + /** + * Switch chain into validation mode for an array of values. + * + * @return \Assert\AssertionChain + */ + public function all() + { + $this->all = true; + + return $this; + } + + /** + * Switch chain into mode allowing nulls, ignoring further assertions. + * + * @return \Assert\AssertionChain + */ + public function nullOr() + { + if (null === $this->value) { + $this->alwaysValid = true; + } + + return $this; + } + + /** + * @param string $className + * + * @return $this + */ + public function setAssertionClassName($className) + { + if (!\is_string($className)) { + throw new LogicException('Exception class name must be passed as a string'); + } + + if ('Assert\Assertion' !== $className && !\is_subclass_of($className, 'Assert\Assertion')) { + throw new LogicException($className . ' is not (a subclass of) Assert\Assertion'); + } + + $this->assertionClassName = $className; + + return $this; + } +} diff --git a/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/AssertionFailedException.php b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/AssertionFailedException.php new file mode 100644 index 000000000..f88a5d464 --- /dev/null +++ b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/AssertionFailedException.php @@ -0,0 +1,24 @@ +propertyPath = $propertyPath; + $this->value = $value; + $this->constraints = $constraints; + } + + /** + * User controlled way to define a sub-property causing + * the failure of a currently asserted objects. + * + * Useful to transport information about the nature of the error + * back to higher layers. + * + * @return string + */ + public function getPropertyPath() + { + return $this->propertyPath; + } + + /** + * Get the value that caused the assertion to fail. + * + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + /** + * Get the constraints that applied to the failed assertion. + * + * @return array + */ + public function getConstraints() + { + return $this->constraints; + } +} diff --git a/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/LazyAssertion.php b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/LazyAssertion.php new file mode 100644 index 000000000..33169d4e7 --- /dev/null +++ b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/LazyAssertion.php @@ -0,0 +1,216 @@ + + * + * @method LazyAssertion alnum(string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric. + * @method LazyAssertion base64(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined. + * @method LazyAssertion between(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. + * @method LazyAssertion betweenExclusive(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. + * @method LazyAssertion betweenLength(int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min,max lengths. + * @method LazyAssertion boolean(string|callable $message = null, string $propertyPath = null) Assert that value is php boolean. + * @method LazyAssertion choice(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. + * @method LazyAssertion choicesNotEmpty(array $choices, string|callable $message = null, string $propertyPath = null) Determines if the values array has every choice as key and that this choice has content. + * @method LazyAssertion classExists(string|callable $message = null, string $propertyPath = null) Assert that the class exists. + * @method LazyAssertion contains(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars. + * @method LazyAssertion count(int $count, string $message = null, string $propertyPath = null) Assert that the count of countable is equal to count. + * @method LazyAssertion date(string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format. + * @method LazyAssertion defined(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined. + * @method LazyAssertion digit(string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit. + * @method LazyAssertion directory(string|callable $message = null, string $propertyPath = null) Assert that a directory exists. + * @method LazyAssertion e164(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number. + * @method LazyAssertion email(string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL). + * @method LazyAssertion endsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars. + * @method LazyAssertion eq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using == ). + * @method LazyAssertion extensionLoaded(string|callable $message = null, string $propertyPath = null) Assert that extension is loaded. + * @method LazyAssertion extensionVersion(string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed. + * @method LazyAssertion false(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False. + * @method LazyAssertion file(string|callable $message = null, string $propertyPath = null) Assert that a file exists. + * @method LazyAssertion float(string|callable $message = null, string $propertyPath = null) Assert that value is a php float. + * @method LazyAssertion greaterOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit. + * @method LazyAssertion greaterThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit. + * @method LazyAssertion implementsInterface(string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface. + * @method LazyAssertion inArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice(). + * @method LazyAssertion integer(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer. + * @method LazyAssertion integerish(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish. + * @method LazyAssertion interfaceExists(string|callable $message = null, string $propertyPath = null) Assert that the interface exists. + * @method LazyAssertion ip(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address. + * @method LazyAssertion ipv4(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address. + * @method LazyAssertion ipv6(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address. + * @method LazyAssertion isArray(string|callable $message = null, string $propertyPath = null) Assert that value is an array. + * @method LazyAssertion isArrayAccessible(string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object. + * @method LazyAssertion isCallable(string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable. + * @method LazyAssertion isInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name. + * @method LazyAssertion isJsonString(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string. + * @method LazyAssertion isObject(string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object. + * @method LazyAssertion isResource(string|callable $message = null, string $propertyPath = null) Assert that value is a resource. + * @method LazyAssertion isTraversable(string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object. + * @method LazyAssertion keyExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array. + * @method LazyAssertion keyIsset(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset(). + * @method LazyAssertion keyNotExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array. + * @method LazyAssertion length(int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length. + * @method LazyAssertion lessOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit. + * @method LazyAssertion lessThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit. + * @method LazyAssertion max(mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit. + * @method LazyAssertion maxLength(int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars. + * @method LazyAssertion methodExists(mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object. + * @method LazyAssertion min(mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit. + * @method LazyAssertion minLength(int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long. + * @method LazyAssertion noContent(string|callable $message = null, string $propertyPath = null) Assert that value is empty. + * @method LazyAssertion notBlank(string|callable $message = null, string $propertyPath = null) Assert that value is not blank. + * @method LazyAssertion notEmpty(string|callable $message = null, string $propertyPath = null) Assert that value is not empty. + * @method LazyAssertion notEmptyKey(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty. + * @method LazyAssertion notEq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using == ). + * @method LazyAssertion notInArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices. + * @method LazyAssertion notIsInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name. + * @method LazyAssertion notNull(string|callable $message = null, string $propertyPath = null) Assert that value is not null. + * @method LazyAssertion notSame(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using === ). + * @method LazyAssertion null(string|callable $message = null, string $propertyPath = null) Assert that value is null. + * @method LazyAssertion numeric(string|callable $message = null, string $propertyPath = null) Assert that value is numeric. + * @method LazyAssertion objectOrClass(string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists. + * @method LazyAssertion phpVersion(mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version. + * @method LazyAssertion propertiesExist(array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist. + * @method LazyAssertion propertyExists(string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists. + * @method LazyAssertion range(mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers. + * @method LazyAssertion readable(string|callable $message = null, string $propertyPath = null) Assert that the value is something readable. + * @method LazyAssertion regex(string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex. + * @method LazyAssertion same(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===). + * @method LazyAssertion satisfy(callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback. + * @method LazyAssertion scalar(string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar. + * @method LazyAssertion startsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars. + * @method LazyAssertion string(string|callable $message = null, string $propertyPath = null) Assert that value is a string. + * @method LazyAssertion subclassOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name. + * @method LazyAssertion true(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True. + * @method LazyAssertion url(string|callable $message = null, string $propertyPath = null) Assert that value is an URL. + * @method LazyAssertion uuid(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID. + * @method LazyAssertion version(string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions. + * @method LazyAssertion writeable(string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable. + * @method LazyAssertion all() Switch chain into validation mode for an array of values. + * @method LazyAssertion nullOr() Switch chain into mode allowing nulls, ignoring further assertions. + */ +class LazyAssertion +{ + private $currentChainFailed = false; + private $alwaysTryAll = false; + private $thisChainTryAll = false; + private $currentChain; + private $errors = array(); + + /** @var string The class to use as AssertionChain factory */ + private $assertClass = 'Assert\Assert'; + + /** @var string|LazyAssertionException The class to use for exceptions */ + private $exceptionClass = 'Assert\LazyAssertionException'; + + public function that($value, $propertyPath, $defaultMessage = null) + { + $this->currentChainFailed = false; + $this->thisChainTryAll = false; + $assertClass = $this->assertClass; + $this->currentChain = $assertClass::that($value, $defaultMessage, $propertyPath); + + return $this; + } + + public function tryAll() + { + if (!$this->currentChain) { + $this->alwaysTryAll = true; + } + + $this->thisChainTryAll = true; + + return $this; + } + + public function __call($method, $args) + { + if (false === $this->alwaysTryAll + && false === $this->thisChainTryAll + && true === $this->currentChainFailed + ) { + return $this; + } + + try { + \call_user_func_array(array($this->currentChain, $method), $args); + } catch (AssertionFailedException $e) { + $this->errors[] = $e; + $this->currentChainFailed = true; + } + + return $this; + } + + /** + * @throws \Assert\LazyAssertionException + * + * @return bool + */ + public function verifyNow() + { + if ($this->errors) { + throw \call_user_func(array($this->exceptionClass, 'fromErrors'), $this->errors); + } + + return true; + } + + /** + * @param string $className + * + * @return $this + */ + public function setAssertClass($className) + { + if (!\is_string($className)) { + throw new LogicException('Assert class name must be passed as a string'); + } + + if ('Assert\Assert' !== $className && !\is_subclass_of($className, 'Assert\Assert')) { + throw new LogicException($className . ' is not (a subclass of) Assert\Assert'); + } + + $this->assertClass = $className; + + return $this; + } + + /** + * @param string $className + * + * @return $this + */ + public function setExceptionClass($className) + { + if (!\is_string($className)) { + throw new LogicException('Exception class name must be passed as a string'); + } + + if ('Assert\LazyAssertionException' !== $className && !\is_subclass_of($className, 'Assert\LazyAssertionException')) { + throw new LogicException($className . ' is not (a subclass of) Assert\LazyAssertionException'); + } + + $this->exceptionClass = $className; + + return $this; + } +} diff --git a/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/LazyAssertionException.php b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/LazyAssertionException.php new file mode 100644 index 000000000..2f08959a3 --- /dev/null +++ b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/LazyAssertionException.php @@ -0,0 +1,52 @@ +getPropertyPath(), $error->getMessage()); + } + + return new static($message, $errors); + } + + public function __construct($message, array $errors) + { + parent::__construct($message, 0, null, null); + + $this->errors = $errors; + } + + public function getErrorExceptions() + { + return $this->errors; + } +} diff --git a/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/functions.php b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/functions.php new file mode 100644 index 000000000..67bb6315e --- /dev/null +++ b/fixtures/composer-dump/dir002/vendor/beberlei/assert/lib/Assert/functions.php @@ -0,0 +1,80 @@ +notEmpty()->integer(); + * \Assert\that($value)->nullOr()->string()->startsWith("Foo"); + * + * The assertion chain can be stateful, that means be careful when you reuse + * it. You should never pass around the chain. + * + * @param mixed $value + * @param string $defaultMessage + * @param string $defaultPropertyPath + * + * @return \Assert\AssertionChain + */ +function that($value, $defaultMessage = null, $defaultPropertyPath = null) +{ + return Assert::that($value, $defaultMessage, $defaultPropertyPath); +} + +/** + * Start validation on a set of values, returns {@link AssertionChain}. + * + * @param mixed $values + * @param string $defaultMessage + * @param string $defaultPropertyPath + * + * @return \Assert\AssertionChain + */ +function thatAll($values, $defaultMessage = null, $defaultPropertyPath = null) +{ + return Assert::thatAll($values, $defaultMessage, $defaultPropertyPath); +} + +/** + * Start validation and allow NULL, returns {@link AssertionChain}. + * + * @param mixed $value + * @param string $defaultMessage + * @param string $defaultPropertyPath + * + * @return \Assert\AssertionChain + * + * @deprecated In favour of Assert::thatNullOr($value, $defaultMessage = null, $defaultPropertyPath = null) + */ +function thatNullOr($value, $defaultMessage = null, $defaultPropertyPath = null) +{ + return Assert::thatNullOr($value, $defaultMessage, $defaultPropertyPath); +} + +/** + * Create a lazy assertion object. + * + * @return \Assert\LazyAssertion + */ +function lazy() +{ + return Assert::lazy(); +} diff --git a/infection.json.dist b/infection.json.dist index b905c1722..792965419 100644 --- a/infection.json.dist +++ b/infection.json.dist @@ -6,7 +6,7 @@ ] }, "logs": { - "text": "dist\/infection-log.txt" + "text": "dist/infection-log.txt" }, "phpunit": { "customPath": "bin/phpunit" diff --git a/phpunit.xml.dist b/phpunit.xml.dist index eb7a1ec3f..64376d399 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -19,8 +19,14 @@ src/ + src/bootstrap.php + src/consts.php src/functions.php + src/Console/Command/Build.php + src/Console/Command/ChangeableWorkingDirectory.php + src/PhpSettingsHandler.php src/Console/Logger + src/FileSystem src/Test diff --git a/src/Box.php b/src/Box.php index 6a3e13c5f..c2ec421af 100644 --- a/src/Box.php +++ b/src/Box.php @@ -16,7 +16,6 @@ use Assert\Assertion; use BadMethodCallException; -use Closure; use Countable; use KevinGH\Box\Compactor\PhpScoper; use KevinGH\Box\Composer\ComposerOrchestrator; @@ -77,7 +76,7 @@ final class Box implements Countable private $basePath; /** - * @var Closure|MapFile + * @var MapFile */ private $mapFile; @@ -96,7 +95,7 @@ private function __construct(Phar $phar, string $file) $this->file = $file; $this->basePath = getcwd(); - $this->mapFile = function (): void { }; + $this->mapFile = new MapFile([]); $this->scoper = new NullScoper(); } @@ -179,13 +178,8 @@ public function removeComposerArtefacts(string $vendorDir): void $this->phar->startBuffering(); foreach ($composerFiles as $composerFile) { - // TODO: the file map could return the unchanged path when no mapping is found... $localComposerFile = ($this->mapFile)($composerFile); - if (null === $localComposerFile) { - $localComposerFile = $composerFile; - } - if (file_exists('phar://'.$this->phar->getPath().'/'.$localComposerFile)) { $this->phar->delete($localComposerFile); } @@ -346,10 +340,6 @@ public function addFile(string $file, string $contents = null, bool $binary = fa $relativePath = make_path_relative($file, $this->basePath); $local = ($this->mapFile)($relativePath); - if (null === $local) { - $local = $relativePath; - } - if ($binary) { $this->bufferedFiles[$local] = $contents; } else { diff --git a/src/Composer/ComposerOrchestrator.php b/src/Composer/ComposerOrchestrator.php index 3edeecad7..f483e722f 100644 --- a/src/Composer/ComposerOrchestrator.php +++ b/src/Composer/ComposerOrchestrator.php @@ -19,9 +19,11 @@ use Humbug\PhpScoper\Autoload\ScoperAutoloadGenerator; use RuntimeException; use Throwable; +use const PHP_EOL; use function KevinGH\Box\FileSystem\dump_file; use function KevinGH\Box\FileSystem\file_contents; use function preg_replace; +use function str_replace; /** * @private @@ -76,20 +78,19 @@ public static function dumpAutoload(array $whitelist, string $prefix): void */ private static function generateAutoloadStatements(array $whitelist, string $prefix, string $autoload): string { - // TODO: make prefix configurable: https://github.com/humbug/php-scoper/issues/178 - $whitelistStatements = (new ScoperAutoloadGenerator($whitelist))->dump($prefix); - - if ('' === $whitelistStatements) { + if ([] === $whitelist) { return $autoload; } + $whitelistStatements = (new ScoperAutoloadGenerator($whitelist))->dump($prefix); + $whitelistStatements = preg_replace( '/(\\$loader \= .*)|(return \\$loader;)/', '', str_replace('composerJson[0]; } - public function getComposerJsonDecodedContents(): ?array + public function getDecodedComposerJsonContents(): ?array { return $this->composerJson[1]; } @@ -392,7 +392,7 @@ public function getComposerLock(): ?string return $this->composerLock[0]; } - public function getComposerLockDecodedContents(): ?array + public function getDecodedComposerLockContents(): ?array { return $this->composerLock[1]; } @@ -481,14 +481,6 @@ public function getOutputPath(): string return $this->outputPath; } - /** - * @return string[] - */ - public function getMap(): array - { - return $this->fileMapper->getMap(); - } - public function getFileMapper(): MapFile { return $this->fileMapper; diff --git a/src/Console/Command/Build.php b/src/Console/Command/Build.php index 4970b39d4..ab3495374 100644 --- a/src/Console/Command/Build.php +++ b/src/Console/Command/Build.php @@ -17,8 +17,8 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; -use function trigger_error; use const E_USER_DEPRECATED; +use function trigger_error; /** * @deprecated diff --git a/src/Console/Command/Compile.php b/src/Console/Command/Compile.php index 75ee79e11..26340f727 100644 --- a/src/Console/Command/Compile.php +++ b/src/Console/Command/Compile.php @@ -451,8 +451,8 @@ private function registerRequirementsChecker(Configuration $config, Box $box, Bu ); $checkFiles = RequirementsDumper::dump( - $config->getComposerJsonDecodedContents() ?? [], - $config->getComposerLockDecodedContents() ?? [], + $config->getDecodedComposerJsonContents() ?? [], + $config->getDecodedComposerLockContents() ?? [], $config->getCompressionAlgorithm() ); @@ -553,7 +553,7 @@ private function checkComposerFiles(Box $box, Configuration $config, BuildLogger if ($config->excludeComposerFiles()) { $box->removeComposerArtefacts( ComposerConfiguration::retrieveVendorDir( - $config->getComposerJsonDecodedContents() ?? [] + $config->getDecodedComposerJsonContents() ?? [] ) ); } diff --git a/src/Console/Command/Configurable.php b/src/Console/Command/Configurable.php index 5ad6a59ff..efc5cbc0f 100644 --- a/src/Console/Command/Configurable.php +++ b/src/Console/Command/Configurable.php @@ -17,6 +17,7 @@ use InvalidArgumentException; use KevinGH\Box\Configuration; use KevinGH\Box\Console\ConfigurationHelper; +use KevinGH\Box\Json\JsonValidationException; use KevinGH\Box\Throwable\Exception\NoConfigurationFound; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; @@ -54,6 +55,8 @@ protected function configure(): void * @param OutputInterface $output * @param bool $allowNoFile Load the config nonetheless if not file is found when true * + * @throws JsonValidationException + * * @return Configuration */ final protected function getConfig(InputInterface $input, OutputInterface $output, bool $allowNoFile = false): Configuration diff --git a/src/Console/ConfigurationHelper.php b/src/Console/ConfigurationHelper.php index bf0a868a7..f27665554 100644 --- a/src/Console/ConfigurationHelper.php +++ b/src/Console/ConfigurationHelper.php @@ -19,7 +19,6 @@ use KevinGH\Box\Throwable\Exception\NoConfigurationFound; use stdClass; use Symfony\Component\Console\Helper\Helper; -use function KevinGH\Box\FileSystem\is_absolute_path; /** * @private @@ -65,23 +64,6 @@ public function loadFile(?string $file): Configuration $json = $this->json->decodeFile($file); - // Include imports - if (isset($json->import)) { - if (!is_absolute_path($json->import)) { - $json->import = implode( - [ - dirname($file), - $json->import, - ] - ); - } - - $json = (object) array_merge( - (array) $this->json->decodeFile($json->import), - (array) $json - ); - } - $this->json->validate( $file, $json, diff --git a/src/Json/Json.php b/src/Json/Json.php index a2d1312a4..a8f377710 100644 --- a/src/Json/Json.php +++ b/src/Json/Json.php @@ -32,6 +32,18 @@ public function __construct() $this->linter = new JsonParser(); } + /** + * @throws ParsingException + */ + public function lint(string $json): void + { + $result = $this->linter->lint($json); + + if ($result instanceof ParsingException) { + throw $result; + } + } + /** * @param string $json * @param bool $assoc @@ -45,15 +57,12 @@ public function decode(string $json, bool $assoc = false) $data = json_decode($json, $assoc); if (JSON_ERROR_NONE !== ($error = json_last_error())) { + // Swallow the UTF-8 error and relies on the lint instead otherwise if (JSON_ERROR_UTF8 === $error) { - throw JsonValidationException::createDecodeException($error); + throw new ParsingException('JSON decoding failed: Malformed UTF-8 characters, possibly incorrectly encoded'); } $this->lint($json); - - if (($result = $this->linter->lint($json)) instanceof ParsingException) { - throw $result; - } } return false === $assoc ? (object) $data : $data; // If JSON is an empty JSON json_decode returns an empty @@ -72,15 +81,6 @@ public function decodeFile(string $file, bool $assoc = false) return $this->decode($json, $assoc); } - public function lint(string $json): void - { - $result = $this->linter->lint($json); - - if ($result instanceof ParsingException) { - throw $result; - } - } - /** * Validates the decoded JSON data. * diff --git a/src/Json/JsonValidationException.php b/src/Json/JsonValidationException.php index f176a6119..a4514cdd7 100644 --- a/src/Json/JsonValidationException.php +++ b/src/Json/JsonValidationException.php @@ -15,7 +15,7 @@ namespace KevinGH\Box\Json; use Assert\Assertion; -use Exception; +use Throwable; use UnexpectedValueException; /** @@ -31,47 +31,22 @@ final class JsonValidationException extends UnexpectedValueException * * @param string[] $errors */ - public function __construct(string $message, string $file = null, $errors = [], Exception $previous = null) - { - Assertion::file($file); + public function __construct( + string $message, + string $file = null, + array $errors = [], + int $code = 0, + Throwable $previous = null + ) { + if (null !== $file) { + Assertion::file($file); + } Assertion::allString($errors); $this->validatedFile = $file; $this->errors = $errors; - parent::__construct($message, 0, $previous); - } - - /** - * Creates an exception according to a given code with a customized message. - * - * @param int $code return code of json_last_error function - * - * @return static - */ - public static function createDecodeException(int $code): self - { - switch ($code) { - case JSON_ERROR_CTRL_CHAR: - $msg = 'Control character error, possibly incorrectly encoded.'; - break; - case JSON_ERROR_DEPTH: - $msg = 'The maximum stack depth has been exceeded.'; - break; - case JSON_ERROR_STATE_MISMATCH: - $msg = 'Invalid or malformed JSON.'; - break; - case JSON_ERROR_SYNTAX: - $msg = 'Syntax error.'; - break; - case JSON_ERROR_UTF8: - $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded.'; - break; - default: - $msg = 'Unknown error'; - } - - return new self('JSON decoding failed: '.$msg); + parent::__construct($message, $code, $previous); } public function getValidatedFile(): ?string diff --git a/src/MapFile.php b/src/MapFile.php index b7ca0bdaa..7298121fc 100644 --- a/src/MapFile.php +++ b/src/MapFile.php @@ -48,7 +48,7 @@ public function __invoke(string $path): ?string } } - return null; + return $path; } public function getMap(): array diff --git a/src/PhpSettingsHandler.php b/src/PhpSettingsHandler.php index ec03729df..50dce21be 100644 --- a/src/PhpSettingsHandler.php +++ b/src/PhpSettingsHandler.php @@ -17,13 +17,13 @@ use Composer\XdebugHandler\Process; use Composer\XdebugHandler\XdebugHandler; use Psr\Log\LoggerInterface; +use const PHP_EOL; use function function_exists; use function getenv; use function ini_get; use function KevinGH\Box\FileSystem\append_to_file; use function sprintf; use function trim; -use const PHP_EOL; /** * @private diff --git a/src/RequirementChecker/RequirementsDumper.php b/src/RequirementChecker/RequirementsDumper.php index eafff675a..94c4e2291 100644 --- a/src/RequirementChecker/RequirementsDumper.php +++ b/src/RequirementChecker/RequirementsDumper.php @@ -14,6 +14,7 @@ namespace KevinGH\Box\RequirementChecker; +use Assert\Assertion; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; use function KevinGH\Box\FileSystem\file_contents; @@ -52,22 +53,24 @@ final class RequirementsDumper return __CONFIG__; PHP; - private const REQUIRMEMENT_CHECKER_PATH = __DIR__.'/../../.requirement-checker'; + private const REQUIREMENT_CHECKER_PATH = __DIR__.'/../../.requirement-checker'; /** * @return string[][] */ - public static function dump(array $composerJsonDecodedContents, array $composerLockDecodedContents, ?int $compressionAlgorithm): array + public static function dump(array $decodedComposerJsonContents, array $decodedComposerLockContents, ?int $compressionAlgorithm): array { + Assertion::directory(self::REQUIREMENT_CHECKER_PATH, 'Expected the requirement checker to have been dumped'); + $filesWithContents = [ - self::dumpRequirementsConfig($composerJsonDecodedContents, $composerLockDecodedContents, $compressionAlgorithm), + self::dumpRequirementsConfig($decodedComposerJsonContents, $decodedComposerLockContents, $compressionAlgorithm), [self::CHECK_FILE_NAME, self::REQUIREMENTS_CHECKER_TEMPLATE], ]; /** @var SplFileInfo[] $requirementCheckerFiles */ $requirementCheckerFiles = Finder::create() ->files() - ->in(self::REQUIRMEMENT_CHECKER_PATH) + ->in(self::REQUIREMENT_CHECKER_PATH) ; foreach ($requirementCheckerFiles as $file) { diff --git a/src/Test/FileSystemTestCase.php b/src/Test/FileSystemTestCase.php index acc00d2a2..f5ae2a2d6 100644 --- a/src/Test/FileSystemTestCase.php +++ b/src/Test/FileSystemTestCase.php @@ -61,4 +61,27 @@ protected function tearDown(): void remove($this->tmp); } + + /** + * @param string[] $files + * + * @return string[] File real paths relative to the current temporary directory + */ + final protected function normalizePaths(array $files): array + { + $root = $this->tmp; + + $files = array_values( + array_map( + function (string $file) use ($root): string { + return str_replace($root.DIRECTORY_SEPARATOR, '', $file); + }, + $files + ) + ); + + natcasesort($files); + + return array_values($files); + } } diff --git a/src/functions.php b/src/functions.php index 94e55771b..5d8bafbd2 100644 --- a/src/functions.php +++ b/src/functions.php @@ -20,6 +20,7 @@ use function constant; use function define; use function defined; +use function sprintf; /** * TODO: this function should be pushed down to the PHAR extension. @@ -48,7 +49,10 @@ function get_phar_compression_algorithm_extension(int $algorithm): ?string Phar::NONE => null, ]; - Assertion::true(array_key_exists($algorithm, $extensions)); + Assertion::true( + array_key_exists($algorithm, $extensions), + sprintf('Unknown compression algorithm code "%d"', $algorithm) + ); return $extensions[$algorithm]; } diff --git a/tests/Compactor/PhpScoperTest.php b/tests/Compactor/PhpScoperTest.php index e1a7d193a..4ed44b439 100644 --- a/tests/Compactor/PhpScoperTest.php +++ b/tests/Compactor/PhpScoperTest.php @@ -16,6 +16,7 @@ use Error; use KevinGH\Box\Compactor\PhpScoper; +use KevinGH\Box\PhpScoper\FakeScoper; use KevinGH\Box\PhpScoper\Scoper; use PHPUnit\Framework\TestCase; use Prophecy\Argument; @@ -73,4 +74,13 @@ public function test_it_returns_the_content_unchanged_if_the_scoping_failed(): v $this->assertSame($contents, $actual); } + + public function test_it_exposes_the_scoper(): void + { + $scoper = new FakeScoper(); + + $compactor = new PhpScoper($scoper); + + $this->assertSame($scoper, $compactor->getScoper()); + } } diff --git a/tests/Composer/ComposerOrchestratorTest.php b/tests/Composer/ComposerOrchestratorTest.php new file mode 100644 index 000000000..d3a26ffb3 --- /dev/null +++ b/tests/Composer/ComposerOrchestratorTest.php @@ -0,0 +1,423 @@ + + * Théo Fidry + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace KevinGH\Box\Composer; + +use KevinGH\Box\Test\FileSystemTestCase; +use RuntimeException; +use Symfony\Component\Finder\Finder; +use function Humbug\get_contents; +use function iterator_to_array; +use function KevinGH\Box\FileSystem\dump_file; +use function KevinGH\Box\FileSystem\mirror; +use function preg_replace; + +/** + * @covers \KevinGH\Box\Composer\ComposerOrchestrator + */ +class ComposerOrchestratorTest extends FileSystemTestCase +{ + private const FIXTURES = __DIR__.'/../../fixtures/composer-dump'; + private const COMPOSER_AUTOLOADER_NAME = 'ComposerAutoloaderInit80c62b20a4a44fb21e8e102ccb92ff05'; + + /** + * @dataProvider provideComposerAutoload + */ + public function test_it_can_dump_the_autoloader_with_an_empty_composer_json( + array $whitelist, + string $prefix, + string $expectedAutoloadContents + ): void { + dump_file('composer.json', '{}'); + + ComposerOrchestrator::dumpAutoload($whitelist, $prefix); + + $expectedPaths = [ + 'composer.json', + 'vendor/autoload.php', + 'vendor/composer/autoload_classmap.php', + 'vendor/composer/autoload_namespaces.php', + 'vendor/composer/autoload_psr4.php', + 'vendor/composer/autoload_real.php', + 'vendor/composer/autoload_static.php', + 'vendor/composer/ClassLoader.php', + 'vendor/composer/LICENSE', + ]; + + $actualPaths = $this->retrievePaths(); + + $this->assertSame($expectedPaths, $actualPaths); + + $this->assertSame( + $expectedAutoloadContents, + preg_replace( + '/ComposerAutoloaderInit[a-z\d]{32}/', + 'ComposerAutoloaderInit80c62b20a4a44fb21e8e102ccb92ff05', + get_contents($this->tmp.'/vendor/autoload.php') + ) + ); + + $this->assertSame( + <<<'PHP' +tmp.'/vendor/composer/autoload_psr4.php') + ) + ); + } + + /** + * @dataProvider provideComposerAutoload + */ + public function test_it_cannot_dump_the_autoloader_with_an_invalid_composer_json( + array $whitelist, + string $prefix + ): void { + mirror(self::FIXTURES.'/dir000', $this->tmp); + + dump_file('composer.json', ''); + + try { + ComposerOrchestrator::dumpAutoload($whitelist, $prefix); + + $this->fail('Expected exception to be thrown.'); + } catch (RuntimeException $exception) { + $this->assertStringStartsWith( + 'Could not dump the autoload: "./composer.json" does not contain valid JSON', + $exception->getMessage() + ); + } + } + + public function test_it_can_dump_the_autoloader_with_a_composer_json_with_a_dependency(): void + { + mirror(self::FIXTURES.'/dir000', $this->tmp); + + ComposerOrchestrator::dumpAutoload([], ''); + + $expectedPaths = [ + 'composer.json', + 'vendor/autoload.php', + 'vendor/composer/autoload_classmap.php', + 'vendor/composer/autoload_namespaces.php', + 'vendor/composer/autoload_psr4.php', + 'vendor/composer/autoload_real.php', + 'vendor/composer/autoload_static.php', + 'vendor/composer/ClassLoader.php', + 'vendor/composer/LICENSE', + ]; + + $actualPaths = $this->retrievePaths(); + + $this->assertSame($expectedPaths, $actualPaths); + + $this->assertSame( + <<<'PHP' +tmp.'/vendor/autoload.php') + ) + ); + + $this->assertSame( + <<<'PHP' +tmp.'/vendor/composer/autoload_psr4.php') + ) + ); + } + + /** + * @dataProvider provideComposerAutoload + */ + public function test_it_cannot_dump_the_autoloader_if_the_composer_json_file_is_missing( + array $whitelist, + string $prefix + ): void { + try { + ComposerOrchestrator::dumpAutoload($whitelist, $prefix); + + $this->fail('Expected exception to be thrown.'); + } catch (RuntimeException $exception) { + $this->assertStringStartsWith( + 'Could not dump the autoload: Composer could not find a composer.json file in', + $exception->getMessage() + ); + } + } + + /** + * @dataProvider provideComposerAutoload + */ + public function test_it_can_dump_the_autoloader_with_a_composer_json_lock_and_installed_with_a_dependency( + array $whitelist, + string $prefix, + string $expectedAutoloadContents + ): void { + mirror(self::FIXTURES.'/dir001', $this->tmp); + + ComposerOrchestrator::dumpAutoload($whitelist, $prefix); + + // The fact that there is a dependency in the `composer.json` does not change anything to Composer + $expectedPaths = [ + 'composer.json', + 'composer.lock', + 'vendor/autoload.php', + 'vendor/beberlei/assert/composer.json', + 'vendor/beberlei/assert/lib/Assert/Assert.php', + 'vendor/beberlei/assert/lib/Assert/Assertion.php', + 'vendor/beberlei/assert/lib/Assert/AssertionChain.php', + 'vendor/beberlei/assert/lib/Assert/AssertionFailedException.php', + 'vendor/beberlei/assert/lib/Assert/functions.php', + 'vendor/beberlei/assert/lib/Assert/InvalidArgumentException.php', + 'vendor/beberlei/assert/lib/Assert/LazyAssertion.php', + 'vendor/beberlei/assert/lib/Assert/LazyAssertionException.php', + 'vendor/beberlei/assert/LICENSE', + 'vendor/composer/autoload_classmap.php', + 'vendor/composer/autoload_files.php', + 'vendor/composer/autoload_namespaces.php', + 'vendor/composer/autoload_psr4.php', + 'vendor/composer/autoload_real.php', + 'vendor/composer/autoload_static.php', + 'vendor/composer/ClassLoader.php', + 'vendor/composer/installed.json', + 'vendor/composer/LICENSE', + ]; + + $actualPaths = $this->retrievePaths(); + + $this->assertSame($expectedPaths, $actualPaths); + + $this->assertSame( + $expectedAutoloadContents, + preg_replace( + '/ComposerAutoloaderInit[a-z\d]{32}/', + 'ComposerAutoloaderInit80c62b20a4a44fb21e8e102ccb92ff05', + get_contents($this->tmp.'/vendor/autoload.php') + ) + ); + + $this->assertSame( + <<<'PHP' + array($vendorDir . '/beberlei/assert/lib/Assert'), +); + +PHP + , + preg_replace( + '/ComposerAutoloaderInit[a-z\d]{32}/', + 'ComposerAutoloaderInit80c62b20a4a44fb21e8e102ccb92ff05', + get_contents($this->tmp.'/vendor/composer/autoload_psr4.php') + ) + ); + } + + /** + * @dataProvider provideComposerAutoload + */ + public function test_it_can_dump_the_autoloader_with_a_composer_json_and_lock_with_a_dependency( + array $whitelist, + string $prefix, + string $expectedAutoloadContents + ): void { + mirror(self::FIXTURES.'/dir002', $this->tmp); + + ComposerOrchestrator::dumpAutoload($whitelist, $prefix); + + // The fact that there is a dependency in the `composer.json` does not change anything to Composer + $expectedPaths = [ + 'composer.json', + 'composer.lock', + 'vendor/autoload.php', + 'vendor/beberlei/assert/composer.json', + 'vendor/beberlei/assert/lib/Assert/Assert.php', + 'vendor/beberlei/assert/lib/Assert/Assertion.php', + 'vendor/beberlei/assert/lib/Assert/AssertionChain.php', + 'vendor/beberlei/assert/lib/Assert/AssertionFailedException.php', + 'vendor/beberlei/assert/lib/Assert/functions.php', + 'vendor/beberlei/assert/lib/Assert/InvalidArgumentException.php', + 'vendor/beberlei/assert/lib/Assert/LazyAssertion.php', + 'vendor/beberlei/assert/lib/Assert/LazyAssertionException.php', + 'vendor/beberlei/assert/LICENSE', + 'vendor/composer/autoload_classmap.php', + 'vendor/composer/autoload_namespaces.php', + 'vendor/composer/autoload_psr4.php', + 'vendor/composer/autoload_real.php', + 'vendor/composer/autoload_static.php', + 'vendor/composer/ClassLoader.php', + 'vendor/composer/LICENSE', + ]; + + $actualPaths = $this->retrievePaths(); + + $this->assertSame($expectedPaths, $actualPaths); + + $this->assertSame( + $expectedAutoloadContents, + preg_replace( + '/ComposerAutoloaderInit[a-z\d]{32}/', + 'ComposerAutoloaderInit80c62b20a4a44fb21e8e102ccb92ff05', + get_contents($this->tmp.'/vendor/autoload.php') + ) + ); + + $this->assertSame( + <<<'PHP' +tmp.'/vendor/composer/autoload_psr4.php') + ) + ); + } + + public function provideComposerAutoload() + { + $composerAutoloaderName = self::COMPOSER_AUTOLOADER_NAME; + + yield [ + [], + '', + <<files()->in($this->tmp); + + return $this->normalizePaths(iterator_to_array($finder)); + } +} diff --git a/tests/ConfigurationFileNoConfigTest.php b/tests/ConfigurationFileNoConfigTest.php index 7a66e1aac..417492294 100644 --- a/tests/ConfigurationFileNoConfigTest.php +++ b/tests/ConfigurationFileNoConfigTest.php @@ -128,14 +128,14 @@ public function test_all_the_files_found_in_the_composer_json_are_taken_by_defau $noFileConfig = $this->getNoFileConfig(); - $actual = $this->normalizeConfigPaths($noFileConfig->getFiles()); + $actual = $this->normalizePaths($noFileConfig->getFiles()); $this->assertEquals($expected, $actual); $this->assertCount(0, $noFileConfig->getBinaryFiles()); $this->reloadConfig(); - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertEquals($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -349,12 +349,12 @@ public function test_the_blacklist_setting_is_applied_to_all_the_files_found_in_ 'PSR4_2/file0', ]; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertEquals($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertEquals($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -572,14 +572,14 @@ public function test_it_ignores_the_most_common_non_needed_files_when_guess_the_ $noFileConfig = $this->getNoFileConfig(); - $actual = $this->normalizeConfigPaths($noFileConfig->getFiles()); + $actual = $this->normalizePaths($noFileConfig->getFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $noFileConfig->getBinaryFiles()); $this->reloadConfig(); - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -594,7 +594,7 @@ public function test_the_existing_PHARs_are_ignored_when_all_the_files_are_colle $this->reloadConfig(); - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertEquals($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -609,7 +609,7 @@ public function test_the_existing_PHARs_are_ignored_when_all_the_files_are_colle 'output' => 'default', ]); - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertEquals($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -650,7 +650,7 @@ public function test_the_box_debug_directory_is_always_excluded(): void $noFileConfig = $this->getNoFileConfig(); - $actual = $this->normalizeConfigPaths($noFileConfig->getFiles()); + $actual = $this->normalizePaths($noFileConfig->getFiles()); $this->assertEquals($expected, $actual); $this->assertCount(0, $noFileConfig->getBinaryFiles()); @@ -678,14 +678,14 @@ public function test_it_includes_the_vendor_files_when_found(): void $noFileConfig = $this->getNoFileConfig(); - $actual = $this->normalizeConfigPaths($noFileConfig->getFiles()); + $actual = $this->normalizePaths($noFileConfig->getFiles()); $this->assertEquals($expected, $actual); $this->assertCount(0, $noFileConfig->getBinaryFiles()); $this->reloadConfig(); - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertEquals($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); diff --git a/tests/ConfigurationFileTest.php b/tests/ConfigurationFileTest.php index 7388f233e..f93cd899c 100644 --- a/tests/ConfigurationFileTest.php +++ b/tests/ConfigurationFileTest.php @@ -17,12 +17,12 @@ use Generator; use InvalidArgumentException; use KevinGH\Box\Json\JsonValidationException; +use const DIRECTORY_SEPARATOR; use function file_put_contents; use function KevinGH\Box\FileSystem\dump_file; use function KevinGH\Box\FileSystem\make_path_absolute; use function KevinGH\Box\FileSystem\rename; use function KevinGH\Box\FileSystem\symlink; -use const DIRECTORY_SEPARATOR; /** * @covers \KevinGH\Box\Configuration @@ -125,7 +125,7 @@ public function test_the_files_can_be_configured(): void 'file1', // 'files' & 'files-bin' are not affected by the blacklist filter ]; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -140,8 +140,8 @@ public function test_the_main_script_file_is_always_ignored(callable $setUp, arr $this->setConfig($config); - $actualFiles = $this->normalizeConfigPaths($this->config->getFiles()); - $actualBinFiles = $this->normalizeConfigPaths($this->config->getBinaryFiles()); + $actualFiles = $this->normalizePaths($this->config->getFiles()); + $actualBinFiles = $this->normalizePaths($this->config->getBinaryFiles()); $this->assertSame($expectedFiles, $actualFiles); $this->assertSame($expectedBinFiles, $actualBinFiles); @@ -233,7 +233,7 @@ public function test_configured_files_are_relative_to_base_path(): void 'sub-dir/file1', ]; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -311,7 +311,7 @@ public function test_configured_files_are_relative_to_base_path_unless_they_are_ 'sub-dir/file1', ]; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -413,7 +413,7 @@ public function test_the_files_belonging_to_dev_packages_are_ignored_only_in_the 'vendor/acme/foo/af1', ]; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -763,7 +763,7 @@ public function test_the_bin_files_iterator_can_be_configured(): void 'file1', // 'files' & 'files-bin' are not affected by the blacklist filter ]; - $actual = $this->normalizeConfigPaths($this->config->getBinaryFiles()); + $actual = $this->normalizePaths($this->config->getBinaryFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getFiles()); @@ -843,7 +843,7 @@ public function test_configured_bin_files_are_relative_to_base_path(): void 'sub-dir/file1', ]; - $actual = $this->normalizeConfigPaths($this->config->getBinaryFiles()); + $actual = $this->normalizePaths($this->config->getBinaryFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getFiles()); @@ -921,7 +921,7 @@ public function test_configured_bin_files_are_relative_to_base_path_unless_they_ 'sub-dir/file1', ]; - $actual = $this->normalizeConfigPaths($this->config->getBinaryFiles()); + $actual = $this->normalizePaths($this->config->getBinaryFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getFiles()); @@ -1069,11 +1069,11 @@ public function test_the_cannot_be_included_twice(): void $this->assertSame( $expected, - $this->normalizeConfigPaths($this->config->getFiles()) + $this->normalizePaths($this->config->getFiles()) ); $this->assertSame( $expected, - $this->normalizeConfigPaths($this->config->getBinaryFiles()) + $this->normalizePaths($this->config->getBinaryFiles()) ); } @@ -1117,7 +1117,7 @@ public function test_the_blacklist_input_is_normalized(): void $expected = [ 'B/fileB0', ]; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); } @@ -1132,7 +1132,7 @@ public function test_the_blacklist_input_may_refer_to_non_existent_paths(): void // Relative to the current working directory for readability $expected = []; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); } @@ -1197,11 +1197,11 @@ public function test_the_files_and_bin_files_input_is_normalized(): void $this->assertSame( $expected, - $this->normalizeConfigPaths($this->config->getFiles()) + $this->normalizePaths($this->config->getFiles()) ); $this->assertSame( $expected, - $this->normalizeConfigPaths($this->config->getBinaryFiles()) + $this->normalizePaths($this->config->getBinaryFiles()) ); } @@ -1266,11 +1266,11 @@ public function test_the_directories_and_bin_directories_input_is_normalized(): $this->assertSame( $expected, - $this->normalizeConfigPaths($this->config->getFiles()) + $this->normalizePaths($this->config->getFiles()) ); $this->assertSame( $expected, - $this->normalizeConfigPaths($this->config->getBinaryFiles()) + $this->normalizePaths($this->config->getBinaryFiles()) ); } @@ -1354,7 +1354,7 @@ public function test_finder_and_bin_finder_input_is_normalized(): void $this->assertEquals( $expected, - $this->normalizeConfigPaths($this->config->getFiles()), + $this->normalizePaths($this->config->getFiles()), '', .0, 10, @@ -1362,7 +1362,7 @@ public function test_finder_and_bin_finder_input_is_normalized(): void ); $this->assertEquals( $expected, - $this->normalizeConfigPaths($this->config->getBinaryFiles()), + $this->normalizePaths($this->config->getBinaryFiles()), '', .0, 10, @@ -1392,7 +1392,7 @@ public function test_finder_and_bin_finder_exclude_files_or_directories_may_not_ $this->assertEquals( $expected, - $this->normalizeConfigPaths($this->config->getFiles()), + $this->normalizePaths($this->config->getFiles()), '', .0, 10, @@ -1400,7 +1400,7 @@ public function test_finder_and_bin_finder_exclude_files_or_directories_may_not_ ); $this->assertEquals( $expected, - $this->normalizeConfigPaths($this->config->getBinaryFiles()), + $this->normalizePaths($this->config->getBinaryFiles()), '', .0, 10, @@ -1436,7 +1436,7 @@ public function test_finder_array_arguments_are_called_as_single_arguments(): vo 'A/foo', 'B/bar', ]; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); } @@ -1489,7 +1489,7 @@ public function test_the_composer_json_and_lock_files_are_always_included_even_w 'file1', ]; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); @@ -1506,7 +1506,7 @@ public function test_the_composer_json_and_lock_files_are_always_included_even_w 'composer.lock', ]; - $actual = $this->normalizeConfigPaths($this->config->getFiles()); + $actual = $this->normalizePaths($this->config->getFiles()); $this->assertSame($expected, $actual); $this->assertCount(0, $this->config->getBinaryFiles()); diff --git a/tests/ConfigurationTest.php b/tests/ConfigurationTest.php index 8c5c99a63..0245f6d75 100644 --- a/tests/ConfigurationTest.php +++ b/tests/ConfigurationTest.php @@ -25,14 +25,15 @@ use Phar; use Seld\JsonLint\ParsingException; use stdClass; +use const DIRECTORY_SEPARATOR; use function file_put_contents; use function KevinGH\Box\FileSystem\dump_file; use function KevinGH\Box\FileSystem\remove; use function KevinGH\Box\FileSystem\rename; -use const DIRECTORY_SEPARATOR; /** * @covers \KevinGH\Box\Configuration + * @covers \KevinGH\Box\MapFile */ class ConfigurationTest extends ConfigurationTestCase { @@ -233,10 +234,10 @@ public function test_it_attempts_to_get_and_decode_the_json_and_lock_files( $this->reloadConfig(); $this->assertSame($expectedJson, $this->config->getComposerJson()); - $this->assertSame($expectedJsonContents, $this->config->getComposerJsonDecodedContents()); + $this->assertSame($expectedJsonContents, $this->config->getDecodedComposerJsonContents()); $this->assertSame($expectedLock, $this->config->getComposerLock()); - $this->assertSame($expectedLockContents, $this->config->getComposerLockDecodedContents()); + $this->assertSame($expectedLockContents, $this->config->getDecodedComposerLockContents()); } public function test_it_throws_an_error_when_a_composer_file_is_found_but_invalid(): void @@ -702,31 +703,19 @@ public function test_the_main_script_cannot_be_enabled(): void } } - public function test_get_map(): void + public function test_there_is_no_file_map_configured_by_default(): void { - $this->assertSame([], $this->config->getMap()); - } + $mapFile = $this->config->getFileMapper(); - public function test_configure_map(): void - { - $this->setConfig([ - 'files' => [self::DEFAULT_FILE], - 'map' => [ - ['a' => 'b'], - ['_empty_' => 'c'], - ], - ]); + $this->assertSame([], $mapFile->getMap()); $this->assertSame( - [ - ['a' => 'b'], - ['' => 'c'], - ], - $this->config->getMap() + 'first/test/path/sub/path/file.php', + $mapFile('first/test/path/sub/path/file.php') ); } - public function test_get_mapper(): void + public function test_the_file_map_can_be_configured(): void { $this->setConfig([ 'files' => [self::DEFAULT_FILE], @@ -738,6 +727,14 @@ public function test_get_mapper(): void $mapFile = $this->config->getFileMapper(); + $this->assertSame( + [ + ['first/test/path' => 'a'], + ['' => 'b'], + ], + $mapFile->getMap() + ); + $this->assertSame( 'a/sub/path/file.php', $mapFile('first/test/path/sub/path/file.php') diff --git a/tests/ConfigurationTestCase.php b/tests/ConfigurationTestCase.php index 6cda8df1c..94a40a46e 100644 --- a/tests/ConfigurationTestCase.php +++ b/tests/ConfigurationTestCase.php @@ -19,8 +19,6 @@ use stdClass; use function file_put_contents; use function KevinGH\Box\FileSystem\make_path_absolute; -use function natcasesort; -use const DIRECTORY_SEPARATOR; abstract class ConfigurationTestCase extends FileSystemTestCase { @@ -70,29 +68,6 @@ final protected function isWindows(): bool return false === strpos(strtolower(PHP_OS), 'darwin') && false !== strpos(strtolower(PHP_OS), 'win'); } - /** - * @param string[] $files - * - * @return string[] File real paths relative to the current temporary directory - */ - final protected function normalizeConfigPaths(array $files): array - { - $root = $this->tmp; - - $files = array_values( - array_map( - function (string $file) use ($root): string { - return str_replace($root.DIRECTORY_SEPARATOR, '', $file); - }, - $files - ) - ); - - natcasesort($files); - - return array_values($files); - } - final protected function getNoFileConfig(): Configuration { return Configuration::create(null, new stdClass()); diff --git a/tests/Console/Command/CompileTest.php b/tests/Console/Command/CompileTest.php index a540db913..e9acadbd0 100644 --- a/tests/Console/Command/CompileTest.php +++ b/tests/Console/Command/CompileTest.php @@ -15,6 +15,7 @@ namespace KevinGH\Box\Console\Command; use DirectoryIterator; +use function extension_loaded; use Generator; use InvalidArgumentException; use KevinGH\Box\Compactor\Php; @@ -24,17 +25,21 @@ use PharFileInfo; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Finder\Finder; use Symfony\Component\Process\PhpExecutableFinder; use Traversable; use function file_get_contents; use function file_put_contents; +use function iterator_to_array; use function KevinGH\Box\FileSystem\dump_file; +use function KevinGH\Box\FileSystem\file_contents; use function KevinGH\Box\FileSystem\mirror; use function KevinGH\Box\FileSystem\rename; use function preg_match; use function preg_replace; use function sort; use function sprintf; +use function str_replace; /** * @covers \KevinGH\Box\Console\Command\Compile @@ -911,6 +916,483 @@ public function test_it_can_build_a_PHAR_file_in_very_verbose_mode(): void $this->assertSame($expected, $actual); } + public function test_it_can_build_a_PHAR_file_in_debug_mode(): void + { + mirror(self::FIXTURES_DIR.'/dir000', $this->tmp); + + $shebang = sprintf('#!%s', (new PhpExecutableFinder())->find()); + + file_put_contents( + 'box.json', + json_encode( + [ + 'alias' => 'test.phar', + 'banner' => [ + 'multiline', + 'custom banner', + ], + 'chmod' => '0755', + 'compactors' => [Php::class], + 'directories' => ['a'], + 'files' => ['test.php'], + 'finder' => [['in' => 'one']], + 'finder-bin' => [['in' => 'two']], + 'key' => 'private.key', + 'key-pass' => true, + 'main' => 'run.php', + 'map' => [ + ['a/deep/test/directory' => 'sub'], + ], + 'metadata' => ['rand' => $rand = random_int(0, mt_getrandmax())], + 'output' => 'test.phar', + 'shebang' => $shebang, + 'stub' => true, + ] + ) + ); + + $this->assertDirectoryNotExists('.box_dump'); + + $commandTester = $this->getCommandTester(); + + $commandTester->setInputs(['test']); // Set input for the passphrase + $commandTester->execute( + [ + 'command' => 'compile', + '--debug' => null, + ], + [ + 'interactive' => true, + 'verbosity' => OutputInterface::VERBOSITY_DEBUG, + ] + ); + + $xdebugLog = extension_loaded('xdebug') + ? '[debug] The xdebug extension is loaded (2.6.0) +[debug] No restart (BOX_ALLOW_XDEBUG=1)' + : '[debug] The xdebug extension is not loaded' + ; + + $expected = << < +/_____/\____/_/|_| + + +Box (repo) + + + // Loading the configuration file "/path/to/box.json.dist". + +? Removing the existing PHAR "/path/to/tmp/test.phar" +* Building the PHAR "/path/to/tmp/test.phar" +? Registering compactors + + KevinGH\Box\Compactor\Php +? Mapping paths + - a/deep/test/directory > sub +? Adding main file: /path/to/tmp/run.php +? Adding requirements checker +? Adding binary files + > 1 file(s) +? Adding files + > 4 file(s) +? Generating new stub + - Using shebang line: #!__PHP_EXECUTABLE__ + - Using banner: + > multiline + > custom banner +? Setting metadata + - array ( + 'rand' => $rand, +) +? Dumping the Composer autoloader +? Removing the Composer dump artefacts +? No compression +? Signing using a private key +Private key passphrase: +? Setting file permissions to 0755 +* Done. + + // PHAR: 44 files (100B) + // You can inspect the generated PHAR with the "info" command. + + // Memory usage: 5.00MB (peak: 10.00MB), time: 0.00s + + +OUTPUT; + + $expected = str_replace( + '__PHP_EXECUTABLE__', + (new PhpExecutableFinder())->find(), + $expected + ); + $actual = $this->normalizeDisplay($commandTester->getDisplay(true)); + + $this->assertSame($expected, $actual); + + $this->assertDirectoryExists('.box_dump'); + + $expectedFiles = [ + '.box_dump/.box/.requirements.php', + '.box_dump/.box/bin/check-requirements.php', + '.box_dump/.box/check_requirements.php', + '.box_dump/.box/composer.json', + '.box_dump/.box/composer.lock', + '.box_dump/.box/src/Checker.php', + '.box_dump/.box/src/IO.php', + '.box_dump/.box/src/IsExtensionFulfilled.php', + '.box_dump/.box/src/IsFulfilled.php', + '.box_dump/.box/src/IsPhpVersionFulfilled.php', + '.box_dump/.box/src/Printer.php', + '.box_dump/.box/src/Requirement.php', + '.box_dump/.box/src/RequirementCollection.php', + '.box_dump/.box/src/Terminal.php', + '.box_dump/.box/vendor/autoload.php', + '.box_dump/.box/vendor/composer/autoload_classmap.php', + '.box_dump/.box/vendor/composer/autoload_namespaces.php', + '.box_dump/.box/vendor/composer/autoload_psr4.php', + '.box_dump/.box/vendor/composer/autoload_real.php', + '.box_dump/.box/vendor/composer/autoload_static.php', + '.box_dump/.box/vendor/composer/ClassLoader.php', + '.box_dump/.box/vendor/composer/installed.json', + '.box_dump/.box/vendor/composer/LICENSE', + '.box_dump/.box/vendor/composer/semver/src/Comparator.php', + '.box_dump/.box/vendor/composer/semver/src/Constraint/AbstractConstraint.php', + '.box_dump/.box/vendor/composer/semver/src/Constraint/Constraint.php', + '.box_dump/.box/vendor/composer/semver/src/Constraint/ConstraintInterface.php', + '.box_dump/.box/vendor/composer/semver/src/Constraint/EmptyConstraint.php', + '.box_dump/.box/vendor/composer/semver/src/Constraint/MultiConstraint.php', + '.box_dump/.box/vendor/composer/semver/src/Semver.php', + '.box_dump/.box/vendor/composer/semver/src/VersionParser.php', + '.box_dump/.box_configuration', + '.box_dump/one/test.php', + '.box_dump/run.php', + '.box_dump/sub/test.php', + '.box_dump/test.php', + '.box_dump/two/test.png', + '.box_dump/vendor/autoload.php', + '.box_dump/vendor/composer/autoload_classmap.php', + '.box_dump/vendor/composer/autoload_namespaces.php', + '.box_dump/vendor/composer/autoload_psr4.php', + '.box_dump/vendor/composer/autoload_real.php', + '.box_dump/vendor/composer/autoload_static.php', + '.box_dump/vendor/composer/ClassLoader.php', + '.box_dump/vendor/composer/LICENSE', + ]; + + $actualFiles = $this->normalizePaths( + iterator_to_array( + Finder::create()->files()->in('.box_dump')->ignoreDotFiles(false) + ) + ); + + $this->assertSame($expectedFiles, $actualFiles); + + $shebang = sprintf('#!%s', (new PhpExecutableFinder())->find()); + + $expectedDumpedConfig = << "/path/to/composer.json" + 1 => array:1 [ + "autoload" => array:1 [ + "classmap" => array:1 [ + 0 => "./" + ] + ] + ] + ] + -composerLock: array:2 [ + 0 => null + 1 => null + ] + -files: array:4 [ + 0 => SplFileInfo {#140 + path: "/path/to" + filename: "test.php" + basename: "test.php" + pathname: "/path/to/test.php" + extension: "php" + realPath: "/path/to/test.php" + aTime: 2018-05-24 20:59:15 + mTime: 2018-05-24 20:59:15 + cTime: 2018-05-24 20:59:15 + inode: 33452869 + size: 306 + perms: 0100644 + owner: 501 + group: 20 + type: "file" + writable: true + readable: true + executable: false + file: true + dir: false + link: false + } + 1 => SplFileInfo {#140 + path: "/path/to" + filename: "composer.json" + basename: "composer.json" + pathname: "/path/to/composer.json" + extension: "json" + realPath: "/path/to/composer.json" + aTime: 2018-05-24 20:59:15 + mTime: 2018-05-24 20:59:15 + cTime: 2018-05-24 20:59:15 + inode: 33452869 + size: 54 + perms: 0100644 + owner: 501 + group: 20 + type: "file" + writable: true + readable: true + executable: false + file: true + dir: false + link: false + } + 2 => Symfony\Component\Finder\SplFileInfo {#140 + -relativePath: "deep/test/directory" + -relativePathname: "deep/test/directory/test.php" + path: "/path/to/a/deep/test/directory" + filename: "test.php" + basename: "test.php" + pathname: "/path/to/a/deep/test/directory/test.php" + extension: "php" + realPath: "/path/to/a/deep/test/directory/test.php" + aTime: 2018-05-24 20:59:15 + mTime: 2018-05-24 20:59:15 + cTime: 2018-05-24 20:59:15 + inode: 33452869 + size: 0 + perms: 0100644 + owner: 501 + group: 20 + type: "file" + writable: true + readable: true + executable: false + file: true + dir: false + link: false + } + 3 => Symfony\Component\Finder\SplFileInfo {#140 + -relativePath: "" + -relativePathname: "test.php" + path: "/path/to/one" + filename: "test.php" + basename: "test.php" + pathname: "/path/to/one/test.php" + extension: "php" + realPath: "/path/to/one/test.php" + aTime: 2018-05-24 20:59:15 + mTime: 2018-05-24 20:59:15 + cTime: 2018-05-24 20:59:15 + inode: 33452869 + size: 0 + perms: 0100644 + owner: 501 + group: 20 + type: "file" + writable: true + readable: true + executable: false + file: true + dir: false + link: false + } + ] + -binaryFiles: array:1 [ + 0 => Symfony\Component\Finder\SplFileInfo {#140 + -relativePath: "" + -relativePathname: "test.png" + path: "/path/to/two" + filename: "test.png" + basename: "test.png" + pathname: "/path/to/two/test.png" + extension: "png" + realPath: "/path/to/two/test.png" + aTime: 2018-05-24 20:59:15 + mTime: 2018-05-24 20:59:15 + cTime: 2018-05-24 20:59:15 + inode: 33452869 + size: 0 + perms: 0100644 + owner: 501 + group: 20 + type: "file" + writable: true + readable: true + executable: false + file: true + dir: false + link: false + } + ] + -dumpAutoload: true + -excludeComposerFiles: true + -compactors: array:1 [ + 0 => KevinGH\Box\Compactor\Php {#140 + -converter: Herrera\Annotations\Convert\ToString {#140 + -break: "\\n" + -char: " " + -level: null + -space: false + -size: 0 + #result: null + #tokens: null + } + -tokenizer: Herrera\Annotations\Tokenizer {#140 + -aliases: [] + -ignored: [] + -lexer: Doctrine\Common\Annotations\DocLexer {#140 + #noCase: array:9 [ + "@" => 101 + "," => 104 + "(" => 109 + ")" => 103 + "{" => 108 + "}" => 102 + "=" => 105 + ":" => 112 + "\" => 107 + ] + #withCase: array:3 [ + "true" => 110 + "false" => 106 + "null" => 111 + ] + -input: null + -tokens: [] + -position: 0 + -peek: 0 + +lookahead: null + +token: null + } + } + -extensions: array:1 [ + 0 => "php" + ] + } + ] + -compressionAlgorithm: null + -mainScriptPath: "/path/to/run.php" + -mainScriptContents: """ + \\n + * Théo Fidry \\n + *\\n + * This source file is subject to the MIT license that is bundled\\n + * with this source code in the file LICENSE.\\n + */\\n + \\n + require 'test.php';\\n + """ + -map: null + -fileMapper: KevinGH\Box\MapFile {#140 + -map: array:1 [ + 0 => array:1 [ + "a/deep/test/directory" => "sub" + ] + ] + } + -metadata: array:1 [ + "rand" => $rand + ] + -tmpOutputPath: "/path/to/test.phar" + -outputPath: "/path/to/test.phar" + -privateKeyPassphrase: null + -privateKeyPath: "private.key" + -isPrivateKeyPrompt: true + -processedReplacements: [] + -shebang: "$shebang" + -signingAlgorithm: 2 + -stubBannerContents: """ + multiline\\n + custom banner + """ + -stubBannerPath: null + -stubPath: null + -isInterceptFileFuncs: false + -isStubGenerated: true + -checkRequirements: true +} + +EOF; + + $actualDumpedConfig = str_replace( + $this->tmp, + '/path/to', + file_contents('.box_dump/.box_configuration') + ); + + $actualDumpedConfig = preg_replace( + '/ \{#\d{3,}/', + ' {#140', + $actualDumpedConfig + ); + + $actualDumpedConfig = preg_replace( + '/Time: \d{4,}-\d{2,}-\d{2,}T\d{2,}:\d{2,}:\d{2,}\+\d{2,}:\d{2,}/', + 'Time: 2018-05-24T20:59:15+00:00', + $actualDumpedConfig + ); + + $actualDumpedConfig = preg_replace( + '/([a-z]Time): \d{4,}-\d{2,}-\d{2,} \d{2,}:\d{2,}:\d{2,}/', + '$1: 2018-05-24 20:59:15', + $actualDumpedConfig + ); + + $actualDumpedConfig = preg_replace( + '/inode: \d+/', + 'inode: 33452869', + $actualDumpedConfig + ); + + $actualDumpedConfig = preg_replace( + '/perms: \d+/', + 'perms: 0100644', + $actualDumpedConfig + ); + + $actualDumpedConfig = preg_replace( + '/owner: \d+/', + 'owner: 501', + $actualDumpedConfig + ); + + $actualDumpedConfig = preg_replace( + '/group: \d+/', + 'group: 20', + $actualDumpedConfig + ); + + $this->assertSame($expectedDumpedConfig, $actualDumpedConfig); + } + public function test_it_can_build_a_PHAR_file_in_quiet_mode(): void { mirror(self::FIXTURES_DIR.'/dir000', $this->tmp); diff --git a/tests/Console/Command/ConfigurableTest.php b/tests/Console/Command/ConfigurableTest.php index 46f37b0bf..e0ba8e206 100644 --- a/tests/Console/Command/ConfigurableTest.php +++ b/tests/Console/Command/ConfigurableTest.php @@ -14,9 +14,12 @@ namespace KevinGH\Box\Console\Command; +use Assert\InvalidArgumentException; use Closure; use KevinGH\Box\Configuration; +use KevinGH\Box\Json\JsonValidationException; use KevinGH\Box\Test\CommandTestCase; +use KevinGH\Box\Throwable\Exception\NoConfigurationFound; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; @@ -39,7 +42,7 @@ public function test_it_can_get_the_configuration(): void { touch('index.php'); - file_put_contents('box.json', '{}'); + file_put_contents('box.json', '{"alias": "foo"}'); /** @var TestConfigurable $command */ $command = $this->application->get('test'); @@ -49,8 +52,9 @@ public function test_it_can_get_the_configuration(): void $output = new NullOutput(); + /** @var Configuration $config */ $config = (Closure::bind( - function (Configurable $command, InputInterface $input, OutputInterface $output) { + function (Configurable $command, InputInterface $input, OutputInterface $output): Configuration { return $command->getConfig($input, $output); }, null, @@ -61,6 +65,161 @@ function (Configurable $command, InputInterface $input, OutputInterface $output) Configuration::class, $config ); + + $this->assertSame('foo', $config->getAlias()); + } + + public function test_it_can_get_the_configuration__with_a_custom_path(): void + { + touch('index.php'); + + file_put_contents('mybox.json', '{"alias": "foo"}'); + + /** @var TestConfigurable $command */ + $command = $this->application->get('test'); + + $input = new ArrayInput(['--config' => 'mybox.json']); + $input->bind($command->getDefinition()); + + $output = new NullOutput(); + + /** @var Configuration $config */ + $config = (Closure::bind( + function (Configurable $command, InputInterface $input, OutputInterface $output): Configuration { + return $command->getConfig($input, $output); + }, + null, + TestConfigurable::class + )($command, $input, $output)); + + $this->assertInstanceOf( + Configuration::class, + $config + ); + + $this->assertSame('foo', $config->getAlias()); + } + + public function test_it_throws_an_error_when_cannot_load_the_config(): void + { + touch('index.php'); + + /** @var TestConfigurable $command */ + $command = $this->application->get('test'); + + $input = new ArrayInput([]); + $input->bind($command->getDefinition()); + + $output = new NullOutput(); + + try { + (Closure::bind( + function (Configurable $command, InputInterface $input, OutputInterface $output): Configuration { + return $command->getConfig($input, $output); + }, + null, + TestConfigurable::class + )($command, $input, $output)); + + $this->fail('Expected exception to be thrown.'); + } catch (NoConfigurationFound $exception) { + $this->assertSame( + 'The configuration file could not be found.', + $exception->getMessage() + ); + } + } + + public function test_it_loads_an_empty_configuration_if_no_configuration_is_allowed_and_no_config_file_is_found(): void + { + touch('index.php'); + + /** @var TestConfigurable $command */ + $command = $this->application->get('test'); + + $input = new ArrayInput([]); + $input->bind($command->getDefinition()); + + $output = new NullOutput(); + + /** @var Configuration $config */ + $config = (Closure::bind( + function (Configurable $command, InputInterface $input, OutputInterface $output): Configuration { + return $command->getConfig($input, $output, true); + }, + null, + TestConfigurable::class + )($command, $input, $output)); + + $this->assertInstanceOf( + Configuration::class, + $config + ); + + $this->assertSame($this->tmp.'/index.php', $config->getMainScriptPath()); + } + + public function test_it_throws_an_error_when_the_config_schema_is_invalid(): void + { + touch('index.php'); + + file_put_contents('box.json', '{"foo": "foo"}'); + + /** @var TestConfigurable $command */ + $command = $this->application->get('test'); + + $input = new ArrayInput([]); + $input->bind($command->getDefinition()); + + $output = new NullOutput(); + + try { + (Closure::bind( + function (Configurable $command, InputInterface $input, OutputInterface $output): Configuration { + return $command->getConfig($input, $output); + }, + null, + TestConfigurable::class + )($command, $input, $output)); + + $this->fail('Expected exception to be thrown.'); + } catch (JsonValidationException $exception) { + $this->assertSame( + '"'.$this->tmp.'/box.json" does not match the expected JSON schema: + - The property foo is not defined and the definition does not allow additional properties', + $exception->getMessage() + ); + } + } + + public function test_it_throws_an_error_when_the_config_is_invalid(): void + { + file_put_contents('box.json', '{}'); + + /** @var TestConfigurable $command */ + $command = $this->application->get('test'); + + $input = new ArrayInput([]); + $input->bind($command->getDefinition()); + + $output = new NullOutput(); + + try { + (Closure::bind( + function (Configurable $command, InputInterface $input, OutputInterface $output): Configuration { + return $command->getConfig($input, $output); + }, + null, + TestConfigurable::class + )($command, $input, $output)); + + $this->fail('Expected exception to be thrown.'); + } catch (InvalidArgumentException $exception) { + $this->assertSame( + 'File "'.$this->tmp.'/index.php" was expected to exist.', + $exception->getMessage() + ); + } } /** diff --git a/tests/Console/Command/InfoTest.php b/tests/Console/Command/InfoTest.php index d9175bc5c..1445728b3 100644 --- a/tests/Console/Command/InfoTest.php +++ b/tests/Console/Command/InfoTest.php @@ -25,13 +25,10 @@ use function preg_replace; use function realpath; -///** -// * @covers \KevinGH\Box\Console\Command\Info -// * -// * @runTestsInSeparateProcesses -// */ /** - * @coversNothing + * @covers \KevinGH\Box\Console\Command\Info + * + * @runTestsInSeparateProcesses */ class InfoTest extends TestCase { diff --git a/tests/FunctionsTest.php b/tests/FunctionsTest.php new file mode 100644 index 000000000..ddf919195 --- /dev/null +++ b/tests/FunctionsTest.php @@ -0,0 +1,112 @@ + + * Théo Fidry + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace KevinGH\Box; + +use InvalidArgumentException; +use Phar; +use PHPUnit\Framework\TestCase; + +/** + * @coversNothing + */ +class FunctionsTest extends TestCase +{ + public function test_it_can_provide_the_PHARs_algorithms(): void + { + $expected = [ + 'GZ' => Phar::GZ, + 'BZ2' => Phar::BZ2, + 'NONE' => Phar::NONE, + ]; + + $actual = get_phar_compression_algorithms(); + + $this->assertSame($expected, $actual); + } + + /** + * @dataProvider providePharCompressionAlgorithm + * + * @param mixed $expected + */ + public function test_it_can_provide_the_PHARs_algorithm_extensions(int $algorithm, $expected): void + { + try { + $actual = get_phar_compression_algorithm_extension($algorithm); + + if (-1 === $expected) { + $this->fail('Expected exception to be thrown.'); + } + + $this->assertSame($expected, $actual); + } catch (InvalidArgumentException $exception) { + $this->assertSame( + 'Unknown compression algorithm code "'.$algorithm.'"', + $exception->getMessage() + ); + } + } + + /** + * @dataProvider provideBytes + */ + public function test_it_can_format_bytes(int $bytes, string $expected): void + { + $actual = format_size($bytes); + + $this->assertSame($expected, $actual); + } + + /** + * @dataProvider provideMemory + */ + public function test_it_can_convet_a_memory_limit_amount_to_bytes(string $memory, int $expected): void + { + $actual = memory_to_bytes($memory); + + $this->assertSame($expected, $actual); + } + + public function providePharCompressionAlgorithm() + { + yield [Phar::GZ, 'zlib']; + yield [Phar::BZ2, 'bz2']; + yield [Phar::NONE, null]; + yield [10, -1]; + } + + public function provideBytes() + { + yield [10, '10.00B']; + yield [1024, '1.00KB']; + yield [1024 ** 2, '1.00MB']; + yield [1024 ** 3, '1.00GB']; + yield [1024 ** 4, '1.00TB']; + yield [1024 ** 5, '1.00PB']; + yield [1024 ** 6, '1.00EB']; + } + + public function provideMemory() + { + yield ['-1', -1]; + yield ['10', 10]; + yield ['1k', 1024]; + yield ['10k', 10240]; + yield ['1m', 1024 ** 2]; + yield ['10m', (1024 ** 2) * 10]; + yield ['1g', 1024 ** 3]; + yield ['10g', (1024 ** 3) * 10]; + } +} diff --git a/tests/Json/JsonTest.php b/tests/Json/JsonTest.php new file mode 100644 index 000000000..301088ba8 --- /dev/null +++ b/tests/Json/JsonTest.php @@ -0,0 +1,306 @@ + + * Théo Fidry + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace KevinGH\Box\Json; + +use Assert\Assertion; +use KevinGH\Box\Test\FileSystemTestCase; +use PHPUnit\Framework\AssertionFailedError; +use Seld\JsonLint\ParsingException; +use stdClass; +use Throwable; +use function get_class; +use function is_object; +use function json_decode; +use function KevinGH\Box\FileSystem\dump_file; + +/** + * @covers \KevinGH\Box\Json\Json + * @requires extension mbstring + */ +class JsonTest extends FileSystemTestCase +{ + /** + * @var Json + */ + private $json; + + /** + * {@inheritdoc} + */ + protected function setUp(): void + { + parent::setUp(); + + $this->json = new Json(); + } + + /** + * @dataProvider provideJsonToLint + */ + public function test_it_can_lint_a_json_string(string $json, ?Throwable $expectedThrowable): void + { + try { + $this->json->lint($json); + + if (null !== $expectedThrowable) { + $this->fail('Expected throwable to be thrown.'); + } + } catch (Throwable $throwable) { + if (null === $expectedThrowable) { + $this->fail('Did not except throwable to be thrown.'); + } + + $this->assertSame(get_class($expectedThrowable), get_class($throwable)); + $this->assertSame($expectedThrowable->getMessage(), $throwable->getMessage()); + + return; + } + + $this->assertTrue(true); + } + + /** + * @dataProvider provideJsonToDecode + * + * @param mixed $expected + */ + public function test_it_can_decode_a_json_string(string $json, bool $assoc, $expected, ?Throwable $expectedThrowable): void + { + if (null === $expected) { + Assertion::notNull($expectedThrowable); + } else { + Assertion::null($expectedThrowable); + } + + try { + $actual = $this->json->decode($json, $assoc); + + if (null !== $expectedThrowable) { + $this->fail('Expected throwable to be thrown.'); + } + } catch (AssertionFailedError $error) { + throw $error; + } catch (Throwable $throwable) { + if (null === $expectedThrowable) { + $this->fail('Did not except throwable to be thrown: '.$throwable->getMessage()); + } + + $this->assertSame(get_class($expectedThrowable), get_class($throwable)); + $this->assertSame($expectedThrowable->getMessage(), $throwable->getMessage()); + + return; + } + + if (is_object($expected)) { + $this->assertEquals($expected, $actual); + } else { + $this->assertSame($expected, $actual); + } + } + + public function test_it_can_decode_a_file(): void + { + dump_file('data.json', '{}'); + + $decoded = $this->json->decodeFile('data.json'); + + $this->assertEquals(new stdClass(), $decoded); + + $decoded = $this->json->decodeFile('data.json', true); + + $this->assertSame([], $decoded); + + dump_file('data.json', ''); + + try { + $this->json->decodeFile('data.json', true); + + $this->fail('Expected exception to be thrown.'); + } catch (ParsingException $exception) { + $this->assertStringStartsWith( + 'Parse error on line 1:', + $exception->getMessage() + ); + } + } + + public function test_it_can_validate_a_file_against_a_schema(): void + { + $schema = json_decode( + <<<'JSON' +{ + "description": "Schema description", + "properties": { + "foo": { + "description": "The foo property", + "type": ["string"] + }, + "bar": { + "description": "The foo property", + "type": ["string"] + } + } +} + +JSON + ); + + touch('data.json'); + + $this->json->validate( + 'data.json', + (function (): stdClass { + $data = new stdClass(); + $data->foo = 'bar'; + + return $data; + })(), + $schema + ); + + try { + $this->json->validate( + 'data.json', + (function (): stdClass { + $data = new stdClass(); + $data->foo = false; + $data->bar = true; + + return $data; + })(), + $schema + ); + + $this->fail('Expected exception to be thrown.'); + } catch (JsonValidationException $exception) { + $this->assertSame( + <<<'EOF' +"data.json" does not match the expected JSON schema: + - foo : Boolean value found, but a string is required + - bar : Boolean value found, but a string is required +EOF + , + $exception->getMessage() + ); + $this->assertSame( + [ + 'foo : Boolean value found, but a string is required', + 'bar : Boolean value found, but a string is required', + ], + $exception->getErrors() + ); + $this->assertSame('data.json', $exception->getValidatedFile()); + $this->assertSame(0, $exception->getCode()); + $this->assertNull($exception->getPrevious()); + } + } + + public function provideJsonToLint() + { + yield ['{}', null]; + + yield [ + '', + new ParsingException( + <<<'EOF' +Parse error on line 1: + +^ +Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[' +EOF + ), + ]; + } + + public function provideJsonToDecode() + { + yield ['{}', true, [], null]; + yield ['{}', false, new stdClass(), null]; + + yield [ + <<<'JSON' +{ + "foo": { + "bar": [], + "baz": ["a", "b"], + "far": {} + } +} +JSON + , + true, + [ + 'foo' => [ + 'bar' => [], + 'baz' => ['a', 'b'], + 'far' => [], + ], + ], + null, + ]; + + yield [ + <<<'JSON' +{ + "foo": { + "bar": [], + "baz": ["a", "b"], + "far": {} + } +} +JSON + , + false, + (function () { + $data = new stdClass(); + $data->foo = new stdClass(); + $data->foo->bar = []; + $data->foo->baz = ['a', 'b']; + $data->foo->far = new stdClass(); + + return $data; + })(), + null, + ]; + + yield [ + '', + true, + null, + new ParsingException( + <<<'EOF' +Parse error on line 1: + +^ +Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[' +EOF + ), + ]; + + yield [ + mb_convert_encoding('ü', 'latin1', 'auto'), + true, + null, + new ParsingException('JSON decoding failed: Malformed UTF-8 characters, possibly incorrectly encoded'), + ]; + + yield [ + "\xEF\xBB\xBF".'{"foo": "bar"}', + true, + null, + new ParsingException('BOM detected, make sure your input does not include a Unicode Byte-Order-Mark'), + ]; + } +} diff --git a/tests/Json/JsonValidationExceptionTest.php b/tests/Json/JsonValidationExceptionTest.php new file mode 100644 index 000000000..9d588fe7c --- /dev/null +++ b/tests/Json/JsonValidationExceptionTest.php @@ -0,0 +1,80 @@ + + * Théo Fidry + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace KevinGH\Box\Json; + +use Error; +use InvalidArgumentException; +use KevinGH\Box\Test\FileSystemTestCase; +use function KevinGH\Box\FileSystem\dump_file; + +/** + * @covers \KevinGH\Box\Json\JsonValidationException + */ +class JsonValidationExceptionTest extends FileSystemTestCase +{ + public function test_it_cannot_be_created_with_a_non_existent_file(): void + { + try { + new JsonValidationException('message', 'unknown file'); + + $this->fail('Expected exception to be thrown'); + } catch (InvalidArgumentException $exception) { + $this->assertSame( + 'File "unknown file" was expected to exist.', + $exception->getMessage() + ); + } + } + + public function test_it_cannot_be_created_with_a_non_valid_errors(): void + { + try { + new JsonValidationException('message', null, [false]); + + $this->fail('Expected exception to be thrown'); + } catch (InvalidArgumentException $exception) { + $this->assertSame( + 'Value "" expected to be string, type boolean given.', + $exception->getMessage() + ); + } + } + + public function test_it_cannot_be_instantiated(): void + { + $message = 'my message'; + + $exception = new JsonValidationException($message); + + $this->assertSame($message, $exception->getMessage()); + $this->assertSame(0, $exception->getCode()); + $this->assertNull($exception->getPrevious()); + $this->assertNull($exception->getValidatedFile()); + $this->assertSame([], $exception->getErrors()); + + dump_file($file = 'dummy_file', ''); + $errors = ['foo', 'bar']; + $code = 10; + $error = new Error(); + + $exception = new JsonValidationException($message, $file, $errors, $code, $error); + + $this->assertSame($message, $exception->getMessage()); + $this->assertSame($code, $exception->getCode()); + $this->assertSame($error, $exception->getPrevious()); + $this->assertSame($file, $exception->getValidatedFile()); + $this->assertSame($errors, $exception->getErrors()); + } +} diff --git a/tests/RequirementChecker/RequirementsDumperTest.php b/tests/RequirementChecker/RequirementsDumperTest.php new file mode 100644 index 000000000..7c04b9e72 --- /dev/null +++ b/tests/RequirementChecker/RequirementsDumperTest.php @@ -0,0 +1,140 @@ + + * Théo Fidry + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace KevinGH\Box\RequirementChecker; + +use Phar; +use PHPUnit\Framework\TestCase; +use function array_column; + +/** + * @covers \KevinGH\Box\RequirementChecker\RequirementsDumper + */ +class RequirementsDumperTest extends TestCase +{ + /** + * @dataProvider provideJsonAndLockContents + */ + public function test_it_dumps_the_requirement_checker_files( + array $decodedComposerJsonContents, + array $decodedComposerLockContents, + ?int $compressionAlgorithm, + string $expectedRequirement + ): void { + $checkFiles = RequirementsDumper::dump($decodedComposerJsonContents, $decodedComposerLockContents, $compressionAlgorithm); + + sort($checkFiles); + + $expectedFiles = [ + '.requirements.php', + 'bin/check-requirements.php', + 'check_requirements.php', + 'composer.json', + 'composer.lock', + 'src/Checker.php', + 'src/IO.php', + 'src/IsExtensionFulfilled.php', + 'src/IsFulfilled.php', + 'src/IsPhpVersionFulfilled.php', + 'src/Printer.php', + 'src/Requirement.php', + 'src/RequirementCollection.php', + 'src/Terminal.php', + 'vendor/autoload.php', + 'vendor/composer/autoload_classmap.php', + 'vendor/composer/autoload_namespaces.php', + 'vendor/composer/autoload_psr4.php', + 'vendor/composer/autoload_real.php', + 'vendor/composer/autoload_static.php', + 'vendor/composer/ClassLoader.php', + 'vendor/composer/installed.json', + 'vendor/composer/LICENSE', + 'vendor/composer/semver/src/Comparator.php', + 'vendor/composer/semver/src/Constraint/AbstractConstraint.php', + 'vendor/composer/semver/src/Constraint/Constraint.php', + 'vendor/composer/semver/src/Constraint/ConstraintInterface.php', + 'vendor/composer/semver/src/Constraint/EmptyConstraint.php', + 'vendor/composer/semver/src/Constraint/MultiConstraint.php', + 'vendor/composer/semver/src/Semver.php', + 'vendor/composer/semver/src/VersionParser.php', + ]; + + sort($expectedFiles); + + $this->assertSame( + $expectedFiles, + array_column($checkFiles, 0) + ); + + $this->assertSame($expectedRequirement, $checkFiles[0][1]); + } + + public function provideJsonAndLockContents() + { + yield [ + [], + [], + null, + <<<'PHP' + [ + [ + 'name' => 'acme/foo', + 'require' => [ + 'php' => '^7.3', + 'ext-json' => '*', + ], + ], + ], + ], + Phar::GZ, + <<<'PHP' + + array ( + 'type' => 'php', + 'condition' => '^7.3', + 'message' => 'The package "acme/foo" requires the version "^7.3" or greater.', + 'helpMessage' => 'The package "acme/foo" requires the version "^7.3" or greater.', + ), + 1 => + array ( + 'type' => 'extension', + 'condition' => 'zlib', + 'message' => 'The application requires the extension "zlib". Enable it or install a polyfill.', + 'helpMessage' => 'The application requires the extension "zlib".', + ), + 2 => + array ( + 'type' => 'extension', + 'condition' => 'json', + 'message' => 'The package "acme/foo" requires the extension "json". Enable it or install a polyfill.', + 'helpMessage' => 'The package "acme/foo" requires the extension "json".', + ), +); +PHP + ]; + } +} diff --git a/tests/Throwable/Exception/NoConfigurationFoundTest.php b/tests/Throwable/Exception/NoConfigurationFoundTest.php new file mode 100644 index 000000000..d6c47ecba --- /dev/null +++ b/tests/Throwable/Exception/NoConfigurationFoundTest.php @@ -0,0 +1,49 @@ + + * Théo Fidry + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace KevinGH\Box\Throwable\Exception; + +use Error; +use PHPUnit\Framework\TestCase; + +/** + * @covers \KevinGH\Box\Throwable\Exception\NoConfigurationFound + */ +class NoConfigurationFoundTest extends TestCase +{ + public function test_it_can_be_created_with_a_default_error_message(): void + { + $exception = new NoConfigurationFound(); + + $this->assertSame( + 'The configuration file could not be found.', + $exception->getMessage() + ); + $this->assertSame(0, $exception->getCode()); + $this->assertNull($exception->getPrevious()); + } + + public function test_it_can_be_created_with_overridden_values(): void + { + $message = 'My message'; + $code = 120; + $error = new Error(); + + $exception = new NoConfigurationFound($message, $code, $error); + + $this->assertSame($message, $exception->getMessage()); + $this->assertSame($code, $exception->getCode()); + $this->assertSame($error, $exception->getPrevious()); + } +}