diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..417392d --- /dev/null +++ b/composer.json @@ -0,0 +1,13 @@ +{ + "require": { + "slim/slim": "^4.8", + "slim/psr7": "^1.5", + "php-di/php-di": "^6.0" + }, + "autoload": { + "psr-4": { + "App\\": "src/" + } + } + } + \ No newline at end of file diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..ecb1cc9 --- /dev/null +++ b/composer.lock @@ -0,0 +1,1000 @@ +{ + "_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": "f27925eac6aff16ca9ab89f53d568cb9", + "packages": [ + { + "name": "fig/http-message-util", + "version": "1.1.5", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message-util.git", + "reference": "9d94dc0154230ac39e5bf89398b324a86f63f765" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message-util/zipball/9d94dc0154230ac39e5bf89398b324a86f63f765", + "reference": "9d94dc0154230ac39e5bf89398b324a86f63f765", + "shasum": "" + }, + "require": { + "php": "^5.3 || ^7.0 || ^8.0" + }, + "suggest": { + "psr/http-message": "The package containing the PSR-7 interfaces" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Fig\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Utility classes and constants for use with PSR-7 (psr/http-message)", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "issues": "https://github.com/php-fig/http-message-util/issues", + "source": "https://github.com/php-fig/http-message-util/tree/1.1.5" + }, + "time": "2020-11-24T22:02:12+00:00" + }, + { + "name": "laravel/serializable-closure", + "version": "v1.3.7", + "source": { + "type": "git", + "url": "https://github.com/laravel/serializable-closure.git", + "reference": "4f48ade902b94323ca3be7646db16209ec76be3d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/4f48ade902b94323ca3be7646db16209ec76be3d", + "reference": "4f48ade902b94323ca3be7646db16209ec76be3d", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0" + }, + "require-dev": { + "illuminate/support": "^8.0|^9.0|^10.0|^11.0", + "nesbot/carbon": "^2.61|^3.0", + "pestphp/pest": "^1.21.3", + "phpstan/phpstan": "^1.8.2", + "symfony/var-dumper": "^5.4.11|^6.2.0|^7.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Laravel\\SerializableClosure\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + }, + { + "name": "Nuno Maduro", + "email": "nuno@laravel.com" + } + ], + "description": "Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.", + "keywords": [ + "closure", + "laravel", + "serializable" + ], + "support": { + "issues": "https://github.com/laravel/serializable-closure/issues", + "source": "https://github.com/laravel/serializable-closure" + }, + "time": "2024-11-14T18:34:49+00:00" + }, + { + "name": "nikic/fast-route", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/FastRoute.git", + "reference": "181d480e08d9476e61381e04a71b34dc0432e812" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/FastRoute/zipball/181d480e08d9476e61381e04a71b34dc0432e812", + "reference": "181d480e08d9476e61381e04a71b34dc0432e812", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35|~5.7" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "FastRoute\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "description": "Fast request router for PHP", + "keywords": [ + "router", + "routing" + ], + "support": { + "issues": "https://github.com/nikic/FastRoute/issues", + "source": "https://github.com/nikic/FastRoute/tree/master" + }, + "time": "2018-02-13T20:26:39+00:00" + }, + { + "name": "php-di/invoker", + "version": "2.3.6", + "source": { + "type": "git", + "url": "https://github.com/PHP-DI/Invoker.git", + "reference": "59f15608528d8a8838d69b422a919fd6b16aa576" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-DI/Invoker/zipball/59f15608528d8a8838d69b422a919fd6b16aa576", + "reference": "59f15608528d8a8838d69b422a919fd6b16aa576", + "shasum": "" + }, + "require": { + "php": ">=7.3", + "psr/container": "^1.0|^2.0" + }, + "require-dev": { + "athletic/athletic": "~0.1.8", + "mnapoli/hard-mode": "~0.3.0", + "phpunit/phpunit": "^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Invoker\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Generic and extensible callable invoker", + "homepage": "https://github.com/PHP-DI/Invoker", + "keywords": [ + "callable", + "dependency", + "dependency-injection", + "injection", + "invoke", + "invoker" + ], + "support": { + "issues": "https://github.com/PHP-DI/Invoker/issues", + "source": "https://github.com/PHP-DI/Invoker/tree/2.3.6" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + } + ], + "time": "2025-01-17T12:49:27+00:00" + }, + { + "name": "php-di/php-di", + "version": "6.4.0", + "source": { + "type": "git", + "url": "https://github.com/PHP-DI/PHP-DI.git", + "reference": "ae0f1b3b03d8b29dff81747063cbfd6276246cc4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-DI/PHP-DI/zipball/ae0f1b3b03d8b29dff81747063cbfd6276246cc4", + "reference": "ae0f1b3b03d8b29dff81747063cbfd6276246cc4", + "shasum": "" + }, + "require": { + "laravel/serializable-closure": "^1.0", + "php": ">=7.4.0", + "php-di/invoker": "^2.0", + "php-di/phpdoc-reader": "^2.0.1", + "psr/container": "^1.0" + }, + "provide": { + "psr/container-implementation": "^1.0" + }, + "require-dev": { + "doctrine/annotations": "~1.10", + "friendsofphp/php-cs-fixer": "^2.4", + "mnapoli/phpunit-easymock": "^1.2", + "ocramius/proxy-manager": "^2.11.2", + "phpstan/phpstan": "^0.12", + "phpunit/phpunit": "^9.5" + }, + "suggest": { + "doctrine/annotations": "Install it if you want to use annotations (version ~1.2)", + "ocramius/proxy-manager": "Install it if you want to use lazy injection (version ~2.0)" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "DI\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "The dependency injection container for humans", + "homepage": "https://php-di.org/", + "keywords": [ + "PSR-11", + "container", + "container-interop", + "dependency injection", + "di", + "ioc", + "psr11" + ], + "support": { + "issues": "https://github.com/PHP-DI/PHP-DI/issues", + "source": "https://github.com/PHP-DI/PHP-DI/tree/6.4.0" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/php-di/php-di", + "type": "tidelift" + } + ], + "time": "2022-04-09T16:46:38+00:00" + }, + { + "name": "php-di/phpdoc-reader", + "version": "2.2.1", + "source": { + "type": "git", + "url": "https://github.com/PHP-DI/PhpDocReader.git", + "reference": "66daff34cbd2627740ffec9469ffbac9f8c8185c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-DI/PhpDocReader/zipball/66daff34cbd2627740ffec9469ffbac9f8c8185c", + "reference": "66daff34cbd2627740ffec9469ffbac9f8c8185c", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "require-dev": { + "mnapoli/hard-mode": "~0.3.0", + "phpunit/phpunit": "^8.5|^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "PhpDocReader\\": "src/PhpDocReader" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PhpDocReader parses @var and @param values in PHP docblocks (supports namespaced class names with the same resolution rules as PHP)", + "keywords": [ + "phpdoc", + "reflection" + ], + "support": { + "issues": "https://github.com/PHP-DI/PhpDocReader/issues", + "source": "https://github.com/PHP-DI/PhpDocReader/tree/2.2.1" + }, + "time": "2020-10-12T12:39:22+00:00" + }, + { + "name": "psr/container", + "version": "1.1.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/513e0666f7216c7459170d56df27dfcefe1689ea", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/1.1.2" + }, + "time": "2021-11-05T16:50:12+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory" + }, + "time": "2024-04-15T12:06:14+00:00" + }, + { + "name": "psr/http-message", + "version": "2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "time": "2023-04-04T09:54:51+00:00" + }, + { + "name": "psr/http-server-handler", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-server-handler.git", + "reference": "84c4fb66179be4caaf8e97bd239203245302e7d4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-server-handler/zipball/84c4fb66179be4caaf8e97bd239203245302e7d4", + "reference": "84c4fb66179be4caaf8e97bd239203245302e7d4", + "shasum": "" + }, + "require": { + "php": ">=7.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP server-side request handler", + "keywords": [ + "handler", + "http", + "http-interop", + "psr", + "psr-15", + "psr-7", + "request", + "response", + "server" + ], + "support": { + "source": "https://github.com/php-fig/http-server-handler/tree/1.0.2" + }, + "time": "2023-04-10T20:06:20+00:00" + }, + { + "name": "psr/http-server-middleware", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-server-middleware.git", + "reference": "c1481f747daaa6a0782775cd6a8c26a1bf4a3829" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-server-middleware/zipball/c1481f747daaa6a0782775cd6a8c26a1bf4a3829", + "reference": "c1481f747daaa6a0782775cd6a8c26a1bf4a3829", + "shasum": "" + }, + "require": { + "php": ">=7.0", + "psr/http-message": "^1.0 || ^2.0", + "psr/http-server-handler": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP server-side middleware", + "keywords": [ + "http", + "http-interop", + "middleware", + "psr", + "psr-15", + "psr-7", + "request", + "response" + ], + "support": { + "issues": "https://github.com/php-fig/http-server-middleware/issues", + "source": "https://github.com/php-fig/http-server-middleware/tree/1.0.2" + }, + "time": "2023-04-11T06:14:47+00:00" + }, + { + "name": "psr/log", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "time": "2024-09-11T13:17:53+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "time": "2019-03-08T08:55:37+00:00" + }, + { + "name": "slim/psr7", + "version": "1.7.0", + "source": { + "type": "git", + "url": "https://github.com/slimphp/Slim-Psr7.git", + "reference": "753e9646def5ff4db1a06e5cf4ef539bfd30f467" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/Slim-Psr7/zipball/753e9646def5ff4db1a06e5cf4ef539bfd30f467", + "reference": "753e9646def5ff4db1a06e5cf4ef539bfd30f467", + "shasum": "" + }, + "require": { + "fig/http-message-util": "^1.1.5", + "php": "^8.0", + "psr/http-factory": "^1.1", + "psr/http-message": "^1.0 || ^2.0", + "ralouphie/getallheaders": "^3.0", + "symfony/polyfill-php80": "^1.29" + }, + "provide": { + "psr/http-factory-implementation": "^1.0", + "psr/http-message-implementation": "^1.0 || ^2.0" + }, + "require-dev": { + "adriansuter/php-autoload-override": "^1.4", + "ext-json": "*", + "http-interop/http-factory-tests": "^1.1.0", + "php-http/psr7-integration-tests": "1.3.0", + "phpspec/prophecy": "^1.19", + "phpspec/prophecy-phpunit": "^2.2", + "phpstan/phpstan": "^1.11", + "phpunit/phpunit": "^9.6", + "squizlabs/php_codesniffer": "^3.10" + }, + "type": "library", + "autoload": { + "psr-4": { + "Slim\\Psr7\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "http://joshlockhart.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" + }, + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, + { + "name": "Pierre Berube", + "email": "pierre@lgse.com", + "homepage": "http://www.lgse.com" + } + ], + "description": "Strict PSR-7 implementation", + "homepage": "https://www.slimframework.com", + "keywords": [ + "http", + "psr-7", + "psr7" + ], + "support": { + "issues": "https://github.com/slimphp/Slim-Psr7/issues", + "source": "https://github.com/slimphp/Slim-Psr7/tree/1.7.0" + }, + "time": "2024-06-08T14:48:17+00:00" + }, + { + "name": "slim/slim", + "version": "4.14.0", + "source": { + "type": "git", + "url": "https://github.com/slimphp/Slim.git", + "reference": "5943393b88716eb9e82c4161caa956af63423913" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/Slim/zipball/5943393b88716eb9e82c4161caa956af63423913", + "reference": "5943393b88716eb9e82c4161caa956af63423913", + "shasum": "" + }, + "require": { + "ext-json": "*", + "nikic/fast-route": "^1.3", + "php": "^7.4 || ^8.0", + "psr/container": "^1.0 || ^2.0", + "psr/http-factory": "^1.1", + "psr/http-message": "^1.1 || ^2.0", + "psr/http-server-handler": "^1.0", + "psr/http-server-middleware": "^1.0", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "require-dev": { + "adriansuter/php-autoload-override": "^1.4", + "ext-simplexml": "*", + "guzzlehttp/psr7": "^2.6", + "httpsoft/http-message": "^1.1", + "httpsoft/http-server-request": "^1.1", + "laminas/laminas-diactoros": "^2.17 || ^3", + "nyholm/psr7": "^1.8", + "nyholm/psr7-server": "^1.1", + "phpspec/prophecy": "^1.19", + "phpspec/prophecy-phpunit": "^2.1", + "phpstan/phpstan": "^1.11", + "phpunit/phpunit": "^9.6", + "slim/http": "^1.3", + "slim/psr7": "^1.6", + "squizlabs/php_codesniffer": "^3.10", + "vimeo/psalm": "^5.24" + }, + "suggest": { + "ext-simplexml": "Needed to support XML format in BodyParsingMiddleware", + "ext-xml": "Needed to support XML format in BodyParsingMiddleware", + "php-di/php-di": "PHP-DI is the recommended container library to be used with Slim", + "slim/psr7": "Slim PSR-7 implementation. See https://www.slimframework.com/docs/v4/start/installation.html for more information." + }, + "type": "library", + "autoload": { + "psr-4": { + "Slim\\": "Slim" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "https://joshlockhart.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" + }, + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, + { + "name": "Pierre Berube", + "email": "pierre@lgse.com", + "homepage": "http://www.lgse.com" + }, + { + "name": "Gabriel Manricks", + "email": "gmanricks@me.com", + "homepage": "http://gabrielmanricks.com" + } + ], + "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", + "homepage": "https://www.slimframework.com", + "keywords": [ + "api", + "framework", + "micro", + "router" + ], + "support": { + "docs": "https://www.slimframework.com/docs/v4/", + "forum": "https://discourse.slimframework.com/", + "irc": "irc://irc.freenode.net:6667/slimphp", + "issues": "https://github.com/slimphp/Slim/issues", + "rss": "https://www.slimframework.com/blog/feed.rss", + "slack": "https://slimphp.slack.com/", + "source": "https://github.com/slimphp/Slim", + "wiki": "https://github.com/slimphp/Slim/wiki" + }, + "funding": [ + { + "url": "https://opencollective.com/slimphp", + "type": "open_collective" + }, + { + "url": "https://tidelift.com/funding/github/packagist/slim/slim", + "type": "tidelift" + } + ], + "time": "2024-06-13T08:54:48+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.31.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.31.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": {}, + "platform-dev": {}, + "plugin-api-version": "2.6.0" +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..7991d9e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,29 @@ +version: '3.8' + +services: + db: + image: postgres:13 + container_name: my_api_db + restart: always + environment: + POSTGRES_DB: dbwikifantasy + POSTGRES_USER: postgres + POSTGRES_PASSWORD: sucepute + volumes: + - ./init.sql:/docker-entrypoint-initdb.d/init.sql + ports: + - "5432:5432" + + app: + build: . + container_name: my_api_app + restart: always + depends_on: + - db + environment: + DB_HOST: db + DB_NAME: dbwikifantasy + DB_USER: postgres + DB_PASSWORD: sucepute + ports: + - "8080:80" diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..faee294 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,22 @@ +FROM php:8.1-apache + +# Installation de l'extension PDO PostgreSQL +RUN docker-php-ext-install pdo pdo_pgsql + +# Installer Composer depuis l'image officielle Composer +COPY --from=composer:latest /usr/bin/composer /usr/bin/composer + +# Définir le répertoire de travail +WORKDIR /var/www/html + +# Copier le fichier de composer et installer les dépendances +COPY composer.json composer.lock ./ +RUN composer install + +# Copier l'ensemble du projet dans le conteneur +COPY . /var/www/html + +# Ajuster les droits sur les fichiers (si nécessaire) +RUN chown -R www-data:www-data /var/www/html + +EXPOSE 80 diff --git a/init.sql b/init.sql new file mode 100644 index 0000000..fa09796 --- /dev/null +++ b/init.sql @@ -0,0 +1,329 @@ +-- Suppression des tables +DROP TABLE IF EXISTS Commentary; +DROP TABLE IF EXISTS Favorite; +DROP TABLE IF EXISTS DailyQuote; +DROP TABLE IF EXISTS Quote; +DROP TABLE IF EXISTS Caracter; +DROP TABLE IF EXISTS Source; +DROP TABLE IF EXISTS Record_quiz; +DROP TABLE IF EXISTS Quiz_Question; +DROP TABLE IF EXISTS Quiz; +DROP TABLE IF EXISTS Question; +DROP TABLE IF EXISTS Admin; +DROP TABLE IF EXISTS Users; +DROP TABLE IF EXISTS Image; + +-- Création des tables +------------------------------------------------------------------------- + +CREATE TABLE Image( + id_img NUMERIC PRIMARY KEY, + imgPath varchar(300) NOT NULL UNIQUE +); + +------------------------------------------------------------------------- + +CREATE TABLE Users( + id_user SERIAL PRIMARY KEY, + username varchar(50) NOT NULL, + email varchar(50) NOT NULL, + password varchar(100) NOT NULL, + img NUMERIC NOT NULL, + creation date NOT NULL, + CONSTRAINT unique_col UNIQUE (email), + CONSTRAINT fk_img FOREIGN KEY(img) REFERENCES Image(id_img) +); + +Create OR REPLACE Function IfUserIsAdmin() RETURNS trigger AS $$ +DECLARE + +BEGIN + Delete From Admin + where users = OLD.id_user; + + RETURN OLD; +END; +$$ LANGUAGE plpgsql ; + +Create Trigger IfUserIsAdmin BEFORE DELETE on Users +FOR EACH ROW +EXECUTE FUNCTION IfUserIsAdmin(); + +Create OR REPLACE Function DeleteUserFavorite() RETURNS trigger AS $$ +DECLARE + +BEGIN + Delete From Favorite + where users = OLD.id_user; + + RETURN OLD; +END; +$$ LANGUAGE plpgsql ; + +Create Trigger DeleteUserFavorite BEFORE DELETE on Users +FOR EACH ROW +EXECUTE FUNCTION DeleteUserFavorite(); + +Create OR REPLACE Function DeleteUserCommentary() RETURNS trigger AS $$ +DECLARE + +BEGIN + Delete From Commentary + where users = OLD.id_user; + + RETURN OLD; +END; +$$ LANGUAGE plpgsql ; + +Create Trigger DeleteUserCommentary BEFORE DELETE on Users +FOR EACH ROW +EXECUTE FUNCTION DeleteUserCommentary(); +------------------------------------------------------------------------- + +CREATE TABLE Admin( + users SERIAL PRIMARY KEY, + CONSTRAINT fk_user FOREIGN KEY(users) REFERENCES Users(id_user) +); + +------------------------------------------------------------------------- + +CREATE TABLE Question( + id_question SERIAL PRIMARY KEY, + texte text NOT NULL UNIQUE, + answerA varchar(30) NOT NULL, + answerB varchar(30) NOT NULL, + answerC varchar(30) NOT NULL, + answerD varchar(30) NOT NULL, + cAnswer varchar(30) NOT NULL, + CONSTRAINT check_cAnswer CHECK (cAnswer = answerA OR cAnswer = answerB OR cAnswer = answerC OR cAnswer = answerD) +); + +------------------------------------------------------------------------- + +CREATE TABLE Quiz( + id_quiz SERIAL PRIMARY KEY, + title varchar(40) NOT NULL, + img NUMERIC NOT NULL, + nb_quest numeric Default 0, + CONSTRAINT fk_img FOREIGN KEY(img) REFERENCES Image(id_img) +); + +Create OR REPLACE Function DeleteQuiz() RETURNS trigger AS $$ +DECLARE + +BEGIN + Delete From Quiz_Question + where quiz=OLD.id_quiz; + + Delete From Record_quiz + where quiz=OLD.id_quiz; +END; +$$ LANGUAGE plpgsql ; + +Create Trigger DeleteQuiz BEFORE DELETE on Quiz +FOR EACH ROW +EXECUTE FUNCTION DeleteQuiz(); +------------------------------------------------------------------------- + +CREATE TABLE Quiz_Question( + quiz SERIAL NOT NULL, + question SERIAL NOT NULL, + PRIMARY KEY (quiz, question), + CONSTRAINT fk_quiz FOREIGN KEY(quiz) REFERENCES Quiz(id_quiz), + CONSTRAINT fk_question FOREIGN KEY(question) REFERENCES Question(id_question) +); + +Create OR REPLACE Function NombreQuestionQuiz() RETURNS trigger AS $$ +DECLARE + nb numeric; +BEGIN + + IF TG_OP='DELETE' Then + SELECT count(quiz) INTO nb + FROM Quiz_Question + WHERE quiz = OLD.quiz; + Else + SELECT count(quiz) INTO nb + FROM Quiz_Question + WHERE quiz = NEW.quiz; + End IF; + + + Update Quiz + set nb_quest=nb + where id_quiz=NEW.quiz; + + Return OLD; +END; +$$ LANGUAGE plpgsql ; + +Create Trigger NombreQuestionQuiz AFTER INSERT or UPDATE or DELETE on Quiz_Question +FOR EACH ROW +EXECUTE FUNCTION NombreQuestionQuiz(); + +------------------------------------------------------------------------- + +CREATE TABLE Record_quiz( + users SERIAL NOT NULL, + quiz SERIAL NOT NULL, + nbPoint numeric DEFAULT 0, + timeQ numeric DEFAULT 0, + PRIMARY KEY (users, quiz), + CONSTRAINT fk_user FOREIGN KEY(users) REFERENCES Users(id_user), + CONSTRAINT fk_quiz FOREIGN KEY(quiz) REFERENCES Quiz(id_quiz), + CONSTRAINT err_nbPoint CHECK(nbPoint >= 0), + CONSTRAINT err_timeQ CHECK(timeQ >= 0) +); + +------------------------------------------------------------------------- + +CREATE TABLE Source( + id_source SERIAL PRIMARY KEY, + title varchar(100) NOT NULL, + dateS numeric(4) NOT NULL +); + +------------------------------------------------------------------------- + +CREATE TABLE Caracter( + id_caracter SERIAL PRIMARY KEY, + caracter varchar(100) NOT NULL, + id_img NUMERIC NOT NULL +); + +------------------------------------------------------------------------- + +CREATE TABLE Quote( + id_quote SERIAL PRIMARY KEY, + content text NOT NULL, + likes numeric DEFAULT '0', + langue char(2) NOT NULL, + isValide boolean NOT NULL DEFAULT 'false', + reason varchar(100) NOT NULL, + id_caracter SERIAL NOT NULL, + id_source SERIAL NOT NULL, + id_user_verif SERIAL NOT NULL, + CONSTRAINT fk_caracter FOREIGN KEY(id_caracter) REFERENCES Caracter(id_caracter), + CONSTRAINT fk_source FOREIGN KEY(id_source) REFERENCES Source(id_source), + CONSTRAINT fk_userverif FOREIGN KEY(id_user_verif) REFERENCES Users(id_user), + CONSTRAINT err_nbLike CHECK (likes >= 0), + CONSTRAINT err_language CHECK (langue = 'fr' OR langue = 'en') +); + +Create OR REPLACE Function DeleteQuoteBEFORE() RETURNS trigger AS $$ +DECLARE + +BEGIN + Delete From Favorite + where quote=OLD.id_quote; + + + Delete From Commentary + where quote=OLD.id_quote; + + + If OLD.id_quote in (Select citation_id From DailyQuote) Then + Update DailyQuote + set citation_id = (Select id_quote + From Quote + Where id_quote!=OLD.id_quote + ORDER BY RAND() + LIMIT 1) + Where citation_id=OLD.id_quote; + END IF; + + Return OLD; +END; +$$ LANGUAGE plpgsql ; + +Create Trigger DeleteQuoteBEFORE BEFORE DELETE on Quote +FOR EACH ROW +EXECUTE FUNCTION DeleteQuoteBEFORE(); + +Create OR REPLACE Function DeleteQuoteAFTER() RETURNS trigger AS $$ +DECLARE + nb numeric; +BEGIN + Select count(id_caracter) into nb + from Quote + where id_caracter=OLD.id_caracter; + + IF nb <= 1 Then + Delete from Caracter + where id_caracter=OLD.id_caracter; + END IF; + + + Select count(id_source) into nb + from Quote + where id_source=OLD.id_source; + + IF nb <= 1 Then + Delete from Source + where id_source=OLD.id_source; + END IF; + + Return OLD; +END; +$$ LANGUAGE plpgsql ; + +Create Trigger DeleteQuoteAFTER AFTER DELETE on Quote +FOR EACH ROW +EXECUTE FUNCTION DeleteQuoteAFTER(); + +------------------------------------------------------------------------- + +CREATE TABLE DailyQuote( + citation_id INT PRIMARY KEY, + FOREIGN KEY (citation_id) REFERENCES Quote(id_quote) ON DELETE CASCADE +); + +Create OR REPLACE Function UniqueDailyQuote() RETURNS trigger AS $$ +DECLARE + nb numeric; +BEGIN + Select count(*) into nb + from DailyQuote; + + IF nb = 0 Then + INSERT INTO DailyQuote (citation_id) + VALUES( (Select id_quote + From Quote + Where id_quote!=OLD.id_quote + ORDER BY RAND() + LIMIT 1 ) ); + + ELSIF nb>1 then + + DELETE From DailyQuote + where citation_id!=NEW.citation_id; + END IF; + RETURN OLD; +END; +$$ LANGUAGE plpgsql ; + +Create Trigger UniqueDailyQuote AFTER INSERT or DELETE on DailyQuote +FOR EACH ROW +EXECUTE FUNCTION UniqueDailyQuote(); + +------------------------------------------------------------------------- + +CREATE TABLE Favorite( + users SERIAL NOT NULL, + quote SERIAL NOT NULL, + PRIMARY KEY (users, quote), + CONSTRAINT fk_quote FOREIGN KEY(quote) REFERENCES Quote(id_quote), + CONSTRAINT fk_user FOREIGN KEY(users) REFERENCES Users(id_user) +); + +------------------------------------------------------------------------- + +CREATE TABLE Commentary( + id_comment SERIAL PRIMARY KEY, + quote SERIAL NOT NULL, + users SERIAL NOT NULL, + dateC date NOT NULL, + comment text NOT NULL, + CONSTRAINT fk_quote FOREIGN KEY(quote) REFERENCES Quote(id_quote), + CONSTRAINT fk_user FOREIGN KEY(users) REFERENCES Users(id_user) +); diff --git a/public/index.php b/public/index.php new file mode 100644 index 0000000..dd7cab4 --- /dev/null +++ b/public/index.php @@ -0,0 +1,16 @@ +run(); diff --git a/src/controllers/ImageController.php b/src/controllers/ImageController.php new file mode 100644 index 0000000..4045529 --- /dev/null +++ b/src/controllers/ImageController.php @@ -0,0 +1,66 @@ +db = $container->get('db'); + } + + // Récupérer toutes les images + public function getImages(Request $request, Response $response, $args) { + $sql = "SELECT * FROM Image"; + try { + $stmt = $this->db->query($sql); + $images = $stmt->fetchAll(\PDO::FETCH_OBJ); + $payload = json_encode($images); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Récupérer une image par son ID + public function getImage(Request $request, Response $response, $args) { + $id = $args['id']; + $sql = "SELECT * FROM Image WHERE id_img = :id"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("id", $id); + $stmt->execute(); + $image = $stmt->fetch(\PDO::FETCH_OBJ); + if(!$image){ + $payload = json_encode(['message' => 'Image not found']); + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json')->withStatus(404); + } + $payload = json_encode($image); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Créer une nouvelle image + public function createImage(Request $request, Response $response, $args) { + $data = $request->getParsedBody(); + $sql = "INSERT INTO Image (imgPath) VALUES (:imgPath)"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("imgPath", $data['imgPath']); + $stmt->execute(); + $data['id_img'] = $this->db->lastInsertId(); + $payload = json_encode($data); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } +} diff --git a/src/controllers/QuizController.php b/src/controllers/QuizController.php new file mode 100644 index 0000000..eb937fb --- /dev/null +++ b/src/controllers/QuizController.php @@ -0,0 +1,84 @@ +db = $container->get('db'); + } + + // Récupérer tous les quiz + public function getQuizzes(Request $request, Response $response, $args) { + $sql = "SELECT * FROM Quiz"; + try { + $stmt = $this->db->query($sql); + $quizzes = $stmt->fetchAll(\PDO::FETCH_OBJ); + $payload = json_encode($quizzes); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Récupérer un quiz par son ID + public function getQuiz(Request $request, Response $response, $args) { + $id = $args['id']; + $sql = "SELECT * FROM Quiz WHERE id_quiz = :id"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("id", $id); + $stmt->execute(); + $quiz = $stmt->fetch(\PDO::FETCH_OBJ); + if(!$quiz){ + $payload = json_encode(['message' => 'Quiz not found']); + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json')->withStatus(404); + } + $payload = json_encode($quiz); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Créer un nouveau quiz + public function createQuiz(Request $request, Response $response, $args) { + $data = $request->getParsedBody(); + $sql = "INSERT INTO Quiz (title, img, nb_quest) VALUES (:title, :img, :nb_quest)"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("title", $data['title']); + $stmt->bindParam("img", $data['img']); + $stmt->bindParam("nb_quest", $data['nb_quest']); + $stmt->execute(); + $data['id_quiz'] = $this->db->lastInsertId(); + $payload = json_encode($data); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Supprimer un quiz + public function deleteQuiz(Request $request, Response $response, $args) { + $id = $args['id']; + $sql = "DELETE FROM Quiz WHERE id_quiz = :id"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("id", $id); + $stmt->execute(); + $payload = json_encode(['message' => 'Quiz deleted']); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } +} diff --git a/src/controllers/QuoteController.php b/src/controllers/QuoteController.php new file mode 100644 index 0000000..b60e077 --- /dev/null +++ b/src/controllers/QuoteController.php @@ -0,0 +1,89 @@ +db = $container->get('db'); + } + + // Récupérer toutes les citations + public function getQuotes(Request $request, Response $response, $args) { + $sql = "SELECT * FROM Quote"; + try { + $stmt = $this->db->query($sql); + $quotes = $stmt->fetchAll(\PDO::FETCH_OBJ); + $payload = json_encode($quotes); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Récupérer une citation par son ID + public function getQuote(Request $request, Response $response, $args) { + $id = $args['id']; + $sql = "SELECT * FROM Quote WHERE id_quote = :id"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("id", $id); + $stmt->execute(); + $quote = $stmt->fetch(\PDO::FETCH_OBJ); + if(!$quote){ + $payload = json_encode(['message' => 'Quote not found']); + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json')->withStatus(404); + } + $payload = json_encode($quote); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Créer une nouvelle citation + public function createQuote(Request $request, Response $response, $args) { + $data = $request->getParsedBody(); + $sql = "INSERT INTO Quote (content, likes, langue, isValide, reason, id_caracter, id_source, id_user_verif) VALUES (:content, :likes, :langue, :isValide, :reason, :id_caracter, :id_source, :id_user_verif)"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("content", $data['content']); + $stmt->bindParam("likes", $data['likes']); + $stmt->bindParam("langue", $data['langue']); + $stmt->bindParam("isValide", $data['isValide']); + $stmt->bindParam("reason", $data['reason']); + $stmt->bindParam("id_caracter", $data['id_caracter']); + $stmt->bindParam("id_source", $data['id_source']); + $stmt->bindParam("id_user_verif", $data['id_user_verif']); + $stmt->execute(); + $data['id_quote'] = $this->db->lastInsertId(); + $payload = json_encode($data); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Supprimer une citation + public function deleteQuote(Request $request, Response $response, $args) { + $id = $args['id']; + $sql = "DELETE FROM Quote WHERE id_quote = :id"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("id", $id); + $stmt->execute(); + $payload = json_encode(['message' => 'Quote deleted']); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } +} diff --git a/src/controllers/UserController.php b/src/controllers/UserController.php new file mode 100644 index 0000000..9c162a9 --- /dev/null +++ b/src/controllers/UserController.php @@ -0,0 +1,108 @@ +db = $container->get('db'); + } + + // Récupérer tous les utilisateurs + public function getUsers(Request $request, Response $response, $args) { + $sql = "SELECT * FROM Users"; + try { + $stmt = $this->db->query($sql); + $users = $stmt->fetchAll(\PDO::FETCH_OBJ); + $payload = json_encode($users); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Récupérer un utilisateur par son ID + public function getUser(Request $request, Response $response, $args) { + $id = $args['id']; + $sql = "SELECT * FROM Users WHERE id_user = :id"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("id", $id); + $stmt->execute(); + $user = $stmt->fetch(\PDO::FETCH_OBJ); + if(!$user){ + $payload = json_encode(['message' => 'User not found']); + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json')->withStatus(404); + } + $payload = json_encode($user); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Créer un nouvel utilisateur + public function createUser(Request $request, Response $response, $args) { + $data = $request->getParsedBody(); + $sql = "INSERT INTO Users (username, email, password, img, creation) VALUES (:username, :email, :password, :img, :creation)"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("username", $data['username']); + $stmt->bindParam("email", $data['email']); + $stmt->bindParam("password", $data['password']); + $stmt->bindParam("img", $data['img']); + $stmt->bindParam("creation", $data['creation']); + $stmt->execute(); + $data['id_user'] = $this->db->lastInsertId(); + $payload = json_encode($data); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Mettre à jour un utilisateur + public function updateUser(Request $request, Response $response, $args) { + $id = $args['id']; + $data = $request->getParsedBody(); + $sql = "UPDATE Users SET username = :username, email = :email, password = :password, img = :img, creation = :creation WHERE id_user = :id"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("username", $data['username']); + $stmt->bindParam("email", $data['email']); + $stmt->bindParam("password", $data['password']); + $stmt->bindParam("img", $data['img']); + $stmt->bindParam("creation", $data['creation']); + $stmt->bindParam("id", $id); + $stmt->execute(); + $payload = json_encode(['message' => 'User updated']); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } + + // Supprimer un utilisateur + public function deleteUser(Request $request, Response $response, $args) { + $id = $args['id']; + $sql = "DELETE FROM Users WHERE id_user = :id"; + try { + $stmt = $this->db->prepare($sql); + $stmt->bindParam("id", $id); + $stmt->execute(); + $payload = json_encode(['message' => 'User deleted']); + } catch (\PDOException $e) { + $payload = json_encode(['error' => $e->getMessage()]); + } + $response->getBody()->write($payload); + return $response->withHeader('Content-Type', 'application/json'); + } +} diff --git a/src/dependencies.php b/src/dependencies.php new file mode 100644 index 0000000..c3ae4b2 --- /dev/null +++ b/src/dependencies.php @@ -0,0 +1,24 @@ +getContainer(); + +$container->set(UserController::class, function($container) { + return new UserController($container); +}); + +$container->set(ImageController::class, function($container) { + return new ImageController($container); +}); + +$container->set(QuoteController::class, function($container) { + return new QuoteController($container); +}); + +$container->set(QuizController::class, function($container) { + return new QuizController($container); +}); diff --git a/src/routes.php b/src/routes.php new file mode 100644 index 0000000..1bb24f2 --- /dev/null +++ b/src/routes.php @@ -0,0 +1,39 @@ +group('/users', function (RouteCollectorProxy $group) { + $group->get('', UserController::class . ':getUsers'); + $group->get('/{id}', UserController::class . ':getUser'); + $group->post('', UserController::class . ':createUser'); + $group->put('/{id}', UserController::class . ':updateUser'); + $group->delete('/{id}', UserController::class . ':deleteUser'); +}); + +// Routes pour les Images +$app->group('/images', function (RouteCollectorProxy $group) { + $group->get('', ImageController::class . ':getImages'); + $group->get('/{id}', ImageController::class . ':getImage'); + $group->post('', ImageController::class . ':createImage'); +}); + +// Routes pour les Quotes +$app->group('/quotes', function (RouteCollectorProxy $group) { + $group->get('', QuoteController::class . ':getQuotes'); + $group->get('/{id}', QuoteController::class . ':getQuote'); + $group->post('', QuoteController::class . ':createQuote'); + $group->delete('/{id}', QuoteController::class . ':deleteQuote'); +}); + +// Routes pour les Quizzes +$app->group('/quizzes', function (RouteCollectorProxy $group) { + $group->get('', QuizController::class . ':getQuizzes'); + $group->get('/{id}', QuizController::class . ':getQuiz'); + $group->post('', QuizController::class . ':createQuiz'); + $group->delete('/{id}', QuizController::class . ':deleteQuiz'); +}); diff --git a/src/settings.php b/src/settings.php new file mode 100644 index 0000000..77cfaa7 --- /dev/null +++ b/src/settings.php @@ -0,0 +1,20 @@ +getContainer(); + +$container->set('db', function () { + // On récupère les paramètres depuis les variables d'environnement + $host = getenv('DB_HOST') ?: 'db'; + $dbname = getenv('DB_NAME') ?: 'dbwikifantasy'; + $user = getenv('DB_USER') ?: 'postgres'; + $pass = getenv('DB_PASSWORD') ?: 'sucepute'; + $dsn = "pgsql:host=$host;dbname=$dbname"; + + try { + $pdo = new PDO($dsn, $user, $pass); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + return $pdo; + } catch (PDOException $e) { + die('Database connection failed: ' . $e->getMessage()); + } +}); diff --git a/vendor/autoload.php b/vendor/autoload.php new file mode 100644 index 0000000..be3ac91 --- /dev/null +++ b/vendor/autoload.php @@ -0,0 +1,25 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var string|null */ + private $vendorDir; + + // PSR-4 + /** + * @var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var list + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * List of PSR-0 prefixes + * + * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) + * + * @var array>> + */ + private $prefixesPsr0 = array(); + /** + * @var list + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var array + */ + private $missingClasses = array(); + + /** @var string|null */ + private $apcuPrefix; + + /** + * @var array + */ + private static $registeredLoaders = array(); + + /** + * @param string|null $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return array> + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return list + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return list + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return array Array of classname => path + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders keyed by their corresponding vendor directories. + * + * @return array + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php new file mode 100644 index 0000000..51e734a --- /dev/null +++ b/vendor/composer/InstalledVersions.php @@ -0,0 +1,359 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array()) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..5490b88 --- /dev/null +++ b/vendor/composer/autoload_classmap.php @@ -0,0 +1,15 @@ + $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', +); diff --git a/vendor/composer/autoload_files.php b/vendor/composer/autoload_files.php new file mode 100644 index 0000000..623ee39 --- /dev/null +++ b/vendor/composer/autoload_files.php @@ -0,0 +1,13 @@ + $vendorDir . '/nikic/fast-route/src/functions.php', + '7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', + 'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php', + 'b33e3d135e5d9e47d845c576147bda89' => $vendorDir . '/php-di/php-di/src/functions.php', +); diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..15a2ff3 --- /dev/null +++ b/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($vendorDir . '/symfony/polyfill-php80'), + 'Slim\\Psr7\\' => array($vendorDir . '/slim/psr7/src'), + 'Slim\\' => array($vendorDir . '/slim/slim/Slim'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/src'), + 'Psr\\Http\\Server\\' => array($vendorDir . '/psr/http-server-handler/src', $vendorDir . '/psr/http-server-middleware/src'), + 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'), + 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'PhpDocReader\\' => array($vendorDir . '/php-di/phpdoc-reader/src/PhpDocReader'), + 'Laravel\\SerializableClosure\\' => array($vendorDir . '/laravel/serializable-closure/src'), + 'Invoker\\' => array($vendorDir . '/php-di/invoker/src'), + 'Fig\\Http\\Message\\' => array($vendorDir . '/fig/http-message-util/src'), + 'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'), + 'DI\\' => array($vendorDir . '/php-di/php-di/src'), + 'App\\' => array($baseDir . '/src'), +); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php new file mode 100644 index 0000000..a201273 --- /dev/null +++ b/vendor/composer/autoload_real.php @@ -0,0 +1,50 @@ +register(true); + + $filesToLoad = \Composer\Autoload\ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9::$files; + $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + + require $file; + } + }, null, null); + foreach ($filesToLoad as $fileIdentifier => $file) { + $requireFile($fileIdentifier, $file); + } + + return $loader; + } +} diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php new file mode 100644 index 0000000..d29dcd5 --- /dev/null +++ b/vendor/composer/autoload_static.php @@ -0,0 +1,133 @@ + __DIR__ . '/..' . '/nikic/fast-route/src/functions.php', + '7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', + 'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', + 'b33e3d135e5d9e47d845c576147bda89' => __DIR__ . '/..' . '/php-di/php-di/src/functions.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'S' => + array ( + 'Symfony\\Polyfill\\Php80\\' => 23, + 'Slim\\Psr7\\' => 10, + 'Slim\\' => 5, + ), + 'P' => + array ( + 'Psr\\Log\\' => 8, + 'Psr\\Http\\Server\\' => 16, + 'Psr\\Http\\Message\\' => 17, + 'Psr\\Container\\' => 14, + 'PhpDocReader\\' => 13, + ), + 'L' => + array ( + 'Laravel\\SerializableClosure\\' => 28, + ), + 'I' => + array ( + 'Invoker\\' => 8, + ), + 'F' => + array ( + 'Fig\\Http\\Message\\' => 17, + 'FastRoute\\' => 10, + ), + 'D' => + array ( + 'DI\\' => 3, + ), + 'A' => + array ( + 'App\\' => 4, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Symfony\\Polyfill\\Php80\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', + ), + 'Slim\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/slim/psr7/src', + ), + 'Slim\\' => + array ( + 0 => __DIR__ . '/..' . '/slim/slim/Slim', + ), + 'Psr\\Log\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/log/src', + ), + 'Psr\\Http\\Server\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-server-handler/src', + 1 => __DIR__ . '/..' . '/psr/http-server-middleware/src', + ), + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-message/src', + 1 => __DIR__ . '/..' . '/psr/http-factory/src', + ), + 'Psr\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/container/src', + ), + 'PhpDocReader\\' => + array ( + 0 => __DIR__ . '/..' . '/php-di/phpdoc-reader/src/PhpDocReader', + ), + 'Laravel\\SerializableClosure\\' => + array ( + 0 => __DIR__ . '/..' . '/laravel/serializable-closure/src', + ), + 'Invoker\\' => + array ( + 0 => __DIR__ . '/..' . '/php-di/invoker/src', + ), + 'Fig\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/fig/http-message-util/src', + ), + 'FastRoute\\' => + array ( + 0 => __DIR__ . '/..' . '/nikic/fast-route/src', + ), + 'DI\\' => + array ( + 0 => __DIR__ . '/..' . '/php-di/php-di/src', + ), + 'App\\' => + array ( + 0 => __DIR__ . '/../..' . '/src', + ), + ); + + public static $classMap = array ( + 'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json new file mode 100644 index 0000000..2e37ac7 --- /dev/null +++ b/vendor/composer/installed.json @@ -0,0 +1,1035 @@ +{ + "packages": [ + { + "name": "fig/http-message-util", + "version": "1.1.5", + "version_normalized": "1.1.5.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message-util.git", + "reference": "9d94dc0154230ac39e5bf89398b324a86f63f765" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message-util/zipball/9d94dc0154230ac39e5bf89398b324a86f63f765", + "reference": "9d94dc0154230ac39e5bf89398b324a86f63f765", + "shasum": "" + }, + "require": { + "php": "^5.3 || ^7.0 || ^8.0" + }, + "suggest": { + "psr/http-message": "The package containing the PSR-7 interfaces" + }, + "time": "2020-11-24T22:02:12+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Fig\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Utility classes and constants for use with PSR-7 (psr/http-message)", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "issues": "https://github.com/php-fig/http-message-util/issues", + "source": "https://github.com/php-fig/http-message-util/tree/1.1.5" + }, + "install-path": "../fig/http-message-util" + }, + { + "name": "laravel/serializable-closure", + "version": "v1.3.7", + "version_normalized": "1.3.7.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/serializable-closure.git", + "reference": "4f48ade902b94323ca3be7646db16209ec76be3d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/4f48ade902b94323ca3be7646db16209ec76be3d", + "reference": "4f48ade902b94323ca3be7646db16209ec76be3d", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0" + }, + "require-dev": { + "illuminate/support": "^8.0|^9.0|^10.0|^11.0", + "nesbot/carbon": "^2.61|^3.0", + "pestphp/pest": "^1.21.3", + "phpstan/phpstan": "^1.8.2", + "symfony/var-dumper": "^5.4.11|^6.2.0|^7.0.0" + }, + "time": "2024-11-14T18:34:49+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Laravel\\SerializableClosure\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + }, + { + "name": "Nuno Maduro", + "email": "nuno@laravel.com" + } + ], + "description": "Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.", + "keywords": [ + "closure", + "laravel", + "serializable" + ], + "support": { + "issues": "https://github.com/laravel/serializable-closure/issues", + "source": "https://github.com/laravel/serializable-closure" + }, + "install-path": "../laravel/serializable-closure" + }, + { + "name": "nikic/fast-route", + "version": "v1.3.0", + "version_normalized": "1.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/FastRoute.git", + "reference": "181d480e08d9476e61381e04a71b34dc0432e812" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/FastRoute/zipball/181d480e08d9476e61381e04a71b34dc0432e812", + "reference": "181d480e08d9476e61381e04a71b34dc0432e812", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35|~5.7" + }, + "time": "2018-02-13T20:26:39+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "FastRoute\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "description": "Fast request router for PHP", + "keywords": [ + "router", + "routing" + ], + "support": { + "issues": "https://github.com/nikic/FastRoute/issues", + "source": "https://github.com/nikic/FastRoute/tree/master" + }, + "install-path": "../nikic/fast-route" + }, + { + "name": "php-di/invoker", + "version": "2.3.6", + "version_normalized": "2.3.6.0", + "source": { + "type": "git", + "url": "https://github.com/PHP-DI/Invoker.git", + "reference": "59f15608528d8a8838d69b422a919fd6b16aa576" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-DI/Invoker/zipball/59f15608528d8a8838d69b422a919fd6b16aa576", + "reference": "59f15608528d8a8838d69b422a919fd6b16aa576", + "shasum": "" + }, + "require": { + "php": ">=7.3", + "psr/container": "^1.0|^2.0" + }, + "require-dev": { + "athletic/athletic": "~0.1.8", + "mnapoli/hard-mode": "~0.3.0", + "phpunit/phpunit": "^9.0" + }, + "time": "2025-01-17T12:49:27+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Invoker\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Generic and extensible callable invoker", + "homepage": "https://github.com/PHP-DI/Invoker", + "keywords": [ + "callable", + "dependency", + "dependency-injection", + "injection", + "invoke", + "invoker" + ], + "support": { + "issues": "https://github.com/PHP-DI/Invoker/issues", + "source": "https://github.com/PHP-DI/Invoker/tree/2.3.6" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + } + ], + "install-path": "../php-di/invoker" + }, + { + "name": "php-di/php-di", + "version": "6.4.0", + "version_normalized": "6.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/PHP-DI/PHP-DI.git", + "reference": "ae0f1b3b03d8b29dff81747063cbfd6276246cc4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-DI/PHP-DI/zipball/ae0f1b3b03d8b29dff81747063cbfd6276246cc4", + "reference": "ae0f1b3b03d8b29dff81747063cbfd6276246cc4", + "shasum": "" + }, + "require": { + "laravel/serializable-closure": "^1.0", + "php": ">=7.4.0", + "php-di/invoker": "^2.0", + "php-di/phpdoc-reader": "^2.0.1", + "psr/container": "^1.0" + }, + "provide": { + "psr/container-implementation": "^1.0" + }, + "require-dev": { + "doctrine/annotations": "~1.10", + "friendsofphp/php-cs-fixer": "^2.4", + "mnapoli/phpunit-easymock": "^1.2", + "ocramius/proxy-manager": "^2.11.2", + "phpstan/phpstan": "^0.12", + "phpunit/phpunit": "^9.5" + }, + "suggest": { + "doctrine/annotations": "Install it if you want to use annotations (version ~1.2)", + "ocramius/proxy-manager": "Install it if you want to use lazy injection (version ~2.0)" + }, + "time": "2022-04-09T16:46:38+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "DI\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "The dependency injection container for humans", + "homepage": "https://php-di.org/", + "keywords": [ + "PSR-11", + "container", + "container-interop", + "dependency injection", + "di", + "ioc", + "psr11" + ], + "support": { + "issues": "https://github.com/PHP-DI/PHP-DI/issues", + "source": "https://github.com/PHP-DI/PHP-DI/tree/6.4.0" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/php-di/php-di", + "type": "tidelift" + } + ], + "install-path": "../php-di/php-di" + }, + { + "name": "php-di/phpdoc-reader", + "version": "2.2.1", + "version_normalized": "2.2.1.0", + "source": { + "type": "git", + "url": "https://github.com/PHP-DI/PhpDocReader.git", + "reference": "66daff34cbd2627740ffec9469ffbac9f8c8185c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-DI/PhpDocReader/zipball/66daff34cbd2627740ffec9469ffbac9f8c8185c", + "reference": "66daff34cbd2627740ffec9469ffbac9f8c8185c", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "require-dev": { + "mnapoli/hard-mode": "~0.3.0", + "phpunit/phpunit": "^8.5|^9.0" + }, + "time": "2020-10-12T12:39:22+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "PhpDocReader\\": "src/PhpDocReader" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PhpDocReader parses @var and @param values in PHP docblocks (supports namespaced class names with the same resolution rules as PHP)", + "keywords": [ + "phpdoc", + "reflection" + ], + "support": { + "issues": "https://github.com/PHP-DI/PhpDocReader/issues", + "source": "https://github.com/PHP-DI/PhpDocReader/tree/2.2.1" + }, + "install-path": "../php-di/phpdoc-reader" + }, + { + "name": "psr/container", + "version": "1.1.2", + "version_normalized": "1.1.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/513e0666f7216c7459170d56df27dfcefe1689ea", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "time": "2021-11-05T16:50:12+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/1.1.2" + }, + "install-path": "../psr/container" + }, + { + "name": "psr/http-factory", + "version": "1.1.0", + "version_normalized": "1.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "time": "2024-04-15T12:06:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory" + }, + "install-path": "../psr/http-factory" + }, + { + "name": "psr/http-message", + "version": "2.0", + "version_normalized": "2.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "time": "2023-04-04T09:54:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "install-path": "../psr/http-message" + }, + { + "name": "psr/http-server-handler", + "version": "1.0.2", + "version_normalized": "1.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-server-handler.git", + "reference": "84c4fb66179be4caaf8e97bd239203245302e7d4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-server-handler/zipball/84c4fb66179be4caaf8e97bd239203245302e7d4", + "reference": "84c4fb66179be4caaf8e97bd239203245302e7d4", + "shasum": "" + }, + "require": { + "php": ">=7.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "time": "2023-04-10T20:06:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP server-side request handler", + "keywords": [ + "handler", + "http", + "http-interop", + "psr", + "psr-15", + "psr-7", + "request", + "response", + "server" + ], + "support": { + "source": "https://github.com/php-fig/http-server-handler/tree/1.0.2" + }, + "install-path": "../psr/http-server-handler" + }, + { + "name": "psr/http-server-middleware", + "version": "1.0.2", + "version_normalized": "1.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-server-middleware.git", + "reference": "c1481f747daaa6a0782775cd6a8c26a1bf4a3829" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-server-middleware/zipball/c1481f747daaa6a0782775cd6a8c26a1bf4a3829", + "reference": "c1481f747daaa6a0782775cd6a8c26a1bf4a3829", + "shasum": "" + }, + "require": { + "php": ">=7.0", + "psr/http-message": "^1.0 || ^2.0", + "psr/http-server-handler": "^1.0" + }, + "time": "2023-04-11T06:14:47+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP server-side middleware", + "keywords": [ + "http", + "http-interop", + "middleware", + "psr", + "psr-15", + "psr-7", + "request", + "response" + ], + "support": { + "issues": "https://github.com/php-fig/http-server-middleware/issues", + "source": "https://github.com/php-fig/http-server-middleware/tree/1.0.2" + }, + "install-path": "../psr/http-server-middleware" + }, + { + "name": "psr/log", + "version": "3.0.2", + "version_normalized": "3.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "time": "2024-09-11T13:17:53+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "install-path": "../psr/log" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "time": "2019-03-08T08:55:37+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "install-path": "../ralouphie/getallheaders" + }, + { + "name": "slim/psr7", + "version": "1.7.0", + "version_normalized": "1.7.0.0", + "source": { + "type": "git", + "url": "https://github.com/slimphp/Slim-Psr7.git", + "reference": "753e9646def5ff4db1a06e5cf4ef539bfd30f467" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/Slim-Psr7/zipball/753e9646def5ff4db1a06e5cf4ef539bfd30f467", + "reference": "753e9646def5ff4db1a06e5cf4ef539bfd30f467", + "shasum": "" + }, + "require": { + "fig/http-message-util": "^1.1.5", + "php": "^8.0", + "psr/http-factory": "^1.1", + "psr/http-message": "^1.0 || ^2.0", + "ralouphie/getallheaders": "^3.0", + "symfony/polyfill-php80": "^1.29" + }, + "provide": { + "psr/http-factory-implementation": "^1.0", + "psr/http-message-implementation": "^1.0 || ^2.0" + }, + "require-dev": { + "adriansuter/php-autoload-override": "^1.4", + "ext-json": "*", + "http-interop/http-factory-tests": "^1.1.0", + "php-http/psr7-integration-tests": "1.3.0", + "phpspec/prophecy": "^1.19", + "phpspec/prophecy-phpunit": "^2.2", + "phpstan/phpstan": "^1.11", + "phpunit/phpunit": "^9.6", + "squizlabs/php_codesniffer": "^3.10" + }, + "time": "2024-06-08T14:48:17+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Slim\\Psr7\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "http://joshlockhart.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" + }, + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, + { + "name": "Pierre Berube", + "email": "pierre@lgse.com", + "homepage": "http://www.lgse.com" + } + ], + "description": "Strict PSR-7 implementation", + "homepage": "https://www.slimframework.com", + "keywords": [ + "http", + "psr-7", + "psr7" + ], + "support": { + "issues": "https://github.com/slimphp/Slim-Psr7/issues", + "source": "https://github.com/slimphp/Slim-Psr7/tree/1.7.0" + }, + "install-path": "../slim/psr7" + }, + { + "name": "slim/slim", + "version": "4.14.0", + "version_normalized": "4.14.0.0", + "source": { + "type": "git", + "url": "https://github.com/slimphp/Slim.git", + "reference": "5943393b88716eb9e82c4161caa956af63423913" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/Slim/zipball/5943393b88716eb9e82c4161caa956af63423913", + "reference": "5943393b88716eb9e82c4161caa956af63423913", + "shasum": "" + }, + "require": { + "ext-json": "*", + "nikic/fast-route": "^1.3", + "php": "^7.4 || ^8.0", + "psr/container": "^1.0 || ^2.0", + "psr/http-factory": "^1.1", + "psr/http-message": "^1.1 || ^2.0", + "psr/http-server-handler": "^1.0", + "psr/http-server-middleware": "^1.0", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "require-dev": { + "adriansuter/php-autoload-override": "^1.4", + "ext-simplexml": "*", + "guzzlehttp/psr7": "^2.6", + "httpsoft/http-message": "^1.1", + "httpsoft/http-server-request": "^1.1", + "laminas/laminas-diactoros": "^2.17 || ^3", + "nyholm/psr7": "^1.8", + "nyholm/psr7-server": "^1.1", + "phpspec/prophecy": "^1.19", + "phpspec/prophecy-phpunit": "^2.1", + "phpstan/phpstan": "^1.11", + "phpunit/phpunit": "^9.6", + "slim/http": "^1.3", + "slim/psr7": "^1.6", + "squizlabs/php_codesniffer": "^3.10", + "vimeo/psalm": "^5.24" + }, + "suggest": { + "ext-simplexml": "Needed to support XML format in BodyParsingMiddleware", + "ext-xml": "Needed to support XML format in BodyParsingMiddleware", + "php-di/php-di": "PHP-DI is the recommended container library to be used with Slim", + "slim/psr7": "Slim PSR-7 implementation. See https://www.slimframework.com/docs/v4/start/installation.html for more information." + }, + "time": "2024-06-13T08:54:48+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Slim\\": "Slim" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "https://joshlockhart.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" + }, + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, + { + "name": "Pierre Berube", + "email": "pierre@lgse.com", + "homepage": "http://www.lgse.com" + }, + { + "name": "Gabriel Manricks", + "email": "gmanricks@me.com", + "homepage": "http://gabrielmanricks.com" + } + ], + "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", + "homepage": "https://www.slimframework.com", + "keywords": [ + "api", + "framework", + "micro", + "router" + ], + "support": { + "docs": "https://www.slimframework.com/docs/v4/", + "forum": "https://discourse.slimframework.com/", + "irc": "irc://irc.freenode.net:6667/slimphp", + "issues": "https://github.com/slimphp/Slim/issues", + "rss": "https://www.slimframework.com/blog/feed.rss", + "slack": "https://slimphp.slack.com/", + "source": "https://github.com/slimphp/Slim", + "wiki": "https://github.com/slimphp/Slim/wiki" + }, + "funding": [ + { + "url": "https://opencollective.com/slimphp", + "type": "open_collective" + }, + { + "url": "https://tidelift.com/funding/github/packagist/slim/slim", + "type": "tidelift" + } + ], + "install-path": "../slim/slim" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.31.0", + "version_normalized": "1.31.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "time": "2024-09-09T11:45:10+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.31.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php80" + } + ], + "dev": true, + "dev-package-names": [] +} diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php new file mode 100644 index 0000000..f9669a6 --- /dev/null +++ b/vendor/composer/installed.php @@ -0,0 +1,185 @@ + array( + 'name' => '__root__', + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => '125ed0da41ed191fb7b6fed7ff678984b90699dc', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => '125ed0da41ed191fb7b6fed7ff678984b90699dc', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'fig/http-message-util' => array( + 'pretty_version' => '1.1.5', + 'version' => '1.1.5.0', + 'reference' => '9d94dc0154230ac39e5bf89398b324a86f63f765', + 'type' => 'library', + 'install_path' => __DIR__ . '/../fig/http-message-util', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'laravel/serializable-closure' => array( + 'pretty_version' => 'v1.3.7', + 'version' => '1.3.7.0', + 'reference' => '4f48ade902b94323ca3be7646db16209ec76be3d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../laravel/serializable-closure', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'nikic/fast-route' => array( + 'pretty_version' => 'v1.3.0', + 'version' => '1.3.0.0', + 'reference' => '181d480e08d9476e61381e04a71b34dc0432e812', + 'type' => 'library', + 'install_path' => __DIR__ . '/../nikic/fast-route', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'php-di/invoker' => array( + 'pretty_version' => '2.3.6', + 'version' => '2.3.6.0', + 'reference' => '59f15608528d8a8838d69b422a919fd6b16aa576', + 'type' => 'library', + 'install_path' => __DIR__ . '/../php-di/invoker', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'php-di/php-di' => array( + 'pretty_version' => '6.4.0', + 'version' => '6.4.0.0', + 'reference' => 'ae0f1b3b03d8b29dff81747063cbfd6276246cc4', + 'type' => 'library', + 'install_path' => __DIR__ . '/../php-di/php-di', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'php-di/phpdoc-reader' => array( + 'pretty_version' => '2.2.1', + 'version' => '2.2.1.0', + 'reference' => '66daff34cbd2627740ffec9469ffbac9f8c8185c', + 'type' => 'library', + 'install_path' => __DIR__ . '/../php-di/phpdoc-reader', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/container' => array( + 'pretty_version' => '1.1.2', + 'version' => '1.1.2.0', + 'reference' => '513e0666f7216c7459170d56df27dfcefe1689ea', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/container', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/container-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '^1.0', + ), + ), + 'psr/http-factory' => array( + 'pretty_version' => '1.1.0', + 'version' => '1.1.0.0', + 'reference' => '2b4765fddfe3b508ac62f829e852b1501d3f6e8a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-factory', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-factory-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '^1.0', + ), + ), + 'psr/http-message' => array( + 'pretty_version' => '2.0', + 'version' => '2.0.0.0', + 'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-message', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-message-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '^1.0 || ^2.0', + ), + ), + 'psr/http-server-handler' => array( + 'pretty_version' => '1.0.2', + 'version' => '1.0.2.0', + 'reference' => '84c4fb66179be4caaf8e97bd239203245302e7d4', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-server-handler', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-server-middleware' => array( + 'pretty_version' => '1.0.2', + 'version' => '1.0.2.0', + 'reference' => 'c1481f747daaa6a0782775cd6a8c26a1bf4a3829', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-server-middleware', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/log' => array( + 'pretty_version' => '3.0.2', + 'version' => '3.0.2.0', + 'reference' => 'f16e1d5863e37f8d8c2a01719f5b34baa2b714d3', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/log', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'ralouphie/getallheaders' => array( + 'pretty_version' => '3.0.3', + 'version' => '3.0.3.0', + 'reference' => '120b605dfeb996808c31b6477290a714d356e822', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ralouphie/getallheaders', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'slim/psr7' => array( + 'pretty_version' => '1.7.0', + 'version' => '1.7.0.0', + 'reference' => '753e9646def5ff4db1a06e5cf4ef539bfd30f467', + 'type' => 'library', + 'install_path' => __DIR__ . '/../slim/psr7', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'slim/slim' => array( + 'pretty_version' => '4.14.0', + 'version' => '4.14.0.0', + 'reference' => '5943393b88716eb9e82c4161caa956af63423913', + 'type' => 'library', + 'install_path' => __DIR__ . '/../slim/slim', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-php80' => array( + 'pretty_version' => 'v1.31.0', + 'version' => '1.31.0.0', + 'reference' => '60328e362d4c2c802a54fcbf04f9d3fb892b4cf8', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php80', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/vendor/composer/platform_check.php b/vendor/composer/platform_check.php new file mode 100644 index 0000000..adfb472 --- /dev/null +++ b/vendor/composer/platform_check.php @@ -0,0 +1,26 @@ += 80000)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 8.0.0". You are running ' . PHP_VERSION . '.'; +} + +if ($issues) { + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + if (!ini_get('display_errors')) { + if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { + fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); + } elseif (!headers_sent()) { + echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; + } + } + trigger_error( + 'Composer detected issues in your platform: ' . implode(' ', $issues), + E_USER_ERROR + ); +} diff --git a/vendor/fig/http-message-util/.gitignore b/vendor/fig/http-message-util/.gitignore new file mode 100644 index 0000000..48b8bf9 --- /dev/null +++ b/vendor/fig/http-message-util/.gitignore @@ -0,0 +1 @@ +vendor/ diff --git a/vendor/fig/http-message-util/CHANGELOG.md b/vendor/fig/http-message-util/CHANGELOG.md new file mode 100644 index 0000000..1a02e54 --- /dev/null +++ b/vendor/fig/http-message-util/CHANGELOG.md @@ -0,0 +1,147 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.1.5 - 2020-11-24 + +### Added + +- [#19](https://github.com/php-fig/http-message-util/pull/19) adds support for PHP 8. + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + +## 1.1.4 - 2020-02-05 + +### Added + +- Nothing. + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- [#15](https://github.com/php-fig/http-message-util/pull/15) removes the dependency on psr/http-message, as it is not technically necessary for usage of this package. + +### Fixed + +- Nothing. + +## 1.1.3 - 2018-11-19 + +### Added + +- [#10](https://github.com/php-fig/http-message-util/pull/10) adds the constants `StatusCodeInterface::STATUS_EARLY_HINTS` (103) and + `StatusCodeInterface::STATUS_TOO_EARLY` (425). + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + +## 1.1.2 - 2017-02-09 + +### Added + +- [#4](https://github.com/php-fig/http-message-util/pull/4) adds the constant + `StatusCodeInterface::STATUS_MISDIRECTED_REQUEST` (421). + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + +## 1.1.1 - 2017-02-06 + +### Added + +- [#3](https://github.com/php-fig/http-message-util/pull/3) adds the constant + `StatusCodeInterface::STATUS_IM_A_TEAPOT` (418). + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + +## 1.1.0 - 2016-09-19 + +### Added + +- [#1](https://github.com/php-fig/http-message-util/pull/1) adds + `Fig\Http\Message\StatusCodeInterface`, with constants named after common + status reason phrases, with values indicating the status codes themselves. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + +## 1.0.0 - 2017-08-05 + +### Added + +- Adds `Fig\Http\Message\RequestMethodInterface`, with constants covering the + most common HTTP request methods as specified by the IETF. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. diff --git a/vendor/fig/http-message-util/LICENSE b/vendor/fig/http-message-util/LICENSE new file mode 100644 index 0000000..e2fa347 --- /dev/null +++ b/vendor/fig/http-message-util/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2016 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/fig/http-message-util/README.md b/vendor/fig/http-message-util/README.md new file mode 100644 index 0000000..ea5b5aa --- /dev/null +++ b/vendor/fig/http-message-util/README.md @@ -0,0 +1,17 @@ +# PSR Http Message Util + +This repository holds utility classes and constants to facilitate common +operations of [PSR-7](https://www.php-fig.org/psr/psr-7/); the primary purpose is +to provide constants for referring to request methods, response status codes and +messages, and potentially common headers. + +Implementation of PSR-7 interfaces is **not** within the scope of this package. + +## Installation + +Install by adding the package as a [Composer](https://getcomposer.org) +requirement: + +```bash +$ composer require fig/http-message-util +``` diff --git a/vendor/fig/http-message-util/composer.json b/vendor/fig/http-message-util/composer.json new file mode 100644 index 0000000..8645893 --- /dev/null +++ b/vendor/fig/http-message-util/composer.json @@ -0,0 +1,28 @@ +{ + "name": "fig/http-message-util", + "description": "Utility classes and constants for use with PSR-7 (psr/http-message)", + "keywords": ["psr", "psr-7", "http", "http-message", "request", "response"], + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": "^5.3 || ^7.0 || ^8.0" + }, + "suggest": { + "psr/http-message": "The package containing the PSR-7 interfaces" + }, + "autoload": { + "psr-4": { + "Fig\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + } +} diff --git a/vendor/fig/http-message-util/src/RequestMethodInterface.php b/vendor/fig/http-message-util/src/RequestMethodInterface.php new file mode 100644 index 0000000..97d9a93 --- /dev/null +++ b/vendor/fig/http-message-util/src/RequestMethodInterface.php @@ -0,0 +1,34 @@ + + * class RequestFactory implements RequestMethodInterface + * { + * public static function factory( + * $uri = '/', + * $method = self::METHOD_GET, + * $data = [] + * ) { + * } + * } + * + */ +interface RequestMethodInterface +{ + const METHOD_HEAD = 'HEAD'; + const METHOD_GET = 'GET'; + const METHOD_POST = 'POST'; + const METHOD_PUT = 'PUT'; + const METHOD_PATCH = 'PATCH'; + const METHOD_DELETE = 'DELETE'; + const METHOD_PURGE = 'PURGE'; + const METHOD_OPTIONS = 'OPTIONS'; + const METHOD_TRACE = 'TRACE'; + const METHOD_CONNECT = 'CONNECT'; +} diff --git a/vendor/fig/http-message-util/src/StatusCodeInterface.php b/vendor/fig/http-message-util/src/StatusCodeInterface.php new file mode 100644 index 0000000..99b7e78 --- /dev/null +++ b/vendor/fig/http-message-util/src/StatusCodeInterface.php @@ -0,0 +1,107 @@ + + * class ResponseFactory implements StatusCodeInterface + * { + * public function createResponse($code = self::STATUS_OK) + * { + * } + * } + * + */ +interface StatusCodeInterface +{ + // Informational 1xx + const STATUS_CONTINUE = 100; + const STATUS_SWITCHING_PROTOCOLS = 101; + const STATUS_PROCESSING = 102; + const STATUS_EARLY_HINTS = 103; + // Successful 2xx + const STATUS_OK = 200; + const STATUS_CREATED = 201; + const STATUS_ACCEPTED = 202; + const STATUS_NON_AUTHORITATIVE_INFORMATION = 203; + const STATUS_NO_CONTENT = 204; + const STATUS_RESET_CONTENT = 205; + const STATUS_PARTIAL_CONTENT = 206; + const STATUS_MULTI_STATUS = 207; + const STATUS_ALREADY_REPORTED = 208; + const STATUS_IM_USED = 226; + // Redirection 3xx + const STATUS_MULTIPLE_CHOICES = 300; + const STATUS_MOVED_PERMANENTLY = 301; + const STATUS_FOUND = 302; + const STATUS_SEE_OTHER = 303; + const STATUS_NOT_MODIFIED = 304; + const STATUS_USE_PROXY = 305; + const STATUS_RESERVED = 306; + const STATUS_TEMPORARY_REDIRECT = 307; + const STATUS_PERMANENT_REDIRECT = 308; + // Client Errors 4xx + const STATUS_BAD_REQUEST = 400; + const STATUS_UNAUTHORIZED = 401; + const STATUS_PAYMENT_REQUIRED = 402; + const STATUS_FORBIDDEN = 403; + const STATUS_NOT_FOUND = 404; + const STATUS_METHOD_NOT_ALLOWED = 405; + const STATUS_NOT_ACCEPTABLE = 406; + const STATUS_PROXY_AUTHENTICATION_REQUIRED = 407; + const STATUS_REQUEST_TIMEOUT = 408; + const STATUS_CONFLICT = 409; + const STATUS_GONE = 410; + const STATUS_LENGTH_REQUIRED = 411; + const STATUS_PRECONDITION_FAILED = 412; + const STATUS_PAYLOAD_TOO_LARGE = 413; + const STATUS_URI_TOO_LONG = 414; + const STATUS_UNSUPPORTED_MEDIA_TYPE = 415; + const STATUS_RANGE_NOT_SATISFIABLE = 416; + const STATUS_EXPECTATION_FAILED = 417; + const STATUS_IM_A_TEAPOT = 418; + const STATUS_MISDIRECTED_REQUEST = 421; + const STATUS_UNPROCESSABLE_ENTITY = 422; + const STATUS_LOCKED = 423; + const STATUS_FAILED_DEPENDENCY = 424; + const STATUS_TOO_EARLY = 425; + const STATUS_UPGRADE_REQUIRED = 426; + const STATUS_PRECONDITION_REQUIRED = 428; + const STATUS_TOO_MANY_REQUESTS = 429; + const STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; + const STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451; + // Server Errors 5xx + const STATUS_INTERNAL_SERVER_ERROR = 500; + const STATUS_NOT_IMPLEMENTED = 501; + const STATUS_BAD_GATEWAY = 502; + const STATUS_SERVICE_UNAVAILABLE = 503; + const STATUS_GATEWAY_TIMEOUT = 504; + const STATUS_VERSION_NOT_SUPPORTED = 505; + const STATUS_VARIANT_ALSO_NEGOTIATES = 506; + const STATUS_INSUFFICIENT_STORAGE = 507; + const STATUS_LOOP_DETECTED = 508; + const STATUS_NOT_EXTENDED = 510; + const STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511; +} diff --git a/vendor/laravel/serializable-closure/LICENSE.md b/vendor/laravel/serializable-closure/LICENSE.md new file mode 100644 index 0000000..79810c8 --- /dev/null +++ b/vendor/laravel/serializable-closure/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Taylor Otwell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/laravel/serializable-closure/README.md b/vendor/laravel/serializable-closure/README.md new file mode 100644 index 0000000..ee0d01a --- /dev/null +++ b/vendor/laravel/serializable-closure/README.md @@ -0,0 +1,73 @@ +# Serializable Closure + + + Build Status + + + Total Downloads + + + Latest Stable Version + + + License + + +## Introduction + +> This project is a fork of the excellent [opis/closure: 3.x](https://github.com/opis/closure) package. At Laravel, we decided to fork this package as the upcoming version [4.x](https://github.com/opis/closure) is a complete rewrite on top of the [FFI extension](https://www.php.net/manual/en/book.ffi.php). As Laravel is a web framework, and FFI is not enabled by default in web requests, this fork allows us to keep using the `3.x` series while adding support for new PHP versions. + +Laravel Serializable Closure provides an easy and secure way to **serialize closures in PHP**. + +## Official Documentation + +### Installation + +> **Requires [PHP 7.4+](https://php.net/releases/)** + +First, install Laravel Serializable Closure via the [Composer](https://getcomposer.org/) package manager: + +```bash +composer require laravel/serializable-closure +``` + +### Usage + +You may serialize a closure this way: + +```php +use Laravel\SerializableClosure\SerializableClosure; + +$closure = fn () => 'james'; + +// Recommended +SerializableClosure::setSecretKey('secret'); + +$serialized = serialize(new SerializableClosure($closure)); +$closure = unserialize($serialized)->getClosure(); + +echo $closure(); // james; +``` + +### Caveats + +* Anonymous classes cannot be created within closures. +* Attributes cannot be used within closures. +* Serializing closures on REPL environments like Laravel Tinker is not supported. +* Serializing closures that reference objects with readonly properties is not supported. + +## Contributing + +Thank you for considering contributing to Serializable Closure! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions). + +## Code of Conduct + +In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct). + +## Security Vulnerabilities + +Please review [our security policy](https://github.com/laravel/serializable-closure/security/policy) on how to report security vulnerabilities. + +## License + +Serializable Closure is open-sourced software licensed under the [MIT license](LICENSE.md). diff --git a/vendor/laravel/serializable-closure/composer.json b/vendor/laravel/serializable-closure/composer.json new file mode 100644 index 0000000..d2d94f6 --- /dev/null +++ b/vendor/laravel/serializable-closure/composer.json @@ -0,0 +1,53 @@ +{ + "name": "laravel/serializable-closure", + "description": "Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.", + "keywords": ["laravel", "Serializable", "closure"], + "license": "MIT", + "support": { + "issues": "https://github.com/laravel/serializable-closure/issues", + "source": "https://github.com/laravel/serializable-closure" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + }, + { + "name": "Nuno Maduro", + "email": "nuno@laravel.com" + } + ], + "require": { + "php": "^7.3|^8.0" + }, + "require-dev": { + "illuminate/support": "^8.0|^9.0|^10.0|^11.0", + "nesbot/carbon": "^2.61|^3.0", + "pestphp/pest": "^1.21.3", + "phpstan/phpstan": "^1.8.2", + "symfony/var-dumper": "^5.4.11|^6.2.0|^7.0.0" + }, + "autoload": { + "psr-4": { + "Laravel\\SerializableClosure\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/vendor/laravel/serializable-closure/src/Contracts/Serializable.php b/vendor/laravel/serializable-closure/src/Contracts/Serializable.php new file mode 100644 index 0000000..1a62922 --- /dev/null +++ b/vendor/laravel/serializable-closure/src/Contracts/Serializable.php @@ -0,0 +1,20 @@ +serializable = Serializers\Signed::$signer + ? new Serializers\Signed($closure) + : new Serializers\Native($closure); + } + + /** + * Resolve the closure with the given arguments. + * + * @return mixed + */ + public function __invoke() + { + if (\PHP_VERSION_ID < 70400) { + throw new PhpVersionNotSupportedException(); + } + + return call_user_func_array($this->serializable, func_get_args()); + } + + /** + * Gets the closure. + * + * @return \Closure + */ + public function getClosure() + { + if (\PHP_VERSION_ID < 70400) { + throw new PhpVersionNotSupportedException(); + } + + return $this->serializable->getClosure(); + } + + /** + * Create a new unsigned serializable closure instance. + * + * @param Closure $closure + * @return \Laravel\SerializableClosure\UnsignedSerializableClosure + */ + public static function unsigned(Closure $closure) + { + return new UnsignedSerializableClosure($closure); + } + + /** + * Sets the serializable closure secret key. + * + * @param string|null $secret + * @return void + */ + public static function setSecretKey($secret) + { + Serializers\Signed::$signer = $secret + ? new Hmac($secret) + : null; + } + + /** + * Sets the serializable closure secret key. + * + * @param \Closure|null $transformer + * @return void + */ + public static function transformUseVariablesUsing($transformer) + { + Serializers\Native::$transformUseVariables = $transformer; + } + + /** + * Sets the serializable closure secret key. + * + * @param \Closure|null $resolver + * @return void + */ + public static function resolveUseVariablesUsing($resolver) + { + Serializers\Native::$resolveUseVariables = $resolver; + } + + /** + * Get the serializable representation of the closure. + * + * @return array + */ + public function __serialize() + { + return [ + 'serializable' => $this->serializable, + ]; + } + + /** + * Restore the closure after serialization. + * + * @param array $data + * @return void + * + * @throws \Laravel\SerializableClosure\Exceptions\InvalidSignatureException + */ + public function __unserialize($data) + { + if (Signed::$signer && ! $data['serializable'] instanceof Signed) { + throw new InvalidSignatureException(); + } + + $this->serializable = $data['serializable']; + } +} diff --git a/vendor/laravel/serializable-closure/src/Serializers/Native.php b/vendor/laravel/serializable-closure/src/Serializers/Native.php new file mode 100644 index 0000000..7325490 --- /dev/null +++ b/vendor/laravel/serializable-closure/src/Serializers/Native.php @@ -0,0 +1,522 @@ +closure = $closure; + } + + /** + * Resolve the closure with the given arguments. + * + * @return mixed + */ + public function __invoke() + { + return call_user_func_array($this->closure, func_get_args()); + } + + /** + * Gets the closure. + * + * @return \Closure + */ + public function getClosure() + { + return $this->closure; + } + + /** + * Get the serializable representation of the closure. + * + * @return array + */ + public function __serialize() + { + if ($this->scope === null) { + $this->scope = new ClosureScope(); + $this->scope->toSerialize++; + } + + $this->scope->serializations++; + + $scope = $object = null; + $reflector = $this->getReflector(); + + if ($reflector->isBindingRequired()) { + $object = $reflector->getClosureThis(); + + static::wrapClosures($object, $this->scope); + } + + if ($scope = $reflector->getClosureScopeClass()) { + $scope = $scope->name; + } + + $this->reference = spl_object_hash($this->closure); + + $this->scope[$this->closure] = $this; + + $use = $reflector->getUseVariables(); + + if (static::$transformUseVariables) { + $use = call_user_func(static::$transformUseVariables, $reflector->getUseVariables()); + } + + $code = $reflector->getCode(); + + $this->mapByReference($use); + + $data = [ + 'use' => $use, + 'function' => $code, + 'scope' => $scope, + 'this' => $object, + 'self' => $this->reference, + ]; + + if (! --$this->scope->serializations && ! --$this->scope->toSerialize) { + $this->scope = null; + } + + return $data; + } + + /** + * Restore the closure after serialization. + * + * @param array $data + * @return void + */ + public function __unserialize($data) + { + ClosureStream::register(); + + $this->code = $data; + unset($data); + + $this->code['objects'] = []; + + if ($this->code['use']) { + $this->scope = new ClosureScope(); + + if (static::$resolveUseVariables) { + $this->code['use'] = call_user_func(static::$resolveUseVariables, $this->code['use']); + } + + $this->mapPointers($this->code['use']); + + extract($this->code['use'], EXTR_OVERWRITE | EXTR_REFS); + + $this->scope = null; + } + + $this->closure = include ClosureStream::STREAM_PROTO.'://'.$this->code['function']; + + if ($this->code['this'] === $this) { + $this->code['this'] = null; + } + + $this->closure = $this->closure->bindTo($this->code['this'], $this->code['scope']); + + if (! empty($this->code['objects'])) { + foreach ($this->code['objects'] as $item) { + $item['property']->setValue($item['instance'], $item['object']->getClosure()); + } + } + + $this->code = $this->code['function']; + } + + /** + * Ensures the given closures are serializable. + * + * @param mixed $data + * @param \Laravel\SerializableClosure\Support\ClosureScope $storage + * @return void + */ + public static function wrapClosures(&$data, $storage) + { + if ($data instanceof Closure) { + $data = new static($data); + } elseif (is_array($data)) { + if (isset($data[self::ARRAY_RECURSIVE_KEY])) { + return; + } + + $data[self::ARRAY_RECURSIVE_KEY] = true; + + foreach ($data as $key => &$value) { + if ($key === self::ARRAY_RECURSIVE_KEY) { + continue; + } + static::wrapClosures($value, $storage); + } + + unset($value); + unset($data[self::ARRAY_RECURSIVE_KEY]); + } elseif ($data instanceof \stdClass) { + if (isset($storage[$data])) { + $data = $storage[$data]; + + return; + } + + $data = $storage[$data] = clone $data; + + foreach ($data as &$value) { + static::wrapClosures($value, $storage); + } + + unset($value); + } elseif (is_object($data) && ! $data instanceof static && ! $data instanceof UnitEnum) { + if (isset($storage[$data])) { + $data = $storage[$data]; + + return; + } + + $instance = $data; + $reflection = new ReflectionObject($instance); + + if (! $reflection->isUserDefined()) { + $storage[$instance] = $data; + + return; + } + + $storage[$instance] = $data = $reflection->newInstanceWithoutConstructor(); + + do { + if (! $reflection->isUserDefined()) { + break; + } + + foreach ($reflection->getProperties() as $property) { + if ($property->isStatic() || ! $property->getDeclaringClass()->isUserDefined()) { + continue; + } + + $property->setAccessible(true); + + if (PHP_VERSION >= 7.4 && ! $property->isInitialized($instance)) { + continue; + } + + $value = $property->getValue($instance); + + if (is_array($value) || is_object($value)) { + static::wrapClosures($value, $storage); + } + + $property->setValue($data, $value); + } + } while ($reflection = $reflection->getParentClass()); + } + } + + /** + * Gets the closure's reflector. + * + * @return \Laravel\SerializableClosure\Support\ReflectionClosure + */ + public function getReflector() + { + if ($this->reflector === null) { + $this->code = null; + $this->reflector = new ReflectionClosure($this->closure); + } + + return $this->reflector; + } + + /** + * Internal method used to map closure pointers. + * + * @param mixed $data + * @return void + */ + protected function mapPointers(&$data) + { + $scope = $this->scope; + + if ($data instanceof static) { + $data = &$data->closure; + } elseif (is_array($data)) { + if (isset($data[self::ARRAY_RECURSIVE_KEY])) { + return; + } + + $data[self::ARRAY_RECURSIVE_KEY] = true; + + foreach ($data as $key => &$value) { + if ($key === self::ARRAY_RECURSIVE_KEY) { + continue; + } elseif ($value instanceof static) { + $data[$key] = &$value->closure; + } elseif ($value instanceof SelfReference && $value->hash === $this->code['self']) { + $data[$key] = &$this->closure; + } else { + $this->mapPointers($value); + } + } + + unset($value); + unset($data[self::ARRAY_RECURSIVE_KEY]); + } elseif ($data instanceof \stdClass) { + if (isset($scope[$data])) { + return; + } + + $scope[$data] = true; + + foreach ($data as $key => &$value) { + if ($value instanceof SelfReference && $value->hash === $this->code['self']) { + $data->{$key} = &$this->closure; + } elseif (is_array($value) || is_object($value)) { + $this->mapPointers($value); + } + } + + unset($value); + } elseif (is_object($data) && ! ($data instanceof Closure)) { + if (isset($scope[$data])) { + return; + } + + $scope[$data] = true; + $reflection = new ReflectionObject($data); + + do { + if (! $reflection->isUserDefined()) { + break; + } + + foreach ($reflection->getProperties() as $property) { + if ($property->isStatic() || ! $property->getDeclaringClass()->isUserDefined()) { + continue; + } + + $property->setAccessible(true); + + if (PHP_VERSION >= 7.4 && ! $property->isInitialized($data)) { + continue; + } + + if (PHP_VERSION >= 8.1 && $property->isReadOnly()) { + continue; + } + + $item = $property->getValue($data); + + if ($item instanceof SerializableClosure || $item instanceof UnsignedSerializableClosure || ($item instanceof SelfReference && $item->hash === $this->code['self'])) { + $this->code['objects'][] = [ + 'instance' => $data, + 'property' => $property, + 'object' => $item instanceof SelfReference ? $this : $item, + ]; + } elseif (is_array($item) || is_object($item)) { + $this->mapPointers($item); + $property->setValue($data, $item); + } + } + } while ($reflection = $reflection->getParentClass()); + } + } + + /** + * Internal method used to map closures by reference. + * + * @param mixed $data + * @return void + */ + protected function mapByReference(&$data) + { + if ($data instanceof Closure) { + if ($data === $this->closure) { + $data = new SelfReference($this->reference); + + return; + } + + if (isset($this->scope[$data])) { + $data = $this->scope[$data]; + + return; + } + + $instance = new static($data); + + $instance->scope = $this->scope; + + $data = $this->scope[$data] = $instance; + } elseif (is_array($data)) { + if (isset($data[self::ARRAY_RECURSIVE_KEY])) { + return; + } + + $data[self::ARRAY_RECURSIVE_KEY] = true; + + foreach ($data as $key => &$value) { + if ($key === self::ARRAY_RECURSIVE_KEY) { + continue; + } + + $this->mapByReference($value); + } + + unset($value); + unset($data[self::ARRAY_RECURSIVE_KEY]); + } elseif ($data instanceof \stdClass) { + if (isset($this->scope[$data])) { + $data = $this->scope[$data]; + + return; + } + + $instance = $data; + $this->scope[$instance] = $data = clone $data; + + foreach ($data as &$value) { + $this->mapByReference($value); + } + + unset($value); + } elseif (is_object($data) && ! $data instanceof SerializableClosure && ! $data instanceof UnsignedSerializableClosure) { + if (isset($this->scope[$data])) { + $data = $this->scope[$data]; + + return; + } + + $instance = $data; + + if ($data instanceof DateTimeInterface) { + $this->scope[$instance] = $data; + + return; + } + + if ($data instanceof UnitEnum) { + $this->scope[$instance] = $data; + + return; + } + + $reflection = new ReflectionObject($data); + + if (! $reflection->isUserDefined()) { + $this->scope[$instance] = $data; + + return; + } + + $this->scope[$instance] = $data = $reflection->newInstanceWithoutConstructor(); + + do { + if (! $reflection->isUserDefined()) { + break; + } + + foreach ($reflection->getProperties() as $property) { + if ($property->isStatic() || ! $property->getDeclaringClass()->isUserDefined()) { + continue; + } + + $property->setAccessible(true); + + if (PHP_VERSION >= 7.4 && ! $property->isInitialized($instance)) { + continue; + } + + if (PHP_VERSION >= 8.1 && $property->isReadOnly() && $property->class !== $reflection->name) { + continue; + } + + $value = $property->getValue($instance); + + if (is_array($value) || is_object($value)) { + $this->mapByReference($value); + } + + $property->setValue($data, $value); + } + } while ($reflection = $reflection->getParentClass()); + } + } +} diff --git a/vendor/laravel/serializable-closure/src/Serializers/Signed.php b/vendor/laravel/serializable-closure/src/Serializers/Signed.php new file mode 100644 index 0000000..391d20d --- /dev/null +++ b/vendor/laravel/serializable-closure/src/Serializers/Signed.php @@ -0,0 +1,91 @@ +closure = $closure; + } + + /** + * Resolve the closure with the given arguments. + * + * @return mixed + */ + public function __invoke() + { + return call_user_func_array($this->closure, func_get_args()); + } + + /** + * Gets the closure. + * + * @return \Closure + */ + public function getClosure() + { + return $this->closure; + } + + /** + * Get the serializable representation of the closure. + * + * @return array + */ + public function __serialize() + { + if (! static::$signer) { + throw new MissingSecretKeyException(); + } + + return static::$signer->sign( + serialize(new Native($this->closure)) + ); + } + + /** + * Restore the closure after serialization. + * + * @param array $signature + * @return void + * + * @throws \Laravel\SerializableClosure\Exceptions\InvalidSignatureException + */ + public function __unserialize($signature) + { + if (static::$signer && ! static::$signer->verify($signature)) { + throw new InvalidSignatureException(); + } + + /** @var \Laravel\SerializableClosure\Contracts\Serializable $serializable */ + $serializable = unserialize($signature['serializable']); + + $this->closure = $serializable->getClosure(); + } +} diff --git a/vendor/laravel/serializable-closure/src/Signers/Hmac.php b/vendor/laravel/serializable-closure/src/Signers/Hmac.php new file mode 100644 index 0000000..d94b0a2 --- /dev/null +++ b/vendor/laravel/serializable-closure/src/Signers/Hmac.php @@ -0,0 +1,53 @@ +secret = $secret; + } + + /** + * Sign the given serializable. + * + * @param string $serialized + * @return array + */ + public function sign($serialized) + { + return [ + 'serializable' => $serialized, + 'hash' => base64_encode(hash_hmac('sha256', $serialized, $this->secret, true)), + ]; + } + + /** + * Verify the given signature. + * + * @param array $signature + * @return bool + */ + public function verify($signature) + { + return hash_equals(base64_encode( + hash_hmac('sha256', $signature['serializable'], $this->secret, true) + ), $signature['hash']); + } +} diff --git a/vendor/laravel/serializable-closure/src/Support/ClosureScope.php b/vendor/laravel/serializable-closure/src/Support/ClosureScope.php new file mode 100644 index 0000000..64ca19a --- /dev/null +++ b/vendor/laravel/serializable-closure/src/Support/ClosureScope.php @@ -0,0 +1,22 @@ +content = "length = strlen($this->content); + + return true; + } + + /** + * Read from stream. + * + * @param int $count + * @return string + */ + public function stream_read($count) + { + $value = substr($this->content, $this->pointer, $count); + + $this->pointer += $count; + + return $value; + } + + /** + * Tests for end-of-file on a file pointer. + * + * @return bool + */ + public function stream_eof() + { + return $this->pointer >= $this->length; + } + + /** + * Change stream options. + * + * @param int $option + * @param int $arg1 + * @param int $arg2 + * @return bool + */ + public function stream_set_option($option, $arg1, $arg2) + { + return false; + } + + /** + * Retrieve information about a file resource. + * + * @return array|bool + */ + public function stream_stat() + { + $stat = stat(__FILE__); + // @phpstan-ignore-next-line + $stat[7] = $stat['size'] = $this->length; + + return $stat; + } + + /** + * Retrieve information about a file. + * + * @param string $path + * @param int $flags + * @return array|bool + */ + public function url_stat($path, $flags) + { + $stat = stat(__FILE__); + // @phpstan-ignore-next-line + $stat[7] = $stat['size'] = $this->length; + + return $stat; + } + + /** + * Seeks to specific location in a stream. + * + * @param int $offset + * @param int $whence + * @return bool + */ + public function stream_seek($offset, $whence = SEEK_SET) + { + $crt = $this->pointer; + + switch ($whence) { + case SEEK_SET: + $this->pointer = $offset; + break; + case SEEK_CUR: + $this->pointer += $offset; + break; + case SEEK_END: + $this->pointer = $this->length + $offset; + break; + } + + if ($this->pointer < 0 || $this->pointer >= $this->length) { + $this->pointer = $crt; + + return false; + } + + return true; + } + + /** + * Retrieve the current position of a stream. + * + * @return int + */ + public function stream_tell() + { + return $this->pointer; + } + + /** + * Registers the stream. + * + * @return void + */ + public static function register() + { + if (! static::$isRegistered) { + static::$isRegistered = stream_wrapper_register(static::STREAM_PROTO, __CLASS__); + } + } +} diff --git a/vendor/laravel/serializable-closure/src/Support/ReflectionClosure.php b/vendor/laravel/serializable-closure/src/Support/ReflectionClosure.php new file mode 100644 index 0000000..e929600 --- /dev/null +++ b/vendor/laravel/serializable-closure/src/Support/ReflectionClosure.php @@ -0,0 +1,1198 @@ +isStaticClosure === null) { + $this->isStaticClosure = strtolower(substr($this->getCode(), 0, 6)) === 'static'; + } + + return $this->isStaticClosure; + } + + /** + * Checks if the closure is a "short closure". + * + * @return bool + */ + public function isShortClosure() + { + if ($this->isShortClosure === null) { + $code = $this->getCode(); + + if ($this->isStatic()) { + $code = substr($code, 6); + } + + $this->isShortClosure = strtolower(substr(trim($code), 0, 2)) === 'fn'; + } + + return $this->isShortClosure; + } + + /** + * Get the closure's code. + * + * @return string + */ + public function getCode() + { + if ($this->code !== null) { + return $this->code; + } + + $fileName = $this->getFileName(); + $line = $this->getStartLine() - 1; + + $className = null; + + if (null !== $className = $this->getClosureScopeClass()) { + $className = '\\'.trim($className->getName(), '\\'); + } + + $builtin_types = self::getBuiltinTypes(); + $class_keywords = ['self', 'static', 'parent']; + + $ns = $this->getClosureNamespaceName(); + $nsf = $ns == '' ? '' : ($ns[0] == '\\' ? $ns : '\\'.$ns); + + $_file = var_export($fileName, true); + $_dir = var_export(dirname($fileName), true); + $_namespace = var_export($ns, true); + $_class = var_export(trim($className ?: '', '\\'), true); + $_function = $ns.($ns == '' ? '' : '\\').'{closure}'; + $_method = ($className == '' ? '' : trim($className, '\\').'::').$_function; + $_function = var_export($_function, true); + $_method = var_export($_method, true); + $_trait = null; + + $tokens = $this->getTokens(); + $state = $lastState = 'start'; + $inside_structure = false; + $isFirstClassCallable = false; + $isShortClosure = false; + + $inside_structure_mark = 0; + $open = 0; + $code = ''; + $id_start = $id_start_ci = $id_name = $context = ''; + $classes = $functions = $constants = null; + $use = []; + $lineAdd = 0; + $isUsingScope = false; + $isUsingThisObject = false; + + for ($i = 0, $l = count($tokens); $i < $l; $i++) { + $token = $tokens[$i]; + + switch ($state) { + case 'start': + if ($token[0] === T_FUNCTION || $token[0] === T_STATIC) { + $code .= $token[1]; + + $state = $token[0] === T_FUNCTION ? 'function' : 'static'; + } elseif ($token[0] === T_FN) { + $isShortClosure = true; + $code .= $token[1]; + $state = 'closure_args'; + } elseif ($token[0] === T_PUBLIC || $token[0] === T_PROTECTED || $token[0] === T_PRIVATE) { + $code = ''; + $isFirstClassCallable = true; + } + break; + case 'static': + if ($token[0] === T_WHITESPACE || $token[0] === T_COMMENT || $token[0] === T_FUNCTION) { + $code .= $token[1]; + if ($token[0] === T_FUNCTION) { + $state = 'function'; + } + } elseif ($token[0] === T_FN) { + $isShortClosure = true; + $code .= $token[1]; + $state = 'closure_args'; + } else { + $code = ''; + $state = 'start'; + } + break; + case 'function': + switch ($token[0]) { + case T_STRING: + if ($isFirstClassCallable) { + $state = 'closure_args'; + break; + } + + $code = ''; + $state = 'named_function'; + break; + case '(': + $code .= '('; + $state = 'closure_args'; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + case 'named_function': + if ($token[0] === T_FUNCTION || $token[0] === T_STATIC) { + $code = $token[1]; + $state = $token[0] === T_FUNCTION ? 'function' : 'static'; + } elseif ($token[0] === T_FN) { + $isShortClosure = true; + $code .= $token[1]; + $state = 'closure_args'; + } + break; + case 'closure_args': + switch ($token[0]) { + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $context = 'args'; + $state = 'id_name'; + $lastState = 'closure_args'; + break; + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $context = 'args'; + $state = 'id_name'; + $lastState = 'closure_args'; + break; + case T_USE: + $code .= $token[1]; + $state = 'use'; + break; + case T_DOUBLE_ARROW: + $code .= $token[1]; + if ($isShortClosure) { + $state = 'closure'; + } + break; + case ':': + $code .= ':'; + $state = 'return'; + break; + case '{': + $code .= '{'; + $state = 'closure'; + $open++; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + case 'use': + switch ($token[0]) { + case T_VARIABLE: + $use[] = substr($token[1], 1); + $code .= $token[1]; + break; + case '{': + $code .= '{'; + $state = 'closure'; + $open++; + break; + case ':': + $code .= ':'; + $state = 'return'; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + break; + } + break; + case 'return': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $code .= $token[1]; + break; + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $context = 'return_type'; + $state = 'id_name'; + $lastState = 'return'; + break 2; + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $context = 'return_type'; + $state = 'id_name'; + $lastState = 'return'; + break 2; + case T_DOUBLE_ARROW: + $code .= $token[1]; + if ($isShortClosure) { + $state = 'closure'; + } + break; + case '{': + $code .= '{'; + $state = 'closure'; + $open++; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + break; + } + break; + case 'closure': + switch ($token[0]) { + case T_CURLY_OPEN: + case T_DOLLAR_OPEN_CURLY_BRACES: + case '{': + $code .= is_array($token) ? $token[1] : $token; + $open++; + break; + case '}': + $code .= '}'; + if (--$open === 0 && ! $isShortClosure) { + break 3; + } elseif ($inside_structure) { + $inside_structure = ! ($open === $inside_structure_mark); + } + break; + case '(': + case '[': + $code .= $token[0]; + if ($isShortClosure) { + $open++; + } + break; + case ')': + case ']': + if ($isShortClosure) { + if ($open === 0) { + break 3; + } + $open--; + } + $code .= $token[0]; + break; + case ',': + case ';': + if ($isShortClosure && $open === 0) { + break 3; + } + $code .= $token[0]; + break; + case T_LINE: + $code .= $token[2] - $line + $lineAdd; + break; + case T_FILE: + $code .= $_file; + break; + case T_DIR: + $code .= $_dir; + break; + case T_NS_C: + $code .= $_namespace; + break; + case T_CLASS_C: + $code .= $inside_structure ? $token[1] : $_class; + break; + case T_FUNC_C: + $code .= $inside_structure ? $token[1] : $_function; + break; + case T_METHOD_C: + $code .= $inside_structure ? $token[1] : $_method; + break; + case T_COMMENT: + if (substr($token[1], 0, 8) === '#trackme') { + $timestamp = time(); + $code .= '/**'.PHP_EOL; + $code .= '* Date : '.date(DATE_W3C, $timestamp).PHP_EOL; + $code .= '* Timestamp : '.$timestamp.PHP_EOL; + $code .= '* Line : '.($line + 1).PHP_EOL; + $code .= '* File : '.$_file.PHP_EOL.'*/'.PHP_EOL; + $lineAdd += 5; + } else { + $code .= $token[1]; + } + break; + case T_VARIABLE: + if ($token[1] == '$this' && ! $inside_structure) { + $isUsingThisObject = true; + } + $code .= $token[1]; + break; + case T_STATIC: + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $context = 'root'; + $state = 'id_name'; + $lastState = 'closure'; + break 2; + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $context = 'root'; + $state = 'id_name'; + $lastState = 'closure'; + break 2; + case T_NEW: + $code .= $token[1]; + $context = 'new'; + $state = 'id_start'; + $lastState = 'closure'; + break 2; + case T_USE: + $code .= $token[1]; + $context = 'use'; + $state = 'id_start'; + $lastState = 'closure'; + break; + case T_INSTANCEOF: + case T_INSTEADOF: + $code .= $token[1]; + $context = 'instanceof'; + $state = 'id_start'; + $lastState = 'closure'; + break; + case T_OBJECT_OPERATOR: + case T_NULLSAFE_OBJECT_OPERATOR: + case T_DOUBLE_COLON: + $code .= $token[1]; + $lastState = 'closure'; + $state = 'ignore_next'; + break; + case T_FUNCTION: + $code .= $token[1]; + $state = 'closure_args'; + if (! $inside_structure) { + $inside_structure = true; + $inside_structure_mark = $open; + } + break; + case T_TRAIT_C: + if ($_trait === null) { + $startLine = $this->getStartLine(); + $endLine = $this->getEndLine(); + $structures = $this->getStructures(); + + $_trait = ''; + + foreach ($structures as &$struct) { + if ($struct['type'] === 'trait' && + $struct['start'] <= $startLine && + $struct['end'] >= $endLine + ) { + $_trait = ($ns == '' ? '' : $ns.'\\').$struct['name']; + break; + } + } + + $_trait = var_export($_trait, true); + } + + $code .= $_trait; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + case 'ignore_next': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $code .= $token[1]; + break; + case T_CLASS: + case T_NEW: + case T_STATIC: + case T_VARIABLE: + case T_STRING: + case T_CLASS_C: + case T_FILE: + case T_DIR: + case T_METHOD_C: + case T_FUNC_C: + case T_FUNCTION: + case T_INSTANCEOF: + case T_LINE: + case T_NS_C: + case T_TRAIT_C: + case T_USE: + $code .= $token[1]; + $state = $lastState; + break; + default: + $state = $lastState; + $i--; + } + break; + case 'id_start': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $code .= $token[1]; + break; + case T_NS_SEPARATOR: + case T_NAME_FULLY_QUALIFIED: + case T_STRING: + case T_STATIC: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $state = 'id_name'; + break 2; + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $state = 'id_name'; + break 2; + case T_VARIABLE: + $code .= $token[1]; + $state = $lastState; + break; + case T_CLASS: + $code .= $token[1]; + $state = 'anonymous'; + break; + default: + $i--; //reprocess last + $state = 'id_name'; + } + break; + case 'id_name': + switch ($token[0]) { + case $token[0] === ':' && $context !== 'instanceof': + if ($lastState === 'closure' && $context === 'root') { + $state = 'closure'; + $code .= $id_start.$token; + } + + break; + case T_NAME_QUALIFIED: + case T_NS_SEPARATOR: + case T_STRING: + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + $id_name .= $token[1]; + break; + case '(': + if ($isShortClosure) { + $open++; + } + if ($context === 'new' || false !== strpos($id_name, '\\')) { + if ($id_start_ci === 'self' || $id_start_ci === 'static') { + if (! $inside_structure) { + $isUsingScope = true; + } + } elseif ($id_start !== '\\' && ! in_array($id_start_ci, $class_keywords)) { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if ($id_start[0] !== '\\') { + $id_start = $nsf.'\\'.$id_start; + } + } + } else { + if ($id_start !== '\\') { + if ($functions === null) { + $functions = $this->getFunctions(); + } + if (isset($functions[$id_start_ci])) { + $id_start = $functions[$id_start_ci]; + } elseif ($nsf !== '\\' && function_exists($nsf.'\\'.$id_start)) { + $id_start = $nsf.'\\'.$id_start; + // Cache it to functions array + $functions[$id_start_ci] = $id_start; + } + } + } + $code .= $id_start.$id_name.'('; + $state = $lastState; + break; + case T_VARIABLE: + case T_DOUBLE_COLON: + if ($id_start !== '\\') { + if ($id_start_ci === 'self' || $id_start_ci === 'parent') { + if (! $inside_structure) { + $isUsingScope = true; + } + } elseif ($id_start_ci === 'static') { + if (! $inside_structure) { + $isUsingScope = $token[0] === T_DOUBLE_COLON; + } + } elseif (! (\PHP_MAJOR_VERSION >= 7 && in_array($id_start_ci, $builtin_types))) { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if ($id_start[0] !== '\\') { + $id_start = $nsf.'\\'.$id_start; + } + } + } + + $code .= $id_start.$id_name.$token[1]; + $state = $token[0] === T_DOUBLE_COLON ? 'ignore_next' : $lastState; + break; + default: + if ($id_start !== '\\' && ! defined($id_start)) { + if ($constants === null) { + $constants = $this->getConstants(); + } + if (isset($constants[$id_start])) { + $id_start = $constants[$id_start]; + } elseif ($context === 'new') { + if (in_array($id_start_ci, $class_keywords)) { + if (! $inside_structure) { + $isUsingScope = true; + } + } else { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if ($id_start[0] !== '\\') { + $id_start = $nsf.'\\'.$id_start; + } + } + } elseif ($context === 'use' || + $context === 'instanceof' || + $context === 'args' || + $context === 'return_type' || + $context === 'extends' || + $context === 'root' + ) { + if (in_array($id_start_ci, $class_keywords)) { + if (! $inside_structure && ! $id_start_ci === 'static') { + $isUsingScope = true; + } + } elseif (! (\PHP_MAJOR_VERSION >= 7 && in_array($id_start_ci, $builtin_types))) { + if ($classes === null) { + $classes = $this->getClasses(); + } + if (isset($classes[$id_start_ci])) { + $id_start = $classes[$id_start_ci]; + } + if ($id_start[0] !== '\\') { + $id_start = $nsf.'\\'.$id_start; + } + } + } + } + $code .= $id_start.$id_name; + $state = $lastState; + $i--; //reprocess last token + } + break; + case 'anonymous': + switch ($token[0]) { + case T_NAME_QUALIFIED: + [$id_start, $id_start_ci, $id_name] = $this->parseNameQualified($token[1]); + $state = 'id_name'; + $lastState = 'anonymous'; + break 2; + case T_NS_SEPARATOR: + case T_STRING: + $id_start = $token[1]; + $id_start_ci = strtolower($id_start); + $id_name = ''; + $state = 'id_name'; + $context = 'extends'; + $lastState = 'anonymous'; + break; + case '{': + $state = 'closure'; + if (! $inside_structure) { + $inside_structure = true; + $inside_structure_mark = $open; + } + $i--; + break; + default: + $code .= is_array($token) ? $token[1] : $token; + } + break; + } + } + + if ($isShortClosure) { + $this->useVariables = $this->getStaticVariables(); + } else { + $this->useVariables = empty($use) ? $use : array_intersect_key($this->getStaticVariables(), array_flip($use)); + } + + $this->isShortClosure = $isShortClosure; + $this->isBindingRequired = $isUsingThisObject; + $this->isScopeRequired = $isUsingScope; + + if (PHP_VERSION_ID >= 80100) { + $attributesCode = array_map(function ($attribute) { + $arguments = $attribute->getArguments(); + + $name = $attribute->getName(); + $arguments = implode(', ', array_map(function ($argument, $key) { + $argument = sprintf("'%s'", str_replace("'", "\\'", $argument)); + + if (is_string($key)) { + $argument = sprintf('%s: %s', $key, $argument); + } + + return $argument; + }, $arguments, array_keys($arguments))); + + return "#[$name($arguments)]"; + }, $this->getAttributes()); + + if (! empty($attributesCode)) { + $code = implode("\n", array_merge($attributesCode, [$code])); + } + } + + $this->code = $code; + + return $this->code; + } + + /** + * Get PHP native built in types. + * + * @return array + */ + protected static function getBuiltinTypes() + { + // PHP 8.1 + if (PHP_VERSION_ID >= 80100) { + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void', 'object', 'mixed', 'false', 'null', 'never']; + } + + // PHP 8 + if (\PHP_MAJOR_VERSION === 8) { + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void', 'object', 'mixed', 'false', 'null']; + } + + // PHP 7 + switch (\PHP_MINOR_VERSION) { + case 0: + return ['array', 'callable', 'string', 'int', 'bool', 'float']; + case 1: + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void']; + default: + return ['array', 'callable', 'string', 'int', 'bool', 'float', 'iterable', 'void', 'object']; + } + } + + /** + * Gets the use variables by the closure. + * + * @return array + */ + public function getUseVariables() + { + if ($this->useVariables !== null) { + return $this->useVariables; + } + + $tokens = $this->getTokens(); + $use = []; + $state = 'start'; + + foreach ($tokens as &$token) { + $is_array = is_array($token); + + switch ($state) { + case 'start': + if ($is_array && $token[0] === T_USE) { + $state = 'use'; + } + break; + case 'use': + if ($is_array) { + if ($token[0] === T_VARIABLE) { + $use[] = substr($token[1], 1); + } + } elseif ($token == ')') { + break 2; + } + break; + } + } + + $this->useVariables = empty($use) ? $use : array_intersect_key($this->getStaticVariables(), array_flip($use)); + + return $this->useVariables; + } + + /** + * Checks if binding is required. + * + * @return bool + */ + public function isBindingRequired() + { + if ($this->isBindingRequired === null) { + $this->getCode(); + } + + return $this->isBindingRequired; + } + + /** + * Checks if access to the scope is required. + * + * @return bool + */ + public function isScopeRequired() + { + if ($this->isScopeRequired === null) { + $this->getCode(); + } + + return $this->isScopeRequired; + } + + /** + * The hash of the current file name. + * + * @return string + */ + protected function getHashedFileName() + { + if ($this->hashedName === null) { + $this->hashedName = sha1($this->getFileName()); + } + + return $this->hashedName; + } + + /** + * Get the file tokens. + * + * @return array + */ + protected function getFileTokens() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$files[$key])) { + static::$files[$key] = token_get_all(file_get_contents($this->getFileName())); + } + + return static::$files[$key]; + } + + /** + * Get the tokens. + * + * @return array + */ + protected function getTokens() + { + if ($this->tokens === null) { + $tokens = $this->getFileTokens(); + $startLine = $this->getStartLine(); + $endLine = $this->getEndLine(); + $results = []; + $start = false; + + foreach ($tokens as &$token) { + if (! is_array($token)) { + if ($start) { + $results[] = $token; + } + + continue; + } + + $line = $token[2]; + + if ($line <= $endLine) { + if ($line >= $startLine) { + $start = true; + $results[] = $token; + } + + continue; + } + + break; + } + + $this->tokens = $results; + } + + return $this->tokens; + } + + /** + * Get the classes. + * + * @return array + */ + protected function getClasses() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$classes[$key])) { + $this->fetchItems(); + } + + return static::$classes[$key]; + } + + /** + * Get the functions. + * + * @return array + */ + protected function getFunctions() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$functions[$key])) { + $this->fetchItems(); + } + + return static::$functions[$key]; + } + + /** + * Gets the constants. + * + * @return array + */ + protected function getConstants() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$constants[$key])) { + $this->fetchItems(); + } + + return static::$constants[$key]; + } + + /** + * Get the structures. + * + * @return array + */ + protected function getStructures() + { + $key = $this->getHashedFileName(); + + if (! isset(static::$structures[$key])) { + $this->fetchItems(); + } + + return static::$structures[$key]; + } + + /** + * Fetch the items. + * + * @return void. + */ + protected function fetchItems() + { + $key = $this->getHashedFileName(); + + $classes = []; + $functions = []; + $constants = []; + $structures = []; + $tokens = $this->getFileTokens(); + + $open = 0; + $state = 'start'; + $lastState = ''; + $prefix = ''; + $name = ''; + $alias = ''; + $isFunc = $isConst = false; + + $startLine = $endLine = 0; + $structType = $structName = ''; + $structIgnore = false; + + foreach ($tokens as $token) { + switch ($state) { + case 'start': + switch ($token[0]) { + case T_CLASS: + case T_INTERFACE: + case T_TRAIT: + $state = 'before_structure'; + $startLine = $token[2]; + $structType = $token[0] == T_CLASS + ? 'class' + : ($token[0] == T_INTERFACE ? 'interface' : 'trait'); + break; + case T_USE: + $state = 'use'; + $prefix = $name = $alias = ''; + $isFunc = $isConst = false; + break; + case T_FUNCTION: + $state = 'structure'; + $structIgnore = true; + break; + case T_NEW: + $state = 'new'; + break; + case T_OBJECT_OPERATOR: + case T_DOUBLE_COLON: + $state = 'invoke'; + break; + } + break; + case 'use': + switch ($token[0]) { + case T_FUNCTION: + $isFunc = true; + break; + case T_CONST: + $isConst = true; + break; + case T_NS_SEPARATOR: + $name .= $token[1]; + break; + case T_STRING: + $name .= $token[1]; + $alias = $token[1]; + break; + case T_NAME_QUALIFIED: + $name .= $token[1]; + $pieces = explode('\\', $token[1]); + $alias = end($pieces); + break; + case T_AS: + $lastState = 'use'; + $state = 'alias'; + break; + case '{': + $prefix = $name; + $name = $alias = ''; + $state = 'use-group'; + break; + case ',': + case ';': + if ($name === '' || $name[0] !== '\\') { + $name = '\\'.$name; + } + + if ($alias !== '') { + if ($isFunc) { + $functions[strtolower($alias)] = $name; + } elseif ($isConst) { + $constants[$alias] = $name; + } else { + $classes[strtolower($alias)] = $name; + } + } + $name = $alias = ''; + $state = $token === ';' ? 'start' : 'use'; + break; + } + break; + case 'use-group': + switch ($token[0]) { + case T_NS_SEPARATOR: + $name .= $token[1]; + break; + case T_NAME_QUALIFIED: + $name .= $token[1]; + $pieces = explode('\\', $token[1]); + $alias = end($pieces); + break; + case T_STRING: + $name .= $token[1]; + $alias = $token[1]; + break; + case T_AS: + $lastState = 'use-group'; + $state = 'alias'; + break; + case ',': + case '}': + + if ($prefix === '' || $prefix[0] !== '\\') { + $prefix = '\\'.$prefix; + } + + if ($alias !== '') { + if ($isFunc) { + $functions[strtolower($alias)] = $prefix.$name; + } elseif ($isConst) { + $constants[$alias] = $prefix.$name; + } else { + $classes[strtolower($alias)] = $prefix.$name; + } + } + $name = $alias = ''; + $state = $token === '}' ? 'use' : 'use-group'; + break; + } + break; + case 'alias': + if ($token[0] === T_STRING) { + $alias = $token[1]; + $state = $lastState; + } + break; + case 'new': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + break 2; + case T_CLASS: + $state = 'structure'; + $structIgnore = true; + break; + default: + $state = 'start'; + } + break; + case 'invoke': + switch ($token[0]) { + case T_WHITESPACE: + case T_COMMENT: + case T_DOC_COMMENT: + break 2; + default: + $state = 'start'; + } + break; + case 'before_structure': + if ($token[0] == T_STRING) { + $structName = $token[1]; + $state = 'structure'; + } + break; + case 'structure': + switch ($token[0]) { + case '{': + case T_CURLY_OPEN: + case T_DOLLAR_OPEN_CURLY_BRACES: + $open++; + break; + case '}': + if (--$open == 0) { + if (! $structIgnore) { + $structures[] = [ + 'type' => $structType, + 'name' => $structName, + 'start' => $startLine, + 'end' => $endLine, + ]; + } + $structIgnore = false; + $state = 'start'; + } + break; + default: + if (is_array($token)) { + $endLine = $token[2]; + } + } + break; + } + } + + static::$classes[$key] = $classes; + static::$functions[$key] = $functions; + static::$constants[$key] = $constants; + static::$structures[$key] = $structures; + } + + /** + * Returns the namespace associated to the closure. + * + * @return string + */ + protected function getClosureNamespaceName() + { + $ns = $this->getNamespaceName(); + + // First class callables... + if ($this->getName() !== '{closure}' && empty($ns) && ! is_null($this->getClosureScopeClass())) { + $ns = $this->getClosureScopeClass()->getNamespaceName(); + } + + return $ns; + } + + /** + * Parse the given token. + * + * @param string $token + * @return array + */ + protected function parseNameQualified($token) + { + $pieces = explode('\\', $token); + + $id_start = array_shift($pieces); + + $id_start_ci = strtolower($id_start); + + $id_name = '\\'.implode('\\', $pieces); + + return [$id_start, $id_start_ci, $id_name]; + } +} diff --git a/vendor/laravel/serializable-closure/src/Support/SelfReference.php b/vendor/laravel/serializable-closure/src/Support/SelfReference.php new file mode 100644 index 0000000..5831950 --- /dev/null +++ b/vendor/laravel/serializable-closure/src/Support/SelfReference.php @@ -0,0 +1,24 @@ +hash = $hash; + } +} diff --git a/vendor/laravel/serializable-closure/src/UnsignedSerializableClosure.php b/vendor/laravel/serializable-closure/src/UnsignedSerializableClosure.php new file mode 100644 index 0000000..1588e7c --- /dev/null +++ b/vendor/laravel/serializable-closure/src/UnsignedSerializableClosure.php @@ -0,0 +1,82 @@ +serializable = new Serializers\Native($closure); + } + + /** + * Resolve the closure with the given arguments. + * + * @return mixed + */ + public function __invoke() + { + if (\PHP_VERSION_ID < 70400) { + throw new PhpVersionNotSupportedException(); + } + + return call_user_func_array($this->serializable, func_get_args()); + } + + /** + * Gets the closure. + * + * @return \Closure + */ + public function getClosure() + { + if (\PHP_VERSION_ID < 70400) { + throw new PhpVersionNotSupportedException(); + } + + return $this->serializable->getClosure(); + } + + /** + * Get the serializable representation of the closure. + * + * @return array + */ + public function __serialize() + { + return [ + 'serializable' => $this->serializable, + ]; + } + + /** + * Restore the closure after serialization. + * + * @param array $data + * @return void + */ + public function __unserialize($data) + { + $this->serializable = $data['serializable']; + } +} diff --git a/vendor/nikic/fast-route/.gitignore b/vendor/nikic/fast-route/.gitignore new file mode 100644 index 0000000..e378a07 --- /dev/null +++ b/vendor/nikic/fast-route/.gitignore @@ -0,0 +1,5 @@ +/vendor/ +.idea/ + +# ignore lock file since we have no extra dependencies +composer.lock diff --git a/vendor/nikic/fast-route/.hhconfig b/vendor/nikic/fast-route/.hhconfig new file mode 100644 index 0000000..0c2153c --- /dev/null +++ b/vendor/nikic/fast-route/.hhconfig @@ -0,0 +1 @@ +assume_php=false diff --git a/vendor/nikic/fast-route/.travis.yml b/vendor/nikic/fast-route/.travis.yml new file mode 100644 index 0000000..10f8381 --- /dev/null +++ b/vendor/nikic/fast-route/.travis.yml @@ -0,0 +1,20 @@ +sudo: false +language: php + +php: + - 5.4 + - 5.5 + - 5.6 + - 7.0 + - 7.1 + - 7.2 + - hhvm + +script: + - ./vendor/bin/phpunit + +before_install: + - travis_retry composer self-update + +install: + - composer install diff --git a/vendor/nikic/fast-route/FastRoute.hhi b/vendor/nikic/fast-route/FastRoute.hhi new file mode 100644 index 0000000..8d50738 --- /dev/null +++ b/vendor/nikic/fast-route/FastRoute.hhi @@ -0,0 +1,126 @@ +; + } + + class RouteCollector { + public function __construct(RouteParser $routeParser, DataGenerator $dataGenerator); + public function addRoute(mixed $httpMethod, string $route, mixed $handler): void; + public function getData(): array; + } + + class Route { + public function __construct(string $httpMethod, mixed $handler, string $regex, array $variables); + public function matches(string $str): bool; + } + + interface DataGenerator { + public function addRoute(string $httpMethod, array $routeData, mixed $handler); + public function getData(): array; + } + + interface Dispatcher { + const int NOT_FOUND = 0; + const int FOUND = 1; + const int METHOD_NOT_ALLOWED = 2; + public function dispatch(string $httpMethod, string $uri): array; + } + + function simpleDispatcher( + (function(RouteCollector): void) $routeDefinitionCallback, + shape( + ?'routeParser' => classname, + ?'dataGenerator' => classname, + ?'dispatcher' => classname, + ?'routeCollector' => classname, + ) $options = shape()): Dispatcher; + + function cachedDispatcher( + (function(RouteCollector): void) $routeDefinitionCallback, + shape( + ?'routeParser' => classname, + ?'dataGenerator' => classname, + ?'dispatcher' => classname, + ?'routeCollector' => classname, + ?'cacheDisabled' => bool, + ?'cacheFile' => string, + ) $options = shape()): Dispatcher; +} + +namespace FastRoute\DataGenerator { + abstract class RegexBasedAbstract implements \FastRoute\DataGenerator { + protected abstract function getApproxChunkSize(); + protected abstract function processChunk($regexToRoutesMap); + + public function addRoute(string $httpMethod, array $routeData, mixed $handler): void; + public function getData(): array; + } + + class CharCountBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array $regexToRoutesMap): array; + } + + class GroupCountBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array $regexToRoutesMap): array; + } + + class GroupPosBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array $regexToRoutesMap): array; + } + + class MarkBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array $regexToRoutesMap): array; + } +} + +namespace FastRoute\Dispatcher { + abstract class RegexBasedAbstract implements \FastRoute\Dispatcher { + protected abstract function dispatchVariableRoute(array $routeData, string $uri): array; + + public function dispatch(string $httpMethod, string $uri): array; + } + + class GroupPosBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array $routeData, string $uri): array; + } + + class GroupCountBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array $routeData, string $uri): array; + } + + class CharCountBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array $routeData, string $uri): array; + } + + class MarkBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array $routeData, string $uri): array; + } +} + +namespace FastRoute\RouteParser { + class Std implements \FastRoute\RouteParser { + const string VARIABLE_REGEX = <<<'REGEX' +\{ + \s* ([a-zA-Z][a-zA-Z0-9_]*) \s* + (?: + : \s* ([^{}]*(?:\{(?-1)\}[^{}]*)*) + )? +\} +REGEX; + const string DEFAULT_DISPATCH_REGEX = '[^/]+'; + public function parse(string $route): array; + } +} diff --git a/vendor/nikic/fast-route/LICENSE b/vendor/nikic/fast-route/LICENSE new file mode 100644 index 0000000..478e764 --- /dev/null +++ b/vendor/nikic/fast-route/LICENSE @@ -0,0 +1,31 @@ +Copyright (c) 2013 by Nikita Popov. + +Some 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. + + * The names of the contributors may not be used to endorse or + promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/nikic/fast-route/README.md b/vendor/nikic/fast-route/README.md new file mode 100644 index 0000000..91bd466 --- /dev/null +++ b/vendor/nikic/fast-route/README.md @@ -0,0 +1,313 @@ +FastRoute - Fast request router for PHP +======================================= + +This library provides a fast implementation of a regular expression based router. [Blog post explaining how the +implementation works and why it is fast.][blog_post] + +Install +------- + +To install with composer: + +```sh +composer require nikic/fast-route +``` + +Requires PHP 5.4 or newer. + +Usage +----- + +Here's a basic usage example: + +```php +addRoute('GET', '/users', 'get_all_users_handler'); + // {id} must be a number (\d+) + $r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler'); + // The /{title} suffix is optional + $r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler'); +}); + +// Fetch method and URI from somewhere +$httpMethod = $_SERVER['REQUEST_METHOD']; +$uri = $_SERVER['REQUEST_URI']; + +// Strip query string (?foo=bar) and decode URI +if (false !== $pos = strpos($uri, '?')) { + $uri = substr($uri, 0, $pos); +} +$uri = rawurldecode($uri); + +$routeInfo = $dispatcher->dispatch($httpMethod, $uri); +switch ($routeInfo[0]) { + case FastRoute\Dispatcher::NOT_FOUND: + // ... 404 Not Found + break; + case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: + $allowedMethods = $routeInfo[1]; + // ... 405 Method Not Allowed + break; + case FastRoute\Dispatcher::FOUND: + $handler = $routeInfo[1]; + $vars = $routeInfo[2]; + // ... call $handler with $vars + break; +} +``` + +### Defining routes + +The routes are defined by calling the `FastRoute\simpleDispatcher()` function, which accepts +a callable taking a `FastRoute\RouteCollector` instance. The routes are added by calling +`addRoute()` on the collector instance: + +```php +$r->addRoute($method, $routePattern, $handler); +``` + +The `$method` is an uppercase HTTP method string for which a certain route should match. It +is possible to specify multiple valid methods using an array: + +```php +// These two calls +$r->addRoute('GET', '/test', 'handler'); +$r->addRoute('POST', '/test', 'handler'); +// Are equivalent to this one call +$r->addRoute(['GET', 'POST'], '/test', 'handler'); +``` + +By default the `$routePattern` uses a syntax where `{foo}` specifies a placeholder with name `foo` +and matching the regex `[^/]+`. To adjust the pattern the placeholder matches, you can specify +a custom pattern by writing `{bar:[0-9]+}`. Some examples: + +```php +// Matches /user/42, but not /user/xyz +$r->addRoute('GET', '/user/{id:\d+}', 'handler'); + +// Matches /user/foobar, but not /user/foo/bar +$r->addRoute('GET', '/user/{name}', 'handler'); + +// Matches /user/foo/bar as well +$r->addRoute('GET', '/user/{name:.+}', 'handler'); +``` + +Custom patterns for route placeholders cannot use capturing groups. For example `{lang:(en|de)}` +is not a valid placeholder, because `()` is a capturing group. Instead you can use either +`{lang:en|de}` or `{lang:(?:en|de)}`. + +Furthermore parts of the route enclosed in `[...]` are considered optional, so that `/foo[bar]` +will match both `/foo` and `/foobar`. Optional parts are only supported in a trailing position, +not in the middle of a route. + +```php +// This route +$r->addRoute('GET', '/user/{id:\d+}[/{name}]', 'handler'); +// Is equivalent to these two routes +$r->addRoute('GET', '/user/{id:\d+}', 'handler'); +$r->addRoute('GET', '/user/{id:\d+}/{name}', 'handler'); + +// Multiple nested optional parts are possible as well +$r->addRoute('GET', '/user[/{id:\d+}[/{name}]]', 'handler'); + +// This route is NOT valid, because optional parts can only occur at the end +$r->addRoute('GET', '/user[/{id:\d+}]/{name}', 'handler'); +``` + +The `$handler` parameter does not necessarily have to be a callback, it could also be a controller +class name or any other kind of data you wish to associate with the route. FastRoute only tells you +which handler corresponds to your URI, how you interpret it is up to you. + +#### Shorcut methods for common request methods + +For the `GET`, `POST`, `PUT`, `PATCH`, `DELETE` and `HEAD` request methods shortcut methods are available. For example: + +```php +$r->get('/get-route', 'get_handler'); +$r->post('/post-route', 'post_handler'); +``` + +Is equivalent to: + +```php +$r->addRoute('GET', '/get-route', 'get_handler'); +$r->addRoute('POST', '/post-route', 'post_handler'); +``` + +#### Route Groups + +Additionally, you can specify routes inside of a group. All routes defined inside a group will have a common prefix. + +For example, defining your routes as: + +```php +$r->addGroup('/admin', function (RouteCollector $r) { + $r->addRoute('GET', '/do-something', 'handler'); + $r->addRoute('GET', '/do-another-thing', 'handler'); + $r->addRoute('GET', '/do-something-else', 'handler'); +}); +``` + +Will have the same result as: + + ```php +$r->addRoute('GET', '/admin/do-something', 'handler'); +$r->addRoute('GET', '/admin/do-another-thing', 'handler'); +$r->addRoute('GET', '/admin/do-something-else', 'handler'); + ``` + +Nested groups are also supported, in which case the prefixes of all the nested groups are combined. + +### Caching + +The reason `simpleDispatcher` accepts a callback for defining the routes is to allow seamless +caching. By using `cachedDispatcher` instead of `simpleDispatcher` you can cache the generated +routing data and construct the dispatcher from the cached information: + +```php +addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); + $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1'); + $r->addRoute('GET', '/user/{name}', 'handler2'); +}, [ + 'cacheFile' => __DIR__ . '/route.cache', /* required */ + 'cacheDisabled' => IS_DEBUG_ENABLED, /* optional, enabled by default */ +]); +``` + +The second parameter to the function is an options array, which can be used to specify the cache +file location, among other things. + +### Dispatching a URI + +A URI is dispatched by calling the `dispatch()` method of the created dispatcher. This method +accepts the HTTP method and a URI. Getting those two bits of information (and normalizing them +appropriately) is your job - this library is not bound to the PHP web SAPIs. + +The `dispatch()` method returns an array whose first element contains a status code. It is one +of `Dispatcher::NOT_FOUND`, `Dispatcher::METHOD_NOT_ALLOWED` and `Dispatcher::FOUND`. For the +method not allowed status the second array element contains a list of HTTP methods allowed for +the supplied URI. For example: + + [FastRoute\Dispatcher::METHOD_NOT_ALLOWED, ['GET', 'POST']] + +> **NOTE:** The HTTP specification requires that a `405 Method Not Allowed` response include the +`Allow:` header to detail available methods for the requested resource. Applications using FastRoute +should use the second array element to add this header when relaying a 405 response. + +For the found status the second array element is the handler that was associated with the route +and the third array element is a dictionary of placeholder names to their values. For example: + + /* Routing against GET /user/nikic/42 */ + + [FastRoute\Dispatcher::FOUND, 'handler0', ['name' => 'nikic', 'id' => '42']] + +### Overriding the route parser and dispatcher + +The routing process makes use of three components: A route parser, a data generator and a +dispatcher. The three components adhere to the following interfaces: + +```php + 'FastRoute\\RouteParser\\Std', + 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased', + 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased', +]); +``` + +The above options array corresponds to the defaults. By replacing `GroupCountBased` by +`GroupPosBased` you could switch to a different dispatching strategy. + +### A Note on HEAD Requests + +The HTTP spec requires servers to [support both GET and HEAD methods][2616-511]: + +> The methods GET and HEAD MUST be supported by all general-purpose servers + +To avoid forcing users to manually register HEAD routes for each resource we fallback to matching an +available GET route for a given resource. The PHP web SAPI transparently removes the entity body +from HEAD responses so this behavior has no effect on the vast majority of users. + +However, implementers using FastRoute outside the web SAPI environment (e.g. a custom server) MUST +NOT send entity bodies generated in response to HEAD requests. If you are a non-SAPI user this is +*your responsibility*; FastRoute has no purview to prevent you from breaking HTTP in such cases. + +Finally, note that applications MAY always specify their own HEAD method route for a given +resource to bypass this behavior entirely. + +### Credits + +This library is based on a router that [Levi Morrison][levi] implemented for the Aerys server. + +A large number of tests, as well as HTTP compliance considerations, were provided by [Daniel Lowrey][rdlowrey]. + + +[2616-511]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1 "RFC 2616 Section 5.1.1" +[blog_post]: http://nikic.github.io/2014/02/18/Fast-request-routing-using-regular-expressions.html +[levi]: https://github.com/morrisonlevi +[rdlowrey]: https://github.com/rdlowrey diff --git a/vendor/nikic/fast-route/composer.json b/vendor/nikic/fast-route/composer.json new file mode 100644 index 0000000..fb446a2 --- /dev/null +++ b/vendor/nikic/fast-route/composer.json @@ -0,0 +1,24 @@ +{ + "name": "nikic/fast-route", + "description": "Fast request router for PHP", + "keywords": ["routing", "router"], + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "autoload": { + "psr-4": { + "FastRoute\\": "src/" + }, + "files": ["src/functions.php"] + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35|~5.7" + } +} diff --git a/vendor/nikic/fast-route/phpunit.xml b/vendor/nikic/fast-route/phpunit.xml new file mode 100644 index 0000000..3c807b6 --- /dev/null +++ b/vendor/nikic/fast-route/phpunit.xml @@ -0,0 +1,24 @@ + + + + + + ./test/ + + + + + + ./src/ + + + diff --git a/vendor/nikic/fast-route/psalm.xml b/vendor/nikic/fast-route/psalm.xml new file mode 100644 index 0000000..0dca5d7 --- /dev/null +++ b/vendor/nikic/fast-route/psalm.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/nikic/fast-route/src/BadRouteException.php b/vendor/nikic/fast-route/src/BadRouteException.php new file mode 100644 index 0000000..62262ec --- /dev/null +++ b/vendor/nikic/fast-route/src/BadRouteException.php @@ -0,0 +1,7 @@ + $route) { + $suffixLen++; + $suffix .= "\t"; + + $regexes[] = '(?:' . $regex . '/(\t{' . $suffixLen . '})\t{' . ($count - $suffixLen) . '})'; + $routeMap[$suffix] = [$route->handler, $route->variables]; + } + + $regex = '~^(?|' . implode('|', $regexes) . ')$~'; + return ['regex' => $regex, 'suffix' => '/' . $suffix, 'routeMap' => $routeMap]; + } +} diff --git a/vendor/nikic/fast-route/src/DataGenerator/GroupCountBased.php b/vendor/nikic/fast-route/src/DataGenerator/GroupCountBased.php new file mode 100644 index 0000000..54d9a05 --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator/GroupCountBased.php @@ -0,0 +1,30 @@ + $route) { + $numVariables = count($route->variables); + $numGroups = max($numGroups, $numVariables); + + $regexes[] = $regex . str_repeat('()', $numGroups - $numVariables); + $routeMap[$numGroups + 1] = [$route->handler, $route->variables]; + + ++$numGroups; + } + + $regex = '~^(?|' . implode('|', $regexes) . ')$~'; + return ['regex' => $regex, 'routeMap' => $routeMap]; + } +} diff --git a/vendor/nikic/fast-route/src/DataGenerator/GroupPosBased.php b/vendor/nikic/fast-route/src/DataGenerator/GroupPosBased.php new file mode 100644 index 0000000..fc4dc0a --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator/GroupPosBased.php @@ -0,0 +1,27 @@ + $route) { + $regexes[] = $regex; + $routeMap[$offset] = [$route->handler, $route->variables]; + + $offset += count($route->variables); + } + + $regex = '~^(?:' . implode('|', $regexes) . ')$~'; + return ['regex' => $regex, 'routeMap' => $routeMap]; + } +} diff --git a/vendor/nikic/fast-route/src/DataGenerator/MarkBased.php b/vendor/nikic/fast-route/src/DataGenerator/MarkBased.php new file mode 100644 index 0000000..0aebed9 --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator/MarkBased.php @@ -0,0 +1,27 @@ + $route) { + $regexes[] = $regex . '(*MARK:' . $markName . ')'; + $routeMap[$markName] = [$route->handler, $route->variables]; + + ++$markName; + } + + $regex = '~^(?|' . implode('|', $regexes) . ')$~'; + return ['regex' => $regex, 'routeMap' => $routeMap]; + } +} diff --git a/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php b/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php new file mode 100644 index 0000000..6457290 --- /dev/null +++ b/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php @@ -0,0 +1,186 @@ +isStaticRoute($routeData)) { + $this->addStaticRoute($httpMethod, $routeData, $handler); + } else { + $this->addVariableRoute($httpMethod, $routeData, $handler); + } + } + + /** + * @return mixed[] + */ + public function getData() + { + if (empty($this->methodToRegexToRoutesMap)) { + return [$this->staticRoutes, []]; + } + + return [$this->staticRoutes, $this->generateVariableRouteData()]; + } + + /** + * @return mixed[] + */ + private function generateVariableRouteData() + { + $data = []; + foreach ($this->methodToRegexToRoutesMap as $method => $regexToRoutesMap) { + $chunkSize = $this->computeChunkSize(count($regexToRoutesMap)); + $chunks = array_chunk($regexToRoutesMap, $chunkSize, true); + $data[$method] = array_map([$this, 'processChunk'], $chunks); + } + return $data; + } + + /** + * @param int + * @return int + */ + private function computeChunkSize($count) + { + $numParts = max(1, round($count / $this->getApproxChunkSize())); + return (int) ceil($count / $numParts); + } + + /** + * @param mixed[] + * @return bool + */ + private function isStaticRoute($routeData) + { + return count($routeData) === 1 && is_string($routeData[0]); + } + + private function addStaticRoute($httpMethod, $routeData, $handler) + { + $routeStr = $routeData[0]; + + if (isset($this->staticRoutes[$httpMethod][$routeStr])) { + throw new BadRouteException(sprintf( + 'Cannot register two routes matching "%s" for method "%s"', + $routeStr, $httpMethod + )); + } + + if (isset($this->methodToRegexToRoutesMap[$httpMethod])) { + foreach ($this->methodToRegexToRoutesMap[$httpMethod] as $route) { + if ($route->matches($routeStr)) { + throw new BadRouteException(sprintf( + 'Static route "%s" is shadowed by previously defined variable route "%s" for method "%s"', + $routeStr, $route->regex, $httpMethod + )); + } + } + } + + $this->staticRoutes[$httpMethod][$routeStr] = $handler; + } + + private function addVariableRoute($httpMethod, $routeData, $handler) + { + list($regex, $variables) = $this->buildRegexForRoute($routeData); + + if (isset($this->methodToRegexToRoutesMap[$httpMethod][$regex])) { + throw new BadRouteException(sprintf( + 'Cannot register two routes matching "%s" for method "%s"', + $regex, $httpMethod + )); + } + + $this->methodToRegexToRoutesMap[$httpMethod][$regex] = new Route( + $httpMethod, $handler, $regex, $variables + ); + } + + /** + * @param mixed[] + * @return mixed[] + */ + private function buildRegexForRoute($routeData) + { + $regex = ''; + $variables = []; + foreach ($routeData as $part) { + if (is_string($part)) { + $regex .= preg_quote($part, '~'); + continue; + } + + list($varName, $regexPart) = $part; + + if (isset($variables[$varName])) { + throw new BadRouteException(sprintf( + 'Cannot use the same placeholder "%s" twice', $varName + )); + } + + if ($this->regexHasCapturingGroups($regexPart)) { + throw new BadRouteException(sprintf( + 'Regex "%s" for parameter "%s" contains a capturing group', + $regexPart, $varName + )); + } + + $variables[$varName] = $varName; + $regex .= '(' . $regexPart . ')'; + } + + return [$regex, $variables]; + } + + /** + * @param string + * @return bool + */ + private function regexHasCapturingGroups($regex) + { + if (false === strpos($regex, '(')) { + // Needs to have at least a ( to contain a capturing group + return false; + } + + // Semi-accurate detection for capturing groups + return (bool) preg_match( + '~ + (?: + \(\?\( + | \[ [^\]\\\\]* (?: \\\\ . [^\]\\\\]* )* \] + | \\\\ . + ) (*SKIP)(*FAIL) | + \( + (?! + \? (?! <(?![!=]) | P< | \' ) + | \* + ) + ~x', + $regex + ); + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher.php b/vendor/nikic/fast-route/src/Dispatcher.php new file mode 100644 index 0000000..4ae72a3 --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher.php @@ -0,0 +1,26 @@ + 'value', ...]] + * + * @param string $httpMethod + * @param string $uri + * + * @return array + */ + public function dispatch($httpMethod, $uri); +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/CharCountBased.php b/vendor/nikic/fast-route/src/Dispatcher/CharCountBased.php new file mode 100644 index 0000000..ef1eec1 --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/CharCountBased.php @@ -0,0 +1,31 @@ +staticRouteMap, $this->variableRouteData) = $data; + } + + protected function dispatchVariableRoute($routeData, $uri) + { + foreach ($routeData as $data) { + if (!preg_match($data['regex'], $uri . $data['suffix'], $matches)) { + continue; + } + + list($handler, $varNames) = $data['routeMap'][end($matches)]; + + $vars = []; + $i = 0; + foreach ($varNames as $varName) { + $vars[$varName] = $matches[++$i]; + } + return [self::FOUND, $handler, $vars]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/GroupCountBased.php b/vendor/nikic/fast-route/src/Dispatcher/GroupCountBased.php new file mode 100644 index 0000000..493e7a9 --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/GroupCountBased.php @@ -0,0 +1,31 @@ +staticRouteMap, $this->variableRouteData) = $data; + } + + protected function dispatchVariableRoute($routeData, $uri) + { + foreach ($routeData as $data) { + if (!preg_match($data['regex'], $uri, $matches)) { + continue; + } + + list($handler, $varNames) = $data['routeMap'][count($matches)]; + + $vars = []; + $i = 0; + foreach ($varNames as $varName) { + $vars[$varName] = $matches[++$i]; + } + return [self::FOUND, $handler, $vars]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/GroupPosBased.php b/vendor/nikic/fast-route/src/Dispatcher/GroupPosBased.php new file mode 100644 index 0000000..498220e --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/GroupPosBased.php @@ -0,0 +1,33 @@ +staticRouteMap, $this->variableRouteData) = $data; + } + + protected function dispatchVariableRoute($routeData, $uri) + { + foreach ($routeData as $data) { + if (!preg_match($data['regex'], $uri, $matches)) { + continue; + } + + // find first non-empty match + for ($i = 1; '' === $matches[$i]; ++$i); + + list($handler, $varNames) = $data['routeMap'][$i]; + + $vars = []; + foreach ($varNames as $varName) { + $vars[$varName] = $matches[$i++]; + } + return [self::FOUND, $handler, $vars]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/MarkBased.php b/vendor/nikic/fast-route/src/Dispatcher/MarkBased.php new file mode 100644 index 0000000..22eb09b --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/MarkBased.php @@ -0,0 +1,31 @@ +staticRouteMap, $this->variableRouteData) = $data; + } + + protected function dispatchVariableRoute($routeData, $uri) + { + foreach ($routeData as $data) { + if (!preg_match($data['regex'], $uri, $matches)) { + continue; + } + + list($handler, $varNames) = $data['routeMap'][$matches['MARK']]; + + $vars = []; + $i = 0; + foreach ($varNames as $varName) { + $vars[$varName] = $matches[++$i]; + } + return [self::FOUND, $handler, $vars]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php b/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php new file mode 100644 index 0000000..206e879 --- /dev/null +++ b/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php @@ -0,0 +1,88 @@ +staticRouteMap[$httpMethod][$uri])) { + $handler = $this->staticRouteMap[$httpMethod][$uri]; + return [self::FOUND, $handler, []]; + } + + $varRouteData = $this->variableRouteData; + if (isset($varRouteData[$httpMethod])) { + $result = $this->dispatchVariableRoute($varRouteData[$httpMethod], $uri); + if ($result[0] === self::FOUND) { + return $result; + } + } + + // For HEAD requests, attempt fallback to GET + if ($httpMethod === 'HEAD') { + if (isset($this->staticRouteMap['GET'][$uri])) { + $handler = $this->staticRouteMap['GET'][$uri]; + return [self::FOUND, $handler, []]; + } + if (isset($varRouteData['GET'])) { + $result = $this->dispatchVariableRoute($varRouteData['GET'], $uri); + if ($result[0] === self::FOUND) { + return $result; + } + } + } + + // If nothing else matches, try fallback routes + if (isset($this->staticRouteMap['*'][$uri])) { + $handler = $this->staticRouteMap['*'][$uri]; + return [self::FOUND, $handler, []]; + } + if (isset($varRouteData['*'])) { + $result = $this->dispatchVariableRoute($varRouteData['*'], $uri); + if ($result[0] === self::FOUND) { + return $result; + } + } + + // Find allowed methods for this URI by matching against all other HTTP methods as well + $allowedMethods = []; + + foreach ($this->staticRouteMap as $method => $uriMap) { + if ($method !== $httpMethod && isset($uriMap[$uri])) { + $allowedMethods[] = $method; + } + } + + foreach ($varRouteData as $method => $routeData) { + if ($method === $httpMethod) { + continue; + } + + $result = $this->dispatchVariableRoute($routeData, $uri); + if ($result[0] === self::FOUND) { + $allowedMethods[] = $method; + } + } + + // If there are no allowed methods the route simply does not exist + if ($allowedMethods) { + return [self::METHOD_NOT_ALLOWED, $allowedMethods]; + } + + return [self::NOT_FOUND]; + } +} diff --git a/vendor/nikic/fast-route/src/Route.php b/vendor/nikic/fast-route/src/Route.php new file mode 100644 index 0000000..e1bf7dd --- /dev/null +++ b/vendor/nikic/fast-route/src/Route.php @@ -0,0 +1,47 @@ +httpMethod = $httpMethod; + $this->handler = $handler; + $this->regex = $regex; + $this->variables = $variables; + } + + /** + * Tests whether this route matches the given string. + * + * @param string $str + * + * @return bool + */ + public function matches($str) + { + $regex = '~^' . $this->regex . '$~'; + return (bool) preg_match($regex, $str); + } +} diff --git a/vendor/nikic/fast-route/src/RouteCollector.php b/vendor/nikic/fast-route/src/RouteCollector.php new file mode 100644 index 0000000..c1c1762 --- /dev/null +++ b/vendor/nikic/fast-route/src/RouteCollector.php @@ -0,0 +1,152 @@ +routeParser = $routeParser; + $this->dataGenerator = $dataGenerator; + $this->currentGroupPrefix = ''; + } + + /** + * Adds a route to the collection. + * + * The syntax used in the $route string depends on the used route parser. + * + * @param string|string[] $httpMethod + * @param string $route + * @param mixed $handler + */ + public function addRoute($httpMethod, $route, $handler) + { + $route = $this->currentGroupPrefix . $route; + $routeDatas = $this->routeParser->parse($route); + foreach ((array) $httpMethod as $method) { + foreach ($routeDatas as $routeData) { + $this->dataGenerator->addRoute($method, $routeData, $handler); + } + } + } + + /** + * Create a route group with a common prefix. + * + * All routes created in the passed callback will have the given group prefix prepended. + * + * @param string $prefix + * @param callable $callback + */ + public function addGroup($prefix, callable $callback) + { + $previousGroupPrefix = $this->currentGroupPrefix; + $this->currentGroupPrefix = $previousGroupPrefix . $prefix; + $callback($this); + $this->currentGroupPrefix = $previousGroupPrefix; + } + + /** + * Adds a GET route to the collection + * + * This is simply an alias of $this->addRoute('GET', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function get($route, $handler) + { + $this->addRoute('GET', $route, $handler); + } + + /** + * Adds a POST route to the collection + * + * This is simply an alias of $this->addRoute('POST', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function post($route, $handler) + { + $this->addRoute('POST', $route, $handler); + } + + /** + * Adds a PUT route to the collection + * + * This is simply an alias of $this->addRoute('PUT', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function put($route, $handler) + { + $this->addRoute('PUT', $route, $handler); + } + + /** + * Adds a DELETE route to the collection + * + * This is simply an alias of $this->addRoute('DELETE', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function delete($route, $handler) + { + $this->addRoute('DELETE', $route, $handler); + } + + /** + * Adds a PATCH route to the collection + * + * This is simply an alias of $this->addRoute('PATCH', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function patch($route, $handler) + { + $this->addRoute('PATCH', $route, $handler); + } + + /** + * Adds a HEAD route to the collection + * + * This is simply an alias of $this->addRoute('HEAD', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function head($route, $handler) + { + $this->addRoute('HEAD', $route, $handler); + } + + /** + * Returns the collected route data, as provided by the data generator. + * + * @return array + */ + public function getData() + { + return $this->dataGenerator->getData(); + } +} diff --git a/vendor/nikic/fast-route/src/RouteParser.php b/vendor/nikic/fast-route/src/RouteParser.php new file mode 100644 index 0000000..6a7685c --- /dev/null +++ b/vendor/nikic/fast-route/src/RouteParser.php @@ -0,0 +1,37 @@ + $segment) { + if ($segment === '' && $n !== 0) { + throw new BadRouteException('Empty optional part'); + } + + $currentRoute .= $segment; + $routeDatas[] = $this->parsePlaceholders($currentRoute); + } + return $routeDatas; + } + + /** + * Parses a route string that does not contain optional segments. + * + * @param string + * @return mixed[] + */ + private function parsePlaceholders($route) + { + if (!preg_match_all( + '~' . self::VARIABLE_REGEX . '~x', $route, $matches, + PREG_OFFSET_CAPTURE | PREG_SET_ORDER + )) { + return [$route]; + } + + $offset = 0; + $routeData = []; + foreach ($matches as $set) { + if ($set[0][1] > $offset) { + $routeData[] = substr($route, $offset, $set[0][1] - $offset); + } + $routeData[] = [ + $set[1][0], + isset($set[2]) ? trim($set[2][0]) : self::DEFAULT_DISPATCH_REGEX + ]; + $offset = $set[0][1] + strlen($set[0][0]); + } + + if ($offset !== strlen($route)) { + $routeData[] = substr($route, $offset); + } + + return $routeData; + } +} diff --git a/vendor/nikic/fast-route/src/bootstrap.php b/vendor/nikic/fast-route/src/bootstrap.php new file mode 100644 index 0000000..0bce3a4 --- /dev/null +++ b/vendor/nikic/fast-route/src/bootstrap.php @@ -0,0 +1,12 @@ + 'FastRoute\\RouteParser\\Std', + 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased', + 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased', + 'routeCollector' => 'FastRoute\\RouteCollector', + ]; + + /** @var RouteCollector $routeCollector */ + $routeCollector = new $options['routeCollector']( + new $options['routeParser'], new $options['dataGenerator'] + ); + $routeDefinitionCallback($routeCollector); + + return new $options['dispatcher']($routeCollector->getData()); + } + + /** + * @param callable $routeDefinitionCallback + * @param array $options + * + * @return Dispatcher + */ + function cachedDispatcher(callable $routeDefinitionCallback, array $options = []) + { + $options += [ + 'routeParser' => 'FastRoute\\RouteParser\\Std', + 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased', + 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased', + 'routeCollector' => 'FastRoute\\RouteCollector', + 'cacheDisabled' => false, + ]; + + if (!isset($options['cacheFile'])) { + throw new \LogicException('Must specify "cacheFile" option'); + } + + if (!$options['cacheDisabled'] && file_exists($options['cacheFile'])) { + $dispatchData = require $options['cacheFile']; + if (!is_array($dispatchData)) { + throw new \RuntimeException('Invalid cache file "' . $options['cacheFile'] . '"'); + } + return new $options['dispatcher']($dispatchData); + } + + $routeCollector = new $options['routeCollector']( + new $options['routeParser'], new $options['dataGenerator'] + ); + $routeDefinitionCallback($routeCollector); + + /** @var RouteCollector $routeCollector */ + $dispatchData = $routeCollector->getData(); + if (!$options['cacheDisabled']) { + file_put_contents( + $options['cacheFile'], + ' $this->getDataGeneratorClass(), + 'dispatcher' => $this->getDispatcherClass() + ]; + } + + /** + * @dataProvider provideFoundDispatchCases + */ + public function testFoundDispatches($method, $uri, $callback, $handler, $argDict) + { + $dispatcher = \FastRoute\simpleDispatcher($callback, $this->generateDispatcherOptions()); + $info = $dispatcher->dispatch($method, $uri); + $this->assertSame($dispatcher::FOUND, $info[0]); + $this->assertSame($handler, $info[1]); + $this->assertSame($argDict, $info[2]); + } + + /** + * @dataProvider provideNotFoundDispatchCases + */ + public function testNotFoundDispatches($method, $uri, $callback) + { + $dispatcher = \FastRoute\simpleDispatcher($callback, $this->generateDispatcherOptions()); + $routeInfo = $dispatcher->dispatch($method, $uri); + $this->assertArrayNotHasKey(1, $routeInfo, + 'NOT_FOUND result must only contain a single element in the returned info array' + ); + $this->assertSame($dispatcher::NOT_FOUND, $routeInfo[0]); + } + + /** + * @dataProvider provideMethodNotAllowedDispatchCases + */ + public function testMethodNotAllowedDispatches($method, $uri, $callback, $availableMethods) + { + $dispatcher = \FastRoute\simpleDispatcher($callback, $this->generateDispatcherOptions()); + $routeInfo = $dispatcher->dispatch($method, $uri); + $this->assertArrayHasKey(1, $routeInfo, + 'METHOD_NOT_ALLOWED result must return an array of allowed methods at index 1' + ); + + list($routedStatus, $methodArray) = $dispatcher->dispatch($method, $uri); + $this->assertSame($dispatcher::METHOD_NOT_ALLOWED, $routedStatus); + $this->assertSame($availableMethods, $methodArray); + } + + /** + * @expectedException \FastRoute\BadRouteException + * @expectedExceptionMessage Cannot use the same placeholder "test" twice + */ + public function testDuplicateVariableNameError() + { + \FastRoute\simpleDispatcher(function (RouteCollector $r) { + $r->addRoute('GET', '/foo/{test}/{test:\d+}', 'handler0'); + }, $this->generateDispatcherOptions()); + } + + /** + * @expectedException \FastRoute\BadRouteException + * @expectedExceptionMessage Cannot register two routes matching "/user/([^/]+)" for method "GET" + */ + public function testDuplicateVariableRoute() + { + \FastRoute\simpleDispatcher(function (RouteCollector $r) { + $r->addRoute('GET', '/user/{id}', 'handler0'); // oops, forgot \d+ restriction ;) + $r->addRoute('GET', '/user/{name}', 'handler1'); + }, $this->generateDispatcherOptions()); + } + + /** + * @expectedException \FastRoute\BadRouteException + * @expectedExceptionMessage Cannot register two routes matching "/user" for method "GET" + */ + public function testDuplicateStaticRoute() + { + \FastRoute\simpleDispatcher(function (RouteCollector $r) { + $r->addRoute('GET', '/user', 'handler0'); + $r->addRoute('GET', '/user', 'handler1'); + }, $this->generateDispatcherOptions()); + } + + /** + * @expectedException \FastRoute\BadRouteException + * @expectedExceptionMessage Static route "/user/nikic" is shadowed by previously defined variable route "/user/([^/]+)" for method "GET" + */ + public function testShadowedStaticRoute() + { + \FastRoute\simpleDispatcher(function (RouteCollector $r) { + $r->addRoute('GET', '/user/{name}', 'handler0'); + $r->addRoute('GET', '/user/nikic', 'handler1'); + }, $this->generateDispatcherOptions()); + } + + /** + * @expectedException \FastRoute\BadRouteException + * @expectedExceptionMessage Regex "(en|de)" for parameter "lang" contains a capturing group + */ + public function testCapturing() + { + \FastRoute\simpleDispatcher(function (RouteCollector $r) { + $r->addRoute('GET', '/{lang:(en|de)}', 'handler0'); + }, $this->generateDispatcherOptions()); + } + + public function provideFoundDispatchCases() + { + $cases = []; + + // 0 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/resource/123/456', 'handler0'); + }; + + $method = 'GET'; + $uri = '/resource/123/456'; + $handler = 'handler0'; + $argDict = []; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 1 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/handler0', 'handler0'); + $r->addRoute('GET', '/handler1', 'handler1'); + $r->addRoute('GET', '/handler2', 'handler2'); + }; + + $method = 'GET'; + $uri = '/handler2'; + $handler = 'handler2'; + $argDict = []; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 2 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); + $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1'); + $r->addRoute('GET', '/user/{name}', 'handler2'); + }; + + $method = 'GET'; + $uri = '/user/rdlowrey'; + $handler = 'handler2'; + $argDict = ['name' => 'rdlowrey']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 3 --------------------------------------------------------------------------------------> + + // reuse $callback from #2 + + $method = 'GET'; + $uri = '/user/12345'; + $handler = 'handler1'; + $argDict = ['id' => '12345']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 4 --------------------------------------------------------------------------------------> + + // reuse $callback from #3 + + $method = 'GET'; + $uri = '/user/NaN'; + $handler = 'handler2'; + $argDict = ['name' => 'NaN']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 5 --------------------------------------------------------------------------------------> + + // reuse $callback from #4 + + $method = 'GET'; + $uri = '/user/rdlowrey/12345'; + $handler = 'handler0'; + $argDict = ['name' => 'rdlowrey', 'id' => '12345']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 6 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler0'); + $r->addRoute('GET', '/user/12345/extension', 'handler1'); + $r->addRoute('GET', '/user/{id:[0-9]+}.{extension}', 'handler2'); + }; + + $method = 'GET'; + $uri = '/user/12345.svg'; + $handler = 'handler2'; + $argDict = ['id' => '12345', 'extension' => 'svg']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 7 ----- Test GET method fallback on HEAD route miss ------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/user/{name}', 'handler0'); + $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler1'); + $r->addRoute('GET', '/static0', 'handler2'); + $r->addRoute('GET', '/static1', 'handler3'); + $r->addRoute('HEAD', '/static1', 'handler4'); + }; + + $method = 'HEAD'; + $uri = '/user/rdlowrey'; + $handler = 'handler0'; + $argDict = ['name' => 'rdlowrey']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 8 ----- Test GET method fallback on HEAD route miss ------------------------------------> + + // reuse $callback from #7 + + $method = 'HEAD'; + $uri = '/user/rdlowrey/1234'; + $handler = 'handler1'; + $argDict = ['name' => 'rdlowrey', 'id' => '1234']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 9 ----- Test GET method fallback on HEAD route miss ------------------------------------> + + // reuse $callback from #8 + + $method = 'HEAD'; + $uri = '/static0'; + $handler = 'handler2'; + $argDict = []; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 10 ---- Test existing HEAD route used if available (no fallback) -----------------------> + + // reuse $callback from #9 + + $method = 'HEAD'; + $uri = '/static1'; + $handler = 'handler4'; + $argDict = []; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 11 ---- More specified routes are not shadowed by less specific of another method ------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/user/{name}', 'handler0'); + $r->addRoute('POST', '/user/{name:[a-z]+}', 'handler1'); + }; + + $method = 'POST'; + $uri = '/user/rdlowrey'; + $handler = 'handler1'; + $argDict = ['name' => 'rdlowrey']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 12 ---- Handler of more specific routes is used, if it occurs first --------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/user/{name}', 'handler0'); + $r->addRoute('POST', '/user/{name:[a-z]+}', 'handler1'); + $r->addRoute('POST', '/user/{name}', 'handler2'); + }; + + $method = 'POST'; + $uri = '/user/rdlowrey'; + $handler = 'handler1'; + $argDict = ['name' => 'rdlowrey']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 13 ---- Route with constant suffix -----------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/user/{name}', 'handler0'); + $r->addRoute('GET', '/user/{name}/edit', 'handler1'); + }; + + $method = 'GET'; + $uri = '/user/rdlowrey/edit'; + $handler = 'handler1'; + $argDict = ['name' => 'rdlowrey']; + + $cases[] = [$method, $uri, $callback, $handler, $argDict]; + + // 14 ---- Handle multiple methods with the same handler ----------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute(['GET', 'POST'], '/user', 'handlerGetPost'); + $r->addRoute(['DELETE'], '/user', 'handlerDelete'); + $r->addRoute([], '/user', 'handlerNone'); + }; + + $argDict = []; + $cases[] = ['GET', '/user', $callback, 'handlerGetPost', $argDict]; + $cases[] = ['POST', '/user', $callback, 'handlerGetPost', $argDict]; + $cases[] = ['DELETE', '/user', $callback, 'handlerDelete', $argDict]; + + // 17 ---- + + $callback = function (RouteCollector $r) { + $r->addRoute('POST', '/user.json', 'handler0'); + $r->addRoute('GET', '/{entity}.json', 'handler1'); + }; + + $cases[] = ['GET', '/user.json', $callback, 'handler1', ['entity' => 'user']]; + + // 18 ---- + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '', 'handler0'); + }; + + $cases[] = ['GET', '', $callback, 'handler0', []]; + + // 19 ---- + + $callback = function (RouteCollector $r) { + $r->addRoute('HEAD', '/a/{foo}', 'handler0'); + $r->addRoute('GET', '/b/{foo}', 'handler1'); + }; + + $cases[] = ['HEAD', '/b/bar', $callback, 'handler1', ['foo' => 'bar']]; + + // 20 ---- + + $callback = function (RouteCollector $r) { + $r->addRoute('HEAD', '/a', 'handler0'); + $r->addRoute('GET', '/b', 'handler1'); + }; + + $cases[] = ['HEAD', '/b', $callback, 'handler1', []]; + + // 21 ---- + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/foo', 'handler0'); + $r->addRoute('HEAD', '/{bar}', 'handler1'); + }; + + $cases[] = ['HEAD', '/foo', $callback, 'handler1', ['bar' => 'foo']]; + + // 22 ---- + + $callback = function (RouteCollector $r) { + $r->addRoute('*', '/user', 'handler0'); + $r->addRoute('*', '/{user}', 'handler1'); + $r->addRoute('GET', '/user', 'handler2'); + }; + + $cases[] = ['GET', '/user', $callback, 'handler2', []]; + + // 23 ---- + + $callback = function (RouteCollector $r) { + $r->addRoute('*', '/user', 'handler0'); + $r->addRoute('GET', '/user', 'handler1'); + }; + + $cases[] = ['POST', '/user', $callback, 'handler0', []]; + + // 24 ---- + + $cases[] = ['HEAD', '/user', $callback, 'handler1', []]; + + // 25 ---- + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/{bar}', 'handler0'); + $r->addRoute('*', '/foo', 'handler1'); + }; + + $cases[] = ['GET', '/foo', $callback, 'handler0', ['bar' => 'foo']]; + + // 26 ---- + + $callback = function(RouteCollector $r) { + $r->addRoute('GET', '/user', 'handler0'); + $r->addRoute('*', '/{foo:.*}', 'handler1'); + }; + + $cases[] = ['POST', '/bar', $callback, 'handler1', ['foo' => 'bar']]; + + // x --------------------------------------------------------------------------------------> + + return $cases; + } + + public function provideNotFoundDispatchCases() + { + $cases = []; + + // 0 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/resource/123/456', 'handler0'); + }; + + $method = 'GET'; + $uri = '/not-found'; + + $cases[] = [$method, $uri, $callback]; + + // 1 --------------------------------------------------------------------------------------> + + // reuse callback from #0 + $method = 'POST'; + $uri = '/not-found'; + + $cases[] = [$method, $uri, $callback]; + + // 2 --------------------------------------------------------------------------------------> + + // reuse callback from #1 + $method = 'PUT'; + $uri = '/not-found'; + + $cases[] = [$method, $uri, $callback]; + + // 3 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/handler0', 'handler0'); + $r->addRoute('GET', '/handler1', 'handler1'); + $r->addRoute('GET', '/handler2', 'handler2'); + }; + + $method = 'GET'; + $uri = '/not-found'; + + $cases[] = [$method, $uri, $callback]; + + // 4 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); + $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1'); + $r->addRoute('GET', '/user/{name}', 'handler2'); + }; + + $method = 'GET'; + $uri = '/not-found'; + + $cases[] = [$method, $uri, $callback]; + + // 5 --------------------------------------------------------------------------------------> + + // reuse callback from #4 + $method = 'GET'; + $uri = '/user/rdlowrey/12345/not-found'; + + $cases[] = [$method, $uri, $callback]; + + // 6 --------------------------------------------------------------------------------------> + + // reuse callback from #5 + $method = 'HEAD'; + + $cases[] = [$method, $uri, $callback]; + + // x --------------------------------------------------------------------------------------> + + return $cases; + } + + public function provideMethodNotAllowedDispatchCases() + { + $cases = []; + + // 0 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/resource/123/456', 'handler0'); + }; + + $method = 'POST'; + $uri = '/resource/123/456'; + $allowedMethods = ['GET']; + + $cases[] = [$method, $uri, $callback, $allowedMethods]; + + // 1 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/resource/123/456', 'handler0'); + $r->addRoute('POST', '/resource/123/456', 'handler1'); + $r->addRoute('PUT', '/resource/123/456', 'handler2'); + $r->addRoute('*', '/', 'handler3'); + }; + + $method = 'DELETE'; + $uri = '/resource/123/456'; + $allowedMethods = ['GET', 'POST', 'PUT']; + + $cases[] = [$method, $uri, $callback, $allowedMethods]; + + // 2 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); + $r->addRoute('POST', '/user/{name}/{id:[0-9]+}', 'handler1'); + $r->addRoute('PUT', '/user/{name}/{id:[0-9]+}', 'handler2'); + $r->addRoute('PATCH', '/user/{name}/{id:[0-9]+}', 'handler3'); + }; + + $method = 'DELETE'; + $uri = '/user/rdlowrey/42'; + $allowedMethods = ['GET', 'POST', 'PUT', 'PATCH']; + + $cases[] = [$method, $uri, $callback, $allowedMethods]; + + // 3 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute('POST', '/user/{name}', 'handler1'); + $r->addRoute('PUT', '/user/{name:[a-z]+}', 'handler2'); + $r->addRoute('PATCH', '/user/{name:[a-z]+}', 'handler3'); + }; + + $method = 'GET'; + $uri = '/user/rdlowrey'; + $allowedMethods = ['POST', 'PUT', 'PATCH']; + + $cases[] = [$method, $uri, $callback, $allowedMethods]; + + // 4 --------------------------------------------------------------------------------------> + + $callback = function (RouteCollector $r) { + $r->addRoute(['GET', 'POST'], '/user', 'handlerGetPost'); + $r->addRoute(['DELETE'], '/user', 'handlerDelete'); + $r->addRoute([], '/user', 'handlerNone'); + }; + + $cases[] = ['PUT', '/user', $callback, ['GET', 'POST', 'DELETE']]; + + // 5 + + $callback = function (RouteCollector $r) { + $r->addRoute('POST', '/user.json', 'handler0'); + $r->addRoute('GET', '/{entity}.json', 'handler1'); + }; + + $cases[] = ['PUT', '/user.json', $callback, ['POST', 'GET']]; + + // x --------------------------------------------------------------------------------------> + + return $cases; + } +} diff --git a/vendor/nikic/fast-route/test/Dispatcher/GroupCountBasedTest.php b/vendor/nikic/fast-route/test/Dispatcher/GroupCountBasedTest.php new file mode 100644 index 0000000..f821ef5 --- /dev/null +++ b/vendor/nikic/fast-route/test/Dispatcher/GroupCountBasedTest.php @@ -0,0 +1,16 @@ +markTestSkipped('PHP 5.6 required for MARK support'); + } + } + + protected function getDispatcherClass() + { + return 'FastRoute\\Dispatcher\\MarkBased'; + } + + protected function getDataGeneratorClass() + { + return 'FastRoute\\DataGenerator\\MarkBased'; + } +} diff --git a/vendor/nikic/fast-route/test/HackTypechecker/HackTypecheckerTest.php b/vendor/nikic/fast-route/test/HackTypechecker/HackTypecheckerTest.php new file mode 100644 index 0000000..b6fc53f --- /dev/null +++ b/vendor/nikic/fast-route/test/HackTypechecker/HackTypecheckerTest.php @@ -0,0 +1,44 @@ +markTestSkipped('HHVM only'); + } + if (!version_compare(HHVM_VERSION, '3.9.0', '>=')) { + $this->markTestSkipped('classname requires HHVM 3.9+'); + } + + // The typechecker recurses the whole tree, so it makes sure + // that everything in fixtures/ is valid when this runs. + + $output = []; + $exit_code = null; + exec( + 'hh_server --check ' . escapeshellarg(__DIR__ . '/../../') . ' 2>&1', + $output, + $exit_code + ); + if ($exit_code === self::SERVER_ALREADY_RUNNING_CODE) { + $this->assertTrue( + $recurse, + 'Typechecker still running after running hh_client stop' + ); + // Server already running - 3.10 => 3.11 regression: + // https://github.com/facebook/hhvm/issues/6646 + exec('hh_client stop 2>/dev/null'); + $this->testTypechecks(/* recurse = */ false); + return; + + } + $this->assertSame(0, $exit_code, implode("\n", $output)); + } +} diff --git a/vendor/nikic/fast-route/test/HackTypechecker/fixtures/all_options.php b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/all_options.php new file mode 100644 index 0000000..05a9af2 --- /dev/null +++ b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/all_options.php @@ -0,0 +1,29 @@ + {}, + shape( + 'routeParser' => \FastRoute\RouteParser\Std::class, + 'dataGenerator' => \FastRoute\DataGenerator\GroupCountBased::class, + 'dispatcher' => \FastRoute\Dispatcher\GroupCountBased::class, + 'routeCollector' => \FastRoute\RouteCollector::class, + ), + ); +} + +function all_options_cached(): \FastRoute\Dispatcher { + return \FastRoute\cachedDispatcher( + $collector ==> {}, + shape( + 'routeParser' => \FastRoute\RouteParser\Std::class, + 'dataGenerator' => \FastRoute\DataGenerator\GroupCountBased::class, + 'dispatcher' => \FastRoute\Dispatcher\GroupCountBased::class, + 'routeCollector' => \FastRoute\RouteCollector::class, + 'cacheFile' => '/dev/null', + 'cacheDisabled' => false, + ), + ); +} diff --git a/vendor/nikic/fast-route/test/HackTypechecker/fixtures/empty_options.php b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/empty_options.php new file mode 100644 index 0000000..61eb541 --- /dev/null +++ b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/empty_options.php @@ -0,0 +1,11 @@ + {}, shape()); +} + +function empty_options_cached(): \FastRoute\Dispatcher { + return \FastRoute\cachedDispatcher($collector ==> {}, shape()); +} diff --git a/vendor/nikic/fast-route/test/HackTypechecker/fixtures/no_options.php b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/no_options.php new file mode 100644 index 0000000..44b5422 --- /dev/null +++ b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/no_options.php @@ -0,0 +1,11 @@ + {}); +} + +function no_options_cached(): \FastRoute\Dispatcher { + return \FastRoute\cachedDispatcher($collector ==> {}); +} diff --git a/vendor/nikic/fast-route/test/RouteCollectorTest.php b/vendor/nikic/fast-route/test/RouteCollectorTest.php new file mode 100644 index 0000000..cc54407 --- /dev/null +++ b/vendor/nikic/fast-route/test/RouteCollectorTest.php @@ -0,0 +1,108 @@ +delete('/delete', 'delete'); + $r->get('/get', 'get'); + $r->head('/head', 'head'); + $r->patch('/patch', 'patch'); + $r->post('/post', 'post'); + $r->put('/put', 'put'); + + $expected = [ + ['DELETE', '/delete', 'delete'], + ['GET', '/get', 'get'], + ['HEAD', '/head', 'head'], + ['PATCH', '/patch', 'patch'], + ['POST', '/post', 'post'], + ['PUT', '/put', 'put'], + ]; + + $this->assertSame($expected, $r->routes); + } + + public function testGroups() + { + $r = new DummyRouteCollector(); + + $r->delete('/delete', 'delete'); + $r->get('/get', 'get'); + $r->head('/head', 'head'); + $r->patch('/patch', 'patch'); + $r->post('/post', 'post'); + $r->put('/put', 'put'); + + $r->addGroup('/group-one', function (DummyRouteCollector $r) { + $r->delete('/delete', 'delete'); + $r->get('/get', 'get'); + $r->head('/head', 'head'); + $r->patch('/patch', 'patch'); + $r->post('/post', 'post'); + $r->put('/put', 'put'); + + $r->addGroup('/group-two', function (DummyRouteCollector $r) { + $r->delete('/delete', 'delete'); + $r->get('/get', 'get'); + $r->head('/head', 'head'); + $r->patch('/patch', 'patch'); + $r->post('/post', 'post'); + $r->put('/put', 'put'); + }); + }); + + $r->addGroup('/admin', function (DummyRouteCollector $r) { + $r->get('-some-info', 'admin-some-info'); + }); + $r->addGroup('/admin-', function (DummyRouteCollector $r) { + $r->get('more-info', 'admin-more-info'); + }); + + $expected = [ + ['DELETE', '/delete', 'delete'], + ['GET', '/get', 'get'], + ['HEAD', '/head', 'head'], + ['PATCH', '/patch', 'patch'], + ['POST', '/post', 'post'], + ['PUT', '/put', 'put'], + ['DELETE', '/group-one/delete', 'delete'], + ['GET', '/group-one/get', 'get'], + ['HEAD', '/group-one/head', 'head'], + ['PATCH', '/group-one/patch', 'patch'], + ['POST', '/group-one/post', 'post'], + ['PUT', '/group-one/put', 'put'], + ['DELETE', '/group-one/group-two/delete', 'delete'], + ['GET', '/group-one/group-two/get', 'get'], + ['HEAD', '/group-one/group-two/head', 'head'], + ['PATCH', '/group-one/group-two/patch', 'patch'], + ['POST', '/group-one/group-two/post', 'post'], + ['PUT', '/group-one/group-two/put', 'put'], + ['GET', '/admin-some-info', 'admin-some-info'], + ['GET', '/admin-more-info', 'admin-more-info'], + ]; + + $this->assertSame($expected, $r->routes); + } +} + +class DummyRouteCollector extends RouteCollector +{ + public $routes = []; + + public function __construct() + { + } + + public function addRoute($method, $route, $handler) + { + $route = $this->currentGroupPrefix . $route; + $this->routes[] = [$method, $route, $handler]; + } +} diff --git a/vendor/nikic/fast-route/test/RouteParser/StdTest.php b/vendor/nikic/fast-route/test/RouteParser/StdTest.php new file mode 100644 index 0000000..e13e4de --- /dev/null +++ b/vendor/nikic/fast-route/test/RouteParser/StdTest.php @@ -0,0 +1,154 @@ +parse($routeString); + $this->assertSame($expectedRouteDatas, $routeDatas); + } + + /** @dataProvider provideTestParseError */ + public function testParseError($routeString, $expectedExceptionMessage) + { + $parser = new Std(); + $this->setExpectedException('FastRoute\\BadRouteException', $expectedExceptionMessage); + $parser->parse($routeString); + } + + public function provideTestParse() + { + return [ + [ + '/test', + [ + ['/test'], + ] + ], + [ + '/test/{param}', + [ + ['/test/', ['param', '[^/]+']], + ] + ], + [ + '/te{ param }st', + [ + ['/te', ['param', '[^/]+'], 'st'] + ] + ], + [ + '/test/{param1}/test2/{param2}', + [ + ['/test/', ['param1', '[^/]+'], '/test2/', ['param2', '[^/]+']] + ] + ], + [ + '/test/{param:\d+}', + [ + ['/test/', ['param', '\d+']] + ] + ], + [ + '/test/{ param : \d{1,9} }', + [ + ['/test/', ['param', '\d{1,9}']] + ] + ], + [ + '/test[opt]', + [ + ['/test'], + ['/testopt'], + ] + ], + [ + '/test[/{param}]', + [ + ['/test'], + ['/test/', ['param', '[^/]+']], + ] + ], + [ + '/{param}[opt]', + [ + ['/', ['param', '[^/]+']], + ['/', ['param', '[^/]+'], 'opt'] + ] + ], + [ + '/test[/{name}[/{id:[0-9]+}]]', + [ + ['/test'], + ['/test/', ['name', '[^/]+']], + ['/test/', ['name', '[^/]+'], '/', ['id', '[0-9]+']], + ] + ], + [ + '', + [ + [''], + ] + ], + [ + '[test]', + [ + [''], + ['test'], + ] + ], + [ + '/{foo-bar}', + [ + ['/', ['foo-bar', '[^/]+']] + ] + ], + [ + '/{_foo:.*}', + [ + ['/', ['_foo', '.*']] + ] + ], + ]; + } + + public function provideTestParseError() + { + return [ + [ + '/test[opt', + "Number of opening '[' and closing ']' does not match" + ], + [ + '/test[opt[opt2]', + "Number of opening '[' and closing ']' does not match" + ], + [ + '/testopt]', + "Number of opening '[' and closing ']' does not match" + ], + [ + '/test[]', + 'Empty optional part' + ], + [ + '/test[[opt]]', + 'Empty optional part' + ], + [ + '[[test]]', + 'Empty optional part' + ], + [ + '/test[/opt]/required', + 'Optional segments can only occur at the end of a route' + ], + ]; + } +} diff --git a/vendor/nikic/fast-route/test/bootstrap.php b/vendor/nikic/fast-route/test/bootstrap.php new file mode 100644 index 0000000..3023f41 --- /dev/null +++ b/vendor/nikic/fast-route/test/bootstrap.php @@ -0,0 +1,11 @@ +get('/project/{project}/issue/{issue}', function ($project, $issue) { + // ... +}); +``` + +Or this command defined with [Silly](https://github.com/mnapoli/silly#usage): + +```php +$app->command('greet [name] [--yell]', function ($name, $yell) { + // ... +}); +``` + +Same pattern in [Slim](https://www.slimframework.com): + +```php +$app->get('/hello/:name', function ($name) { + // ... +}); +``` + +You get the point. These frameworks invoke the controller/command/handler using something akin to named parameters: whatever the order of the parameters, they are matched by their name. + +**This library allows to invoke callables with named parameters in a generic and extensible way.** + +### Dependency injection + +Anyone familiar with AngularJS is familiar with how dependency injection is performed: + +```js +angular.controller('MyController', ['dep1', 'dep2', function(dep1, dep2) { + // ... +}]); +``` + +In PHP we find this pattern again in some frameworks and DI containers with partial to full support. For example in Silex you can type-hint the application to get it injected, but it only works with `Silex\Application`: + +```php +$app->get('/hello/{name}', function (Silex\Application $app, $name) { + // ... +}); +``` + +In Silly, it only works with `OutputInterface` to inject the application output: + +```php +$app->command('greet [name]', function ($name, OutputInterface $output) { + // ... +}); +``` + +[PHP-DI](https://php-di.org/doc/container.html) provides a way to invoke a callable and resolve all dependencies from the container using type-hints: + +```php +$container->call(function (Logger $logger, EntityManager $em) { + // ... +}); +``` + +**This library provides clear extension points to let frameworks implement any kind of dependency injection support they want.** + +### TL/DR + +In short, this library is meant to be a base building block for calling a function with named parameters and/or dependency injection. + +## Installation + +```sh +$ composer require PHP-DI/invoker +``` + +## Usage + +### Default behavior + +By default the `Invoker` can call using named parameters: + +```php +$invoker = new Invoker\Invoker; + +$invoker->call(function () { + echo 'Hello world!'; +}); + +// Simple parameter array +$invoker->call(function ($name) { + echo 'Hello ' . $name; +}, ['John']); + +// Named parameters +$invoker->call(function ($name) { + echo 'Hello ' . $name; +}, [ + 'name' => 'John' +]); + +// Use the default value +$invoker->call(function ($name = 'world') { + echo 'Hello ' . $name; +}); + +// Invoke any PHP callable +$invoker->call(['MyClass', 'myStaticMethod']); + +// Using Class::method syntax +$invoker->call('MyClass::myStaticMethod'); +``` + +Dependency injection in parameters is supported but needs to be configured with your container. Read on or jump to [*Built-in support for dependency injection*](#built-in-support-for-dependency-injection) if you are impatient. + +Additionally, callables can also be resolved from your container. Read on or jump to [*Resolving callables from a container*](#resolving-callables-from-a-container) if you are impatient. + +### Parameter resolvers + +Extending the behavior of the `Invoker` is easy and is done by implementing a [`ParameterResolver`](https://github.com/PHP-DI/Invoker/blob/master/src/ParameterResolver/ParameterResolver.php). + +This is explained in details the [Parameter resolvers documentation](doc/parameter-resolvers.md). + +#### Built-in support for dependency injection + +Rather than have you re-implement support for dependency injection with different containers every time, this package ships with 2 optional resolvers: + +- [`TypeHintContainerResolver`](https://github.com/PHP-DI/Invoker/blob/master/src/ParameterResolver/Container/TypeHintContainerResolver.php) + + This resolver will inject container entries by searching for the class name using the type-hint: + + ```php + $invoker->call(function (Psr\Logger\LoggerInterface $logger) { + // ... + }); + ``` + + In this example it will `->get('Psr\Logger\LoggerInterface')` from the container and inject it. + + This resolver is only useful if you store objects in your container using the class (or interface) name. Silex or Symfony for example store services under a custom name (e.g. `twig`, `db`, etc.) instead of the class name: in that case use the resolver shown below. + +- [`ParameterNameContainerResolver`](https://github.com/PHP-DI/Invoker/blob/master/src/ParameterResolver/Container/ParameterNameContainerResolver.php) + + This resolver will inject container entries by searching for the name of the parameter: + + ```php + $invoker->call(function ($twig) { + // ... + }); + ``` + + In this example it will `->get('twig')` from the container and inject it. + +These resolvers can work with any dependency injection container compliant with [PSR-11](http://www.php-fig.org/psr/psr-11/). + +Setting up those resolvers is simple: + +```php +// $container must be an instance of Psr\Container\ContainerInterface +$container = ... + +$containerResolver = new TypeHintContainerResolver($container); +// or +$containerResolver = new ParameterNameContainerResolver($container); + +$invoker = new Invoker\Invoker; +// Register it before all the other parameter resolvers +$invoker->getParameterResolver()->prependResolver($containerResolver); +``` + +You can also register both resolvers at the same time if you wish by prepending both. Implementing support for more tricky things is easy and up to you! + +### Resolving callables from a container + +The `Invoker` can be wired to your DI container to resolve the callables. + +For example with an invokable class: + +```php +class MyHandler +{ + public function __invoke() + { + // ... + } +} + +// By default this doesn't work: an instance of the class should be provided +$invoker->call('MyHandler'); + +// If we set up the container to use +$invoker = new Invoker\Invoker(null, $container); +// Now 'MyHandler' is resolved using the container! +$invoker->call('MyHandler'); +``` + +The same works for a class method: + +```php +class WelcomeController +{ + public function home() + { + // ... + } +} + +// By default this doesn't work: home() is not a static method +$invoker->call(['WelcomeController', 'home']); + +// If we set up the container to use +$invoker = new Invoker\Invoker(null, $container); +// Now 'WelcomeController' is resolved using the container! +$invoker->call(['WelcomeController', 'home']); +// Alternatively we can use the Class::method syntax +$invoker->call('WelcomeController::home'); +``` + +That feature can be used as the base building block for a framework's dispatcher. + +Again, any [PSR-11](https://www.php-fig.org/psr/psr-11/) compliant container can be provided. + diff --git a/vendor/php-di/invoker/composer.json b/vendor/php-di/invoker/composer.json new file mode 100644 index 0000000..55e6bcf --- /dev/null +++ b/vendor/php-di/invoker/composer.json @@ -0,0 +1,32 @@ +{ + "name": "php-di/invoker", + "description": "Generic and extensible callable invoker", + "keywords": ["invoker", "dependency-injection", "dependency", "injection", "callable", "invoke"], + "homepage": "https://github.com/PHP-DI/Invoker", + "license": "MIT", + "type": "library", + "autoload": { + "psr-4": { + "Invoker\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Invoker\\Test\\": "tests/" + } + }, + "require": { + "php": ">=7.3", + "psr/container": "^1.0|^2.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.0", + "athletic/athletic": "~0.1.8", + "mnapoli/hard-mode": "~0.3.0" + }, + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + } +} diff --git a/vendor/php-di/invoker/src/CallableResolver.php b/vendor/php-di/invoker/src/CallableResolver.php new file mode 100644 index 0000000..e3b11b2 --- /dev/null +++ b/vendor/php-di/invoker/src/CallableResolver.php @@ -0,0 +1,124 @@ +container = $container; + } + + /** + * Resolve the given callable into a real PHP callable. + * + * @param callable|string|array $callable + * @return callable Real PHP callable. + * @throws NotCallableException|ReflectionException + */ + public function resolve($callable): callable + { + if (is_string($callable) && strpos($callable, '::') !== false) { + $callable = explode('::', $callable, 2); + } + + $callable = $this->resolveFromContainer($callable); + + if (! is_callable($callable)) { + throw NotCallableException::fromInvalidCallable($callable, true); + } + + return $callable; + } + + /** + * @param callable|string|array $callable + * @return callable|mixed + * @throws NotCallableException|ReflectionException + */ + private function resolveFromContainer($callable) + { + // Shortcut for a very common use case + if ($callable instanceof Closure) { + return $callable; + } + + // If it's already a callable there is nothing to do + if (is_callable($callable)) { + // TODO with PHP 8 that should not be necessary to check this anymore + if (! $this->isStaticCallToNonStaticMethod($callable)) { + return $callable; + } + } + + // The callable is a container entry name + if (is_string($callable)) { + try { + return $this->container->get($callable); + } catch (NotFoundExceptionInterface $e) { + if ($this->container->has($callable)) { + throw $e; + } + throw NotCallableException::fromInvalidCallable($callable, true); + } + } + + // The callable is an array whose first item is a container entry name + // e.g. ['some-container-entry', 'methodToCall'] + if (is_array($callable) && is_string($callable[0])) { + try { + // Replace the container entry name by the actual object + $callable[0] = $this->container->get($callable[0]); + return $callable; + } catch (NotFoundExceptionInterface $e) { + if ($this->container->has($callable[0])) { + throw $e; + } + throw new NotCallableException(sprintf( + 'Cannot call %s() on %s because it is not a class nor a valid container entry', + $callable[1], + $callable[0] + )); + } + } + + // Unrecognized stuff, we let it fail later + return $callable; + } + + /** + * Check if the callable represents a static call to a non-static method. + * + * @param mixed $callable + * @throws ReflectionException + */ + private function isStaticCallToNonStaticMethod($callable): bool + { + if (is_array($callable) && is_string($callable[0])) { + [$class, $method] = $callable; + + if (! method_exists($class, $method)) { + return false; + } + + $reflection = new ReflectionMethod($class, $method); + + return ! $reflection->isStatic(); + } + + return false; + } +} diff --git a/vendor/php-di/invoker/src/Exception/InvocationException.php b/vendor/php-di/invoker/src/Exception/InvocationException.php new file mode 100644 index 0000000..90f6585 --- /dev/null +++ b/vendor/php-di/invoker/src/Exception/InvocationException.php @@ -0,0 +1,10 @@ +parameterResolver = $parameterResolver ?: $this->createParameterResolver(); + $this->container = $container; + + if ($container) { + $this->callableResolver = new CallableResolver($container); + } + } + + /** + * {@inheritdoc} + */ + public function call($callable, array $parameters = []) + { + if ($this->callableResolver) { + $callable = $this->callableResolver->resolve($callable); + } + + if (! is_callable($callable)) { + throw new NotCallableException(sprintf( + '%s is not a callable', + is_object($callable) ? 'Instance of ' . get_class($callable) : var_export($callable, true) + )); + } + + $callableReflection = CallableReflection::create($callable); + + $args = $this->parameterResolver->getParameters($callableReflection, $parameters, []); + + // Sort by array key because call_user_func_array ignores numeric keys + ksort($args); + + // Check all parameters are resolved + $diff = array_diff_key($callableReflection->getParameters(), $args); + $parameter = reset($diff); + if ($parameter && \assert($parameter instanceof ReflectionParameter) && ! $parameter->isVariadic()) { + throw new NotEnoughParametersException(sprintf( + 'Unable to invoke the callable because no value was given for parameter %d ($%s)', + $parameter->getPosition() + 1, + $parameter->name + )); + } + + return call_user_func_array($callable, $args); + } + + /** + * Create the default parameter resolver. + */ + private function createParameterResolver(): ParameterResolver + { + return new ResolverChain([ + new NumericArrayResolver, + new AssociativeArrayResolver, + new DefaultValueResolver, + ]); + } + + /** + * @return ParameterResolver By default it's a ResolverChain + */ + public function getParameterResolver(): ParameterResolver + { + return $this->parameterResolver; + } + + public function getContainer(): ?ContainerInterface + { + return $this->container; + } + + /** + * @return CallableResolver|null Returns null if no container was given in the constructor. + */ + public function getCallableResolver(): ?CallableResolver + { + return $this->callableResolver; + } +} diff --git a/vendor/php-di/invoker/src/InvokerInterface.php b/vendor/php-di/invoker/src/InvokerInterface.php new file mode 100644 index 0000000..06f0064 --- /dev/null +++ b/vendor/php-di/invoker/src/InvokerInterface.php @@ -0,0 +1,25 @@ +call($callable, ['foo' => 'bar'])` will inject the string `'bar'` + * in the parameter named `$foo`. + * + * Parameters that are not indexed by a string are ignored. + */ +class AssociativeArrayResolver implements ParameterResolver +{ + public function getParameters( + ReflectionFunctionAbstract $reflection, + array $providedParameters, + array $resolvedParameters + ): array { + $parameters = $reflection->getParameters(); + + // Skip parameters already resolved + if (! empty($resolvedParameters)) { + $parameters = array_diff_key($parameters, $resolvedParameters); + } + + foreach ($parameters as $index => $parameter) { + if (array_key_exists($parameter->name, $providedParameters)) { + $resolvedParameters[$index] = $providedParameters[$parameter->name]; + } + } + + return $resolvedParameters; + } +} diff --git a/vendor/php-di/invoker/src/ParameterResolver/Container/ParameterNameContainerResolver.php b/vendor/php-di/invoker/src/ParameterResolver/Container/ParameterNameContainerResolver.php new file mode 100644 index 0000000..126e14c --- /dev/null +++ b/vendor/php-di/invoker/src/ParameterResolver/Container/ParameterNameContainerResolver.php @@ -0,0 +1,47 @@ +container = $container; + } + + public function getParameters( + ReflectionFunctionAbstract $reflection, + array $providedParameters, + array $resolvedParameters + ): array { + $parameters = $reflection->getParameters(); + + // Skip parameters already resolved + if (! empty($resolvedParameters)) { + $parameters = array_diff_key($parameters, $resolvedParameters); + } + + foreach ($parameters as $index => $parameter) { + $name = $parameter->name; + + if ($name && $this->container->has($name)) { + $resolvedParameters[$index] = $this->container->get($name); + } + } + + return $resolvedParameters; + } +} diff --git a/vendor/php-di/invoker/src/ParameterResolver/Container/TypeHintContainerResolver.php b/vendor/php-di/invoker/src/ParameterResolver/Container/TypeHintContainerResolver.php new file mode 100644 index 0000000..014956e --- /dev/null +++ b/vendor/php-di/invoker/src/ParameterResolver/Container/TypeHintContainerResolver.php @@ -0,0 +1,65 @@ +container = $container; + } + + public function getParameters( + ReflectionFunctionAbstract $reflection, + array $providedParameters, + array $resolvedParameters + ): array { + $parameters = $reflection->getParameters(); + + // Skip parameters already resolved + if (! empty($resolvedParameters)) { + $parameters = array_diff_key($parameters, $resolvedParameters); + } + + foreach ($parameters as $index => $parameter) { + $parameterType = $parameter->getType(); + if (! $parameterType) { + // No type + continue; + } + if (! $parameterType instanceof ReflectionNamedType) { + // Union types are not supported + continue; + } + if ($parameterType->isBuiltin()) { + // Primitive types are not supported + continue; + } + + $parameterClass = $parameterType->getName(); + if ($parameterClass === 'self') { + $parameterClass = $parameter->getDeclaringClass()->getName(); + } + + if ($this->container->has($parameterClass)) { + $resolvedParameters[$index] = $this->container->get($parameterClass); + } + } + + return $resolvedParameters; + } +} diff --git a/vendor/php-di/invoker/src/ParameterResolver/DefaultValueResolver.php b/vendor/php-di/invoker/src/ParameterResolver/DefaultValueResolver.php new file mode 100644 index 0000000..3fdf7b7 --- /dev/null +++ b/vendor/php-di/invoker/src/ParameterResolver/DefaultValueResolver.php @@ -0,0 +1,43 @@ +getParameters(); + + // Skip parameters already resolved + if (! empty($resolvedParameters)) { + $parameters = array_diff_key($parameters, $resolvedParameters); + } + + foreach ($parameters as $index => $parameter) { + \assert($parameter instanceof \ReflectionParameter); + if ($parameter->isDefaultValueAvailable()) { + try { + $resolvedParameters[$index] = $parameter->getDefaultValue(); + } catch (ReflectionException $e) { + // Can't get default values from PHP internal classes and functions + } + } else { + $parameterType = $parameter->getType(); + if ($parameterType && $parameterType->allowsNull()) { + $resolvedParameters[$index] = null; + } + } + } + + return $resolvedParameters; + } +} diff --git a/vendor/php-di/invoker/src/ParameterResolver/NumericArrayResolver.php b/vendor/php-di/invoker/src/ParameterResolver/NumericArrayResolver.php new file mode 100644 index 0000000..07d8ece --- /dev/null +++ b/vendor/php-di/invoker/src/ParameterResolver/NumericArrayResolver.php @@ -0,0 +1,37 @@ +call($callable, ['foo', 'bar'])` will simply resolve the parameters + * to `['foo', 'bar']`. + * + * Parameters that are not indexed by a number (i.e. parameter position) + * will be ignored. + */ +class NumericArrayResolver implements ParameterResolver +{ + public function getParameters( + ReflectionFunctionAbstract $reflection, + array $providedParameters, + array $resolvedParameters + ): array { + // Skip parameters already resolved + if (! empty($resolvedParameters)) { + $providedParameters = array_diff_key($providedParameters, $resolvedParameters); + } + + foreach ($providedParameters as $key => $value) { + if (is_int($key)) { + $resolvedParameters[$key] = $value; + } + } + + return $resolvedParameters; + } +} diff --git a/vendor/php-di/invoker/src/ParameterResolver/ParameterResolver.php b/vendor/php-di/invoker/src/ParameterResolver/ParameterResolver.php new file mode 100644 index 0000000..85046c3 --- /dev/null +++ b/vendor/php-di/invoker/src/ParameterResolver/ParameterResolver.php @@ -0,0 +1,30 @@ +resolvers = $resolvers; + } + + public function getParameters( + ReflectionFunctionAbstract $reflection, + array $providedParameters, + array $resolvedParameters + ): array { + $reflectionParameters = $reflection->getParameters(); + + foreach ($this->resolvers as $resolver) { + $resolvedParameters = $resolver->getParameters( + $reflection, + $providedParameters, + $resolvedParameters + ); + + $diff = array_diff_key($reflectionParameters, $resolvedParameters); + if (empty($diff)) { + // Stop traversing: all parameters are resolved + return $resolvedParameters; + } + } + + return $resolvedParameters; + } + + /** + * Push a parameter resolver after the ones already registered. + */ + public function appendResolver(ParameterResolver $resolver): void + { + $this->resolvers[] = $resolver; + } + + /** + * Insert a parameter resolver before the ones already registered. + */ + public function prependResolver(ParameterResolver $resolver): void + { + array_unshift($this->resolvers, $resolver); + } +} diff --git a/vendor/php-di/invoker/src/ParameterResolver/TypeHintResolver.php b/vendor/php-di/invoker/src/ParameterResolver/TypeHintResolver.php new file mode 100644 index 0000000..3ccc2e0 --- /dev/null +++ b/vendor/php-di/invoker/src/ParameterResolver/TypeHintResolver.php @@ -0,0 +1,54 @@ +getParameters(); + + // Skip parameters already resolved + if (! empty($resolvedParameters)) { + $parameters = array_diff_key($parameters, $resolvedParameters); + } + + foreach ($parameters as $index => $parameter) { + $parameterType = $parameter->getType(); + if (! $parameterType) { + // No type + continue; + } + if (! $parameterType instanceof ReflectionNamedType) { + // Union types are not supported + continue; + } + if ($parameterType->isBuiltin()) { + // Primitive types are not supported + continue; + } + + $parameterClass = $parameterType->getName(); + if ($parameterClass === 'self') { + $parameterClass = $parameter->getDeclaringClass()->getName(); + } + + if (array_key_exists($parameterClass, $providedParameters)) { + $resolvedParameters[$index] = $providedParameters[$parameterClass]; + } + } + + return $resolvedParameters; + } +} diff --git a/vendor/php-di/invoker/src/Reflection/CallableReflection.php b/vendor/php-di/invoker/src/Reflection/CallableReflection.php new file mode 100644 index 0000000..3f19f33 --- /dev/null +++ b/vendor/php-di/invoker/src/Reflection/CallableReflection.php @@ -0,0 +1,56 @@ + DI\factory(function ($host) {...}) + ->parameter('host', DI\get('db.host')), + ]; + ``` + Read the [factories documentation](https://php-di.org/doc/php-definitions.html#factories) to learn more. Feature implemented by [@predakanga](https://github.com/predakanga). + +Improvements: + +- [#429](https://github.com/PHP-DI/PHP-DI/pull/429): performance improvements in definition resolution (by [@mnapoli](https://github.com/mnapoli)) +- [#421](https://github.com/PHP-DI/PHP-DI/issues/421): once a `ContainerBuilder` has built a container, it is locked to prevent confusion when adding new definitions to it (by [@mnapoli](https://github.com/mnapoli)) +- [#423](https://github.com/PHP-DI/PHP-DI/pull/423): improved exception messages (by [@mnapoli](https://github.com/mnapoli)) + +## 5.3 + +Read the [news entry](news/19-php-di-5-3-released.md). + +- release of the [2.0 version](https://github.com/PHP-DI/Symfony-Bridge/releases/tag/2.0.0) of the Symfony bridge (by [@mnapoli](https://github.com/mnapoli)) +- PHP 5.5 or above is now required +- a lot of documentation improvements by 9 different contributors +- [#389](https://github.com/PHP-DI/PHP-DI/pull/389): exception message improvement by [@mopahle](https://github.com/mopahle) +- [#359](https://github.com/PHP-DI/PHP-DI/issues/359), [#411](https://github.com/PHP-DI/PHP-DI/issues/411), [#414](https://github.com/PHP-DI/PHP-DI/pull/414), [#412](https://github.com/PHP-DI/PHP-DI/pull/412): compatibility with ProxyManager 1.* and 2.* (by [@holtkamp](https://github.com/holtkamp) and [@mnapoli](https://github.com/mnapoli)) +- [#416](https://github.com/PHP-DI/PHP-DI/pull/416): dumping definitions was refactored into a more lightweight and simple solution; definition "dumpers" have been removed (internal classes), definitions can now be cast to string directly (by [@mnapoli](https://github.com/mnapoli)) + +## 5.2 + +Read the [news entry](news/17-php-di-5-2-released.md). + +Improvements: + +- [#347](https://github.com/PHP-DI/PHP-DI/pull/347) (includes [#333](https://github.com/PHP-DI/PHP-DI/pull/333) and [#345](https://github.com/PHP-DI/PHP-DI/pull/345)): by [@jdreesen](https://github.com/jdreesen), [@quimcalpe](https://github.com/quimcalpe) and [@mnapoli](https://github.com/mnapoli) + - Allow injection of any container object as factory parameter via type hinting + - Allow injection of a `DI\Factory\RequestedEntry` object to get the requested entry name +- [#272](https://github.com/PHP-DI/PHP-DI/issues/272): Support `"Class::method""` syntax for callables (by [@jdreesen](https://github.com/jdreesen)) +- [#332](https://github.com/PHP-DI/PHP-DI/issues/332): IDE support (plugin and documentation) (by [@pulyaevskiy](https://github.com/pulyaevskiy), [@avant1](https://github.com/avant1) and [@mnapoli](https://github.com/mnapoli)) +- [#326](https://github.com/PHP-DI/PHP-DI/pull/326): Exception messages are simpler and more consistent (by [@mnapoli](https://github.com/mnapoli)) +- [#325](https://github.com/PHP-DI/PHP-DI/pull/325): Add a "Edit this page" button in the website to encourage users to improve the documentation (by [@jdreesen](https://github.com/jdreesen)) + +Bugfixes: + +- [#321](https://github.com/PHP-DI/PHP-DI/pull/321): Allow factory definitions to reference arbitrary container entries as callables (by [@jdreesen](https://github.com/jdreesen)) +- [#335](https://github.com/PHP-DI/PHP-DI/issues/335): Class imports in traits are now considered when parsing annotations (by [@thebigb](https://github.com/thebigb)) + +## 5.1 + +Read the [news entry](news/16-php-di-5-1-released.md). + +Improvements: + +- [Zend Framework 2 integration](https://github.com/PHP-DI/ZF2-Bridge) (by @Rastusik) +- [#308](https://github.com/PHP-DI/PHP-DI/pull/308): Instantiate factories using the container (`DI\factory(['FooFactory', 'create'])`) +- Many performances improvements - some benchmarks show up to 35% performance improvements, real results may vary of course +- Many documentation improvements (@jdreesen, @mindplay-dk, @mnapoli, @holtkamp, @Rastusik) +- [#296](https://github.com/PHP-DI/PHP-DI/issues/296): Provide a faster `ArrayCache` implementation, mostly useful in micro-benchmarks + +Bugfixes: + +- [#257](https://github.com/PHP-DI/PHP-DI/issues/257) & [#274](https://github.com/PHP-DI/PHP-DI/issues/274): Private properties of parent classes are not injected when using annotations +- [#300](https://github.com/PHP-DI/PHP-DI/pull/300): Exception if object definition extends an incompatible definition +- [#306](https://github.com/PHP-DI/PHP-DI/issues/306): Errors when using parameters passed by reference (fixed by @bradynpoulsen) +- [#318](https://github.com/PHP-DI/PHP-DI/issues/318): `Container::call()` ignores parameter's default value + +Internal changes: + +- [#276](https://github.com/PHP-DI/PHP-DI/pull/276): Tests now pass on Windows (@bgaillard) + +## 5.0 + +This is the complete change log. You can also read the [migration guide](doc/migration/5.0.md) for upgrading, or [the news article](news/15-php-di-5-0-released.md) for a nicer introduction to this new version. + +Improvements: + +- Moved to an organization on GitHub: [github.com/PHP-DI/PHP-DI](https://github.com/PHP-DI/PHP-DI) +- The package has been renamed to: from `mnapoli/php-di` to [`php-di/php-di`](https://packagist.org/packages/php-di/php-di) +- New [Silex integration](doc/frameworks/silex.md) +- Lighter package: from 10 to 3 Composer dependencies! +- [#235](https://github.com/PHP-DI/PHP-DI/issues/235): `DI\link()` is now deprecated in favor of `DI\get()`. There is no BC break as `DI\link()` still works. +- [#207](https://github.com/PHP-DI/PHP-DI/issues/207): Support for `DI\link()` in arrays +- [#203](https://github.com/PHP-DI/PHP-DI/issues/203): New `DI\string()` helper ([documentation](doc/php-definitions.md)) +- [#208](https://github.com/PHP-DI/PHP-DI/issues/208): Support for nested definitions +- [#226](https://github.com/PHP-DI/PHP-DI/pull/226): `DI\factory()` can now be omitted with closures: + + ```php + // before + 'My\Class' => DI\factory(function () { ... }) + // now (optional shortcut) + 'My\Class' => function () { ... } + ``` +- [#193](https://github.com/PHP-DI/PHP-DI/issues/193): `DI\object()->method()` now supports calling the same method twice (or more). +- [#248](https://github.com/PHP-DI/PHP-DI/issues/248): New `DI\decorate()` helper to decorate a previously defined entry ([documentation](doc/definition-overriding.md)) +- [#215](https://github.com/PHP-DI/PHP-DI/pull/215): New `DI\add()` helper to add entries to an existing array ([documentation](doc/definition-overriding.md)) +- [#218](https://github.com/PHP-DI/PHP-DI/issues/218): `ContainerBuilder::addDefinitions()` can now take an array of definitions +- [#211](https://github.com/PHP-DI/PHP-DI/pull/211): `ContainerBuilder::addDefinitions()` is now fluent (return `$this`) +- [#250](https://github.com/PHP-DI/PHP-DI/issues/250): `Container::call()` now also accepts parameters not indexed by name as well as embedded definitions ([documentation](doc/container.md)) +- Various performance improvements, e.g. lower the number of files loaded, simpler architecture, … + +BC breaks: + +- PHP-DI now requires a version of PHP >= 5.4.0 +- The package is lighter by default: + - [#251](https://github.com/PHP-DI/PHP-DI/issues/251): Annotations are disabled by default, if you use annotations enable them with `$containerBuilder->useAnnotations(true)`. Additionally the `doctrine/annotations` package isn't required by default anymore, so you also need to run `composer require doctrine/annotations`. + - `doctrine/cache` is not installed by default anymore, you need to require it in `composer.json` (`~1.0`) if you want to configure a cache for PHP-DI + - [#198](https://github.com/PHP-DI/PHP-DI/issues/198): `ocramius/proxy-manager` is not installed by default anymore, you need to require it in `composer.json` (`~1.0`) if you want to use **lazy injection** +- Closures are now converted into factory definitions automatically. If you ever defined a closure as a value (e.g. to have the closure injected in a class), you need to wrap the closure with the new `DI\value()` helper. +- [#223](https://github.com/PHP-DI/PHP-DI/issues/223): `DI\ContainerInterface` was deprecated since v4.1 and has been removed + +Internal changes in case you were replacing/extending some parts: + +- the definition sources architecture has been refactored, if you defined custom definition sources you will need to update your code (it should be much easier now) +- [#252](https://github.com/PHP-DI/PHP-DI/pull/252): `DI\Scope` internal implementation has changed. You are encouraged to use the constants (`DI\Scope::SINGLETON` and `DI\Scope::PROTOTYPE`) instead of the static methods, but backward compatibility is kept (static methods still work). +- [#241](https://github.com/PHP-DI/PHP-DI/issues/241): `Container::call()` now uses the *Invoker* external library + +## 4.4 + +Read the [news entry](news/13-php-di-4-4-released.md). + +- [#185](https://github.com/PHP-DI/PHP-DI/issues/185) Support for invokable objects in `Container::call()` +- [#192](https://github.com/PHP-DI/PHP-DI/pull/192) Support for invokable classes in `Container::call()` (will instantiate the class) +- [#184](https://github.com/PHP-DI/PHP-DI/pull/184) Option to ignore phpdoc errors + +## 4.3 + +Read the [news entry](news/11-php-di-4-3-released.md). + +- [#176](https://github.com/PHP-DI/PHP-DI/pull/176) New definition type for reading environment variables: `DI\env()` +- [#181](https://github.com/PHP-DI/PHP-DI/pull/181) `DI\FactoryInterface` and `DI\InvokerInterface` are now auto-registered inside the container so that you can inject them without any configuration needed +- [#173](https://github.com/PHP-DI/PHP-DI/pull/173) `$container->call(['MyClass', 'method]);` will get `MyClass` from the container if `method()` is not a static method + +## 4.2.2 + +- Fixed [#180](https://github.com/PHP-DI/PHP-DI/pull/180): `Container::call()` with object methods (`[$object, 'method']`) is now supported + +## 4.2.1 + +- Support for PHP 5.3.3, which was previously incomplete because of a bug in the reflection (there is now a workaround for this bug) + +But if you can, seriously avoid this (really old) PHP version and upgrade. + +## 4.2 + +Read the [news entry](news/10-php-di-4-2-released.md). + +**Minor BC-break**: Optional parameters (that were not configured) were injected, they are now ignored, which is what naturally makes sense since they are optional. +Example: + +```php + public function __construct(Bar $bar = null) + { + $this->bar = $bar ?: $this->createDefaultBar(); + } +``` + +Before 4.2, PHP-DI would try to inject a `Bar` instance. From 4.2 and onwards, it will inject `null`. + +Of course, you can still explicitly define an injection for the optional parameters and that will work. + +All changes: + +* [#162](https://github.com/PHP-DI/PHP-DI/pull/162) Added `Container::call()` to call functions with dependency injection +* [#156](https://github.com/PHP-DI/PHP-DI/issues/156) Wildcards (`*`) in definitions +* [#164](https://github.com/PHP-DI/PHP-DI/issues/164) Prototype scope is now available for `factory()` definitions too +* FIXED [#168](https://github.com/PHP-DI/PHP-DI/pull/168) `Container::has()` now returns false for interfaces and abstract classes that are not mapped in the definitions +* FIXED [#171](https://github.com/PHP-DI/PHP-DI/issues/171) Optional parameters are now ignored (not injected) if not set in the definitions (see the BC-break warning above) + +## 4.1 + +Read the [news entry](news/09-php-di-4-1-released.md). + +BC-breaks: None. + +* [#138](https://github.com/PHP-DI/PHP-DI/issues/138) [Container-interop](https://github.com/container-interop/container-interop) compliance +* [#143](https://github.com/PHP-DI/PHP-DI/issues/143) Much more explicit exception messages +* [#157](https://github.com/PHP-DI/PHP-DI/issues/157) HHVM support +* [#158](https://github.com/PHP-DI/PHP-DI/issues/158) Improved the documentation for [Symfony 2 integration](https://php-di.org/doc/frameworks/symfony2.html) + +## 4.0 + +Major changes: + +* The configuration format has changed ([read more here to understand why](news/06-php-di-4-0-new-definitions.md)) + +Read the migration guide if you are using 3.x: [Migration guide from 3.x to 4.0](doc/migration/4.0.md). + +BC-breaks: + +* YAML, XML and JSON definitions have been removed, and the PHP definition format has changed (see above) +* `ContainerSingleton` has been removed +* You cannot configure an injection as lazy anymore, you can only configure a container entry as lazy +* The Container constructor now takes mandatory parameters. Use the ContainerBuilder to create a Container. +* Removed `ContainerBuilder::setDefinitionsValidation()` (no definition validation anymore) +* `ContainerBuilder::useReflection()` is now named: `ContainerBuilder::useAutowiring()` +* `ContainerBuilder::addDefinitionsFromFile()` is now named: `ContainerBuilder::addDefinitions()` +* The `$proxy` parameter in `Container::get($name, $proxy = true)` hase been removed. To get a proxy, you now need to define an entry as "lazy". + +Other changes: + +* Added `ContainerInterface` and `FactoryInterface`, both implemented by the container. +* [#115](https://github.com/PHP-DI/PHP-DI/issues/115) Added `Container::has()` +* [#142](https://github.com/PHP-DI/PHP-DI/issues/142) Added `Container::make()` to resolve an entry +* [#127](https://github.com/PHP-DI/PHP-DI/issues/127) Added support for cases where PHP-DI is wrapped by another container (like Acclimate): PHP-DI can now use the wrapping container to perform injections +* [#128](https://github.com/PHP-DI/PHP-DI/issues/128) Configure entry aliases +* [#110](https://github.com/PHP-DI/PHP-DI/issues/110) XML definitions are not supported anymore +* [#122](https://github.com/PHP-DI/PHP-DI/issues/122) JSON definitions are not supported anymore +* `ContainerSingleton` has finally been removed +* Added `ContainerBuilder::buildDevContainer()` to get started with a default container very easily. +* [#99](https://github.com/PHP-DI/PHP-DI/issues/99) Fixed "`@param` with PHP internal type throws exception" + +## 3.5.1 + +* FIXED [#126](https://github.com/PHP-DI/PHP-DI/issues/126): `Container::set` without effect if a value has already been set and retrieved + +## 3.5 + +Read the [news entry](news/05-php-di-3-5.md). + +* Importing `@Inject` and `@Injectable` annotations is now optional! It means that you don't have to write `use DI\Annotation\Inject` anymore +* FIXED [#124](https://github.com/PHP-DI/PHP-DI/issues/124): `@Injects` annotation conflicts with other annotations + +## 3.4 + +Read the [news entry](news/04-php-di-3-4.md). + +* [#106](https://github.com/PHP-DI/PHP-DI/pull/106) You can now define arrays of values (in YAML, PHP, …) thanks to [@unkind](https://github.com/unkind) +* [#98](https://github.com/PHP-DI/PHP-DI/issues/98) `ContainerBuilder` is now fluent thanks to [@drdamour](https://github.com/drdamour) +* [#101](https://github.com/PHP-DI/PHP-DI/pull/101) Optional parameters are now supported: if you don't define a value to inject, their default value will be used +* XML definitions have been deprecated, there weren't even documented and were not maintained. They will be removed in 4.0. +* FIXED [#100](https://github.com/PHP-DI/PHP-DI/issues/100): bug for lazy injection in constructors + +## 3.3 + +Read the [news entry](news/03-php-di-3-3.md). + +* Inject dependencies on an existing instance with `Container::injectOn` (work from [Jeff Flitton](https://github.com/jflitton): [#89](https://github.com/PHP-DI/PHP-DI/pull/89)). +* [#86](https://github.com/PHP-DI/PHP-DI/issues/86): Optimized definition lookup (faster) +* FIXED [#87](https://github.com/PHP-DI/PHP-DI/issues/87): Rare bug in the `PhpDocParser`, fixed by [drdamour](https://github.com/drdamour) + +## 3.2 + +Read the [news entry](news/02-php-di-3-2.md). + +Small BC-break: PHP-DI 3.0 and 3.1 injected properties before calling the constructor. This was confusing and [not supported for internal classes](https://github.com/PHP-DI/PHP-DI/issues/74). +From 3.2 and on, properties are injected after calling the constructor. + +* **[Lazy injection](doc/lazy-injection.md)**: it is now possible to use lazy injection on properties and methods (setters and constructors). +* Lazy dependencies are now proxies that extend the class they proxy, so type-hinting works. +* Addition of the **`ContainerBuilder`** object, that helps to [create and configure a `Container`](doc/container-configuration.md). +* Some methods for configuring the Container have gone **deprecated** in favor of the `ContainerBuilder`. Fear not, these deprecated methods will remain until next major version (4.0). + * `Container::useReflection`, use ContainerBuilder::useReflection instead + * `Container::useAnnotations`, use ContainerBuilder::useAnnotations instead + * `Container::setDefinitionCache`, use ContainerBuilder::setDefinitionCache instead + * `Container::setDefinitionsValidation`, use ContainerBuilder::setDefinitionsValidation instead +* The container is now auto-registered (as 'DI\Container'). You can now inject the container without registering it. + +## 3.1.1 + +* Value definitions (`$container->set('foo', 80)`) are not cached anymore +* FIXED [#82](https://github.com/PHP-DI/PHP-DI/issues/82): Serialization error when using a cache + +## 3.1 + +Read the [news entry](news/01-php-di-3-1.md). + +* Zend Framework 1 integration through the [PHP-DI-ZF1 project](https://github.com/PHP-DI/PHP-DI-ZF1) +* Fixed the order of priorities when you mix different definition sources (reflection, annotations, files, …). See [Definition overriding](doc/definition-overriding.md) +* Now possible to define null values with `$container->set('foo', null)` (see [#79](https://github.com/PHP-DI/PHP-DI/issues/79)). +* Deprecated usage of `ContainerSingleton`, will be removed in next major version (4.0) + +## 3.0.6 + +* FIXED [#76](https://github.com/PHP-DI/PHP-DI/issues/76): Definition conflict when setting a closure for a class name + +## 3.0.5 + +* FIXED [#70](https://github.com/PHP-DI/PHP-DI/issues/70): Definition conflict when setting a value for a class name + +## 3.0.4 + +* FIXED [#69](https://github.com/PHP-DI/PHP-DI/issues/69): YamlDefinitionFileLoader crashes if YAML file is empty + +## 3.0.3 + +* Fixed over-restrictive dependencies in composer.json + +## 3.0.2 + +* [#64](https://github.com/PHP-DI/PHP-DI/issues/64): Non PHP-DI exceptions are not captured-rethrown anymore when injecting dependencies (cleaner stack trace) + +## 3.0.1 + +* [#62](https://github.com/PHP-DI/PHP-DI/issues/62): When using aliases, definitions are now merged + +## 3.0 + +Major compatibility breaks with 2.x. + +* The container is no longer a Singleton (but `ContainerSingleton::getInstance()` is available for fools who like it) +* Setter injection +* Constructor injection +* Scopes: singleton (share the same instance of the class) or prototype (create a new instance each time it is fetched). Defined at class level. +* Configuration is reworked from scratch. Now every configuration backend can do 100% of the job. +* Provided configuration backends: + * Reflection + * Annotations: @Inject, @Injectable + * PHP code (`Container::set()`) + * PHP array + * YAML file +* As a consequence, annotations are not mandatory anymore, all functionalities can be used with or without annotations. +* Renamed `DI\Annotations\` to `DI\Annotation\` +* `Container` no longer implements ArrayAccess, use only `$container->get($key)` now +* ZF1 integration broken and removed (work in progress for next releases) +* Code now follows PSR1 and PSR2 coding styles +* FIXED: [#58](https://github.com/PHP-DI/PHP-DI/issues/58) Getting a proxy of an alias didn't work + +## 2.1 + +* `use` statements to import classes from other namespaces are now taken into account with the `@var` annotation +* Updated and lightened the dependencies : `doctrine/common` has been replaced with more specific `doctrine/annotations` and `doctrine/cache` + +## 2.0 + +Major compatibility breaks with 1.x. + +* `Container::resolveDependencies()` has been renamed to `Container::injectAll()` +* Dependencies are now injected **before** the constructor is called, and thus are available in the constructor +* Merged `@Value` annotation with `@Inject`: no difference between value and bean injection anymore +* Container implements ArrayAccess for get() and set() (`$container['db.host'] = 'localhost';`) +* Ini configuration files removed: configuration is done in PHP +* Allow to define beans within closures for lazy-loading +* Switched to MIT License + +Warning: + +* If you use PHP 5.3 and __wakeup() methods, they will be called when PHP-DI creates new instances of those classes. + +## 1.1 + +* Caching of annotations based on Doctrine caches + +## 1.0 + +* DependencyManager renamed to Container +* Refactored basic Container usage with `get` and `set` +* Allow named injection `@Inject(name="")` +* Zend Framework integration diff --git a/vendor/php-di/php-di/composer.json b/vendor/php-di/php-di/composer.json new file mode 100644 index 0000000..16b5f26 --- /dev/null +++ b/vendor/php-di/php-di/composer.json @@ -0,0 +1,49 @@ +{ + "name": "php-di/php-di", + "type": "library", + "description": "The dependency injection container for humans", + "keywords": ["di", "dependency injection", "container", "ioc", "psr-11", "psr11", "container-interop"], + "homepage": "https://php-di.org/", + "license": "MIT", + "autoload": { + "psr-4": { + "DI\\": "src/" + }, + "files": [ + "src/functions.php" + ] + }, + "autoload-dev": { + "psr-4": { + "DI\\Test\\IntegrationTest\\": "tests/IntegrationTest/", + "DI\\Test\\UnitTest\\": "tests/UnitTest/" + } + }, + "scripts": { + "test": "phpunit", + "format-code": "php-cs-fixer fix --allow-risky=yes", + "phpstan": "phpstan analyse -l 5 -c phpstan.neon src" + }, + "require": { + "php": ">=7.4.0", + "psr/container": "^1.0", + "php-di/invoker": "^2.0", + "php-di/phpdoc-reader": "^2.0.1", + "laravel/serializable-closure": "^1.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.5", + "mnapoli/phpunit-easymock": "^1.2", + "doctrine/annotations": "~1.10", + "ocramius/proxy-manager": "^2.11.2", + "friendsofphp/php-cs-fixer": "^2.4", + "phpstan/phpstan": "^0.12" + }, + "provide": { + "psr/container-implementation": "^1.0" + }, + "suggest": { + "doctrine/annotations": "Install it if you want to use annotations (version ~1.2)", + "ocramius/proxy-manager": "Install it if you want to use lazy injection (version ~2.0)" + } +} diff --git a/vendor/php-di/php-di/src/Annotation/Inject.php b/vendor/php-di/php-di/src/Annotation/Inject.php new file mode 100644 index 0000000..c0eef19 --- /dev/null +++ b/vendor/php-di/php-di/src/Annotation/Inject.php @@ -0,0 +1,93 @@ + + */ +final class Inject +{ + /** + * Entry name. + * @var string + */ + private $name; + + /** + * Parameters, indexed by the parameter number (index) or name. + * + * Used if the annotation is set on a method + * @var array + */ + private $parameters = []; + + /** + * @throws InvalidAnnotation + */ + public function __construct(array $values) + { + // Process the parameters as a list AND as a parameter array (we don't know on what the annotation is) + + // @Inject(name="foo") + if (isset($values['name']) && is_string($values['name'])) { + $this->name = $values['name']; + + return; + } + + // @Inject + if (! isset($values['value'])) { + return; + } + + $values = $values['value']; + + // @Inject("foo") + if (is_string($values)) { + $this->name = $values; + } + + // @Inject({...}) on a method + if (is_array($values)) { + foreach ($values as $key => $value) { + if (! is_string($value)) { + throw new InvalidAnnotation(sprintf( + '@Inject({"param" = "value"}) expects "value" to be a string, %s given.', + json_encode($value) + )); + } + + $this->parameters[$key] = $value; + } + } + } + + /** + * @return string|null Name of the entry to inject + */ + public function getName() + { + return $this->name; + } + + /** + * @return array Parameters, indexed by the parameter number (index) or name + */ + public function getParameters() : array + { + return $this->parameters; + } +} diff --git a/vendor/php-di/php-di/src/Annotation/Injectable.php b/vendor/php-di/php-di/src/Annotation/Injectable.php new file mode 100644 index 0000000..ea15944 --- /dev/null +++ b/vendor/php-di/php-di/src/Annotation/Injectable.php @@ -0,0 +1,42 @@ + + * @author Matthieu Napoli + */ +final class Injectable +{ + /** + * Should the object be lazy-loaded. + * @var bool|null + */ + private $lazy; + + public function __construct(array $values) + { + if (isset($values['lazy'])) { + $this->lazy = (bool) $values['lazy']; + } + } + + /** + * @return bool|null + */ + public function isLazy() + { + return $this->lazy; + } +} diff --git a/vendor/php-di/php-di/src/CompiledContainer.php b/vendor/php-di/php-di/src/CompiledContainer.php new file mode 100644 index 0000000..31fc017 --- /dev/null +++ b/vendor/php-di/php-di/src/CompiledContainer.php @@ -0,0 +1,129 @@ + + */ +abstract class CompiledContainer extends Container +{ + /** + * This const is overridden in child classes (compiled containers). + * @var array + */ + protected const METHOD_MAPPING = []; + + /** + * @var InvokerInterface + */ + private $factoryInvoker; + + /** + * {@inheritdoc} + */ + public function get($name) + { + // Try to find the entry in the singleton map + if (isset($this->resolvedEntries[$name]) || array_key_exists($name, $this->resolvedEntries)) { + return $this->resolvedEntries[$name]; + } + + $method = static::METHOD_MAPPING[$name] ?? null; + + // If it's a compiled entry, then there is a method in this class + if ($method !== null) { + // Check if we are already getting this entry -> circular dependency + if (isset($this->entriesBeingResolved[$name])) { + throw new DependencyException("Circular dependency detected while trying to resolve entry '$name'"); + } + $this->entriesBeingResolved[$name] = true; + + try { + $value = $this->$method(); + } finally { + unset($this->entriesBeingResolved[$name]); + } + + // Store the entry to always return it without recomputing it + $this->resolvedEntries[$name] = $value; + + return $value; + } + + return parent::get($name); + } + + /** + * {@inheritdoc} + */ + public function has($name) + { + if (! is_string($name)) { + throw new \InvalidArgumentException(sprintf( + 'The name parameter must be of type string, %s given', + is_object($name) ? get_class($name) : gettype($name) + )); + } + + // The parent method is overridden to check in our array, it avoids resolving definitions + if (isset(static::METHOD_MAPPING[$name])) { + return true; + } + + return parent::has($name); + } + + protected function setDefinition(string $name, Definition $definition) + { + // It needs to be forbidden because that would mean get() must go through the definitions + // every time, which kinds of defeats the performance gains of the compiled container + throw new \LogicException('You cannot set a definition at runtime on a compiled container. You can either put your definitions in a file, disable compilation or ->set() a raw value directly (PHP object, string, int, ...) instead of a PHP-DI definition.'); + } + + /** + * Invoke the given callable. + */ + protected function resolveFactory($callable, $entryName, array $extraParameters = []) + { + // Initialize the factory resolver + if (! $this->factoryInvoker) { + $parameterResolver = new ResolverChain([ + new AssociativeArrayResolver, + new FactoryParameterResolver($this->delegateContainer), + new NumericArrayResolver, + new DefaultValueResolver, + ]); + + $this->factoryInvoker = new Invoker($parameterResolver, $this->delegateContainer); + } + + $parameters = [$this->delegateContainer, new RequestedEntryHolder($entryName)]; + + $parameters = array_merge($parameters, $extraParameters); + + try { + return $this->factoryInvoker->call($callable, $parameters); + } catch (NotCallableException $e) { + throw new InvalidDefinition("Entry \"$entryName\" cannot be resolved: factory " . $e->getMessage()); + } catch (NotEnoughParametersException $e) { + throw new InvalidDefinition("Entry \"$entryName\" cannot be resolved: " . $e->getMessage()); + } + } +} diff --git a/vendor/php-di/php-di/src/Compiler/Compiler.php b/vendor/php-di/php-di/src/Compiler/Compiler.php new file mode 100644 index 0000000..ca5d494 --- /dev/null +++ b/vendor/php-di/php-di/src/Compiler/Compiler.php @@ -0,0 +1,422 @@ + + */ +class Compiler +{ + /** + * @var string + */ + private $containerClass; + + /** + * @var string + */ + private $containerParentClass; + + /** + * Definitions indexed by the entry name. The value can be null if the definition needs to be fetched. + * + * Keys are strings, values are `Definition` objects or null. + * + * @var \ArrayIterator + */ + private $entriesToCompile; + + /** + * Progressive counter for definitions. + * + * Each key in $entriesToCompile is defined as 'SubEntry' + counter + * and each definition has always the same key in the CompiledContainer + * if PHP-DI configuration does not change. + * + * @var int + */ + private $subEntryCounter; + + /** + * Progressive counter for CompiledContainer get methods. + * + * Each CompiledContainer method name is defined as 'get' + counter + * and remains the same after each recompilation + * if PHP-DI configuration does not change. + * + * @var int + */ + private $methodMappingCounter; + + /** + * Map of entry names to method names. + * + * @var string[] + */ + private $entryToMethodMapping = []; + + /** + * @var string[] + */ + private $methods = []; + + /** + * @var bool + */ + private $autowiringEnabled; + + /** + * @var ProxyFactory + */ + private $proxyFactory; + + public function __construct(ProxyFactory $proxyFactory) + { + $this->proxyFactory = $proxyFactory; + } + + public function getProxyFactory() : ProxyFactory + { + return $this->proxyFactory; + } + + /** + * Compile the container. + * + * @return string The compiled container file name. + */ + public function compile( + DefinitionSource $definitionSource, + string $directory, + string $className, + string $parentClassName, + bool $autowiringEnabled + ) : string { + $fileName = rtrim($directory, '/') . '/' . $className . '.php'; + + if (file_exists($fileName)) { + // The container is already compiled + return $fileName; + } + + $this->autowiringEnabled = $autowiringEnabled; + + // Validate that a valid class name was provided + $validClassName = preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $className); + if (!$validClassName) { + throw new InvalidArgumentException("The container cannot be compiled: `$className` is not a valid PHP class name"); + } + + $this->entriesToCompile = new \ArrayIterator($definitionSource->getDefinitions()); + + // We use an ArrayIterator so that we can keep adding new items to the list while we compile entries + foreach ($this->entriesToCompile as $entryName => $definition) { + $silenceErrors = false; + // This is an entry found by reference during autowiring + if (!$definition) { + $definition = $definitionSource->getDefinition($entryName); + // We silence errors for those entries because type-hints may reference interfaces/abstract classes + // which could later be defined, or even not used (we don't want to block the compilation for those) + $silenceErrors = true; + } + if (!$definition) { + // We do not throw a `NotFound` exception here because the dependency + // could be defined at runtime + continue; + } + // Check that the definition can be compiled + $errorMessage = $this->isCompilable($definition); + if ($errorMessage !== true) { + continue; + } + try { + $this->compileDefinition($entryName, $definition); + } catch (InvalidDefinition $e) { + if ($silenceErrors) { + // forget the entry + unset($this->entryToMethodMapping[$entryName]); + } else { + throw $e; + } + } + } + + $this->containerClass = $className; + $this->containerParentClass = $parentClassName; + + ob_start(); + require __DIR__ . '/Template.php'; + $fileContent = ob_get_clean(); + + $fileContent = "createCompilationDirectory(dirname($fileName)); + $this->writeFileAtomic($fileName, $fileContent); + + return $fileName; + } + + private function writeFileAtomic(string $fileName, string $content) : int + { + $tmpFile = @tempnam(dirname($fileName), 'swap-compile'); + if ($tmpFile === false) { + throw new InvalidArgumentException( + sprintf('Error while creating temporary file in %s', dirname($fileName)) + ); + } + @chmod($tmpFile, 0666); + + $written = file_put_contents($tmpFile, $content); + if ($written === false) { + @unlink($tmpFile); + + throw new InvalidArgumentException(sprintf('Error while writing to %s', $tmpFile)); + } + + @chmod($tmpFile, 0666); + $renamed = @rename($tmpFile, $fileName); + if (!$renamed) { + @unlink($tmpFile); + throw new InvalidArgumentException(sprintf('Error while renaming %s to %s', $tmpFile, $fileName)); + } + + return $written; + } + + /** + * @throws DependencyException + * @throws InvalidDefinition + * @return string The method name + */ + private function compileDefinition(string $entryName, Definition $definition) : string + { + // Generate a unique method name + $methodName = 'get' . (++$this->methodMappingCounter); + $this->entryToMethodMapping[$entryName] = $methodName; + + switch (true) { + case $definition instanceof ValueDefinition: + $value = $definition->getValue(); + $code = 'return ' . $this->compileValue($value) . ';'; + break; + case $definition instanceof Reference: + $targetEntryName = $definition->getTargetEntryName(); + $code = 'return $this->delegateContainer->get(' . $this->compileValue($targetEntryName) . ');'; + // If this method is not yet compiled we store it for compilation + if (!isset($this->entriesToCompile[$targetEntryName])) { + $this->entriesToCompile[$targetEntryName] = null; + } + break; + case $definition instanceof StringDefinition: + $entryName = $this->compileValue($definition->getName()); + $expression = $this->compileValue($definition->getExpression()); + $code = 'return \DI\Definition\StringDefinition::resolveExpression(' . $entryName . ', ' . $expression . ', $this->delegateContainer);'; + break; + case $definition instanceof EnvironmentVariableDefinition: + $variableName = $this->compileValue($definition->getVariableName()); + $isOptional = $this->compileValue($definition->isOptional()); + $defaultValue = $this->compileValue($definition->getDefaultValue()); + $code = <<getVariableName()}' has not been defined"); + } + return $defaultValue; +PHP; + break; + case $definition instanceof ArrayDefinition: + try { + $code = 'return ' . $this->compileValue($definition->getValues()) . ';'; + } catch (\Exception $e) { + throw new DependencyException(sprintf( + 'Error while compiling %s. %s', + $definition->getName(), + $e->getMessage() + ), 0, $e); + } + break; + case $definition instanceof ObjectDefinition: + $compiler = new ObjectCreationCompiler($this); + $code = $compiler->compile($definition); + $code .= "\n return \$object;"; + break; + case $definition instanceof DecoratorDefinition: + $decoratedDefinition = $definition->getDecoratedDefinition(); + if (! $decoratedDefinition instanceof Definition) { + if (! $definition->getName()) { + throw new InvalidDefinition('Decorators cannot be nested in another definition'); + } + throw new InvalidDefinition(sprintf( + 'Entry "%s" decorates nothing: no previous definition with the same name was found', + $definition->getName() + )); + } + $code = sprintf( + 'return call_user_func(%s, %s, $this->delegateContainer);', + $this->compileValue($definition->getCallable()), + $this->compileValue($decoratedDefinition) + ); + break; + case $definition instanceof FactoryDefinition: + $value = $definition->getCallable(); + + // Custom error message to help debugging + $isInvokableClass = is_string($value) && class_exists($value) && method_exists($value, '__invoke'); + if ($isInvokableClass && !$this->autowiringEnabled) { + throw new InvalidDefinition(sprintf( + 'Entry "%s" cannot be compiled. Invokable classes cannot be automatically resolved if autowiring is disabled on the container, you need to enable autowiring or define the entry manually.', + $entryName + )); + } + + $definitionParameters = ''; + if (!empty($definition->getParameters())) { + $definitionParameters = ', ' . $this->compileValue($definition->getParameters()); + } + + $code = sprintf( + 'return $this->resolveFactory(%s, %s%s);', + $this->compileValue($value), + var_export($entryName, true), + $definitionParameters + ); + + break; + default: + // This case should not happen (so it cannot be tested) + throw new \Exception('Cannot compile definition of type ' . get_class($definition)); + } + + $this->methods[$methodName] = $code; + + return $methodName; + } + + public function compileValue($value) : string + { + // Check that the value can be compiled + $errorMessage = $this->isCompilable($value); + if ($errorMessage !== true) { + throw new InvalidDefinition($errorMessage); + } + + if ($value instanceof Definition) { + // Give it an arbitrary unique name + $subEntryName = 'subEntry' . (++$this->subEntryCounter); + // Compile the sub-definition in another method + $methodName = $this->compileDefinition($subEntryName, $value); + // The value is now a method call to that method (which returns the value) + return "\$this->$methodName()"; + } + + if (is_array($value)) { + $value = array_map(function ($value, $key) { + $compiledValue = $this->compileValue($value); + $key = var_export($key, true); + + return " $key => $compiledValue,\n"; + }, $value, array_keys($value)); + $value = implode('', $value); + + return "[\n$value ]"; + } + + if ($value instanceof \Closure) { + return $this->compileClosure($value); + } + + return var_export($value, true); + } + + private function createCompilationDirectory(string $directory) + { + if (!is_dir($directory) && !@mkdir($directory, 0777, true) && !is_dir($directory)) { + throw new InvalidArgumentException(sprintf('Compilation directory does not exist and cannot be created: %s.', $directory)); + } + if (!is_writable($directory)) { + throw new InvalidArgumentException(sprintf('Compilation directory is not writable: %s.', $directory)); + } + } + + /** + * @return string|true If true is returned that means that the value is compilable. + */ + private function isCompilable($value) + { + if ($value instanceof ValueDefinition) { + return $this->isCompilable($value->getValue()); + } + if ($value instanceof DecoratorDefinition) { + if (empty($value->getName())) { + return 'Decorators cannot be nested in another definition'; + } + } + // All other definitions are compilable + if ($value instanceof Definition) { + return true; + } + if ($value instanceof \Closure) { + return true; + } + if (is_object($value)) { + return 'An object was found but objects cannot be compiled'; + } + if (is_resource($value)) { + return 'A resource was found but resources cannot be compiled'; + } + + return true; + } + + /** + * @throws \DI\Definition\Exception\InvalidDefinition + */ + private function compileClosure(\Closure $closure) : string + { + $reflector = new ReflectionClosure($closure); + + if ($reflector->getUseVariables()) { + throw new InvalidDefinition('Cannot compile closures which import variables using the `use` keyword'); + } + + if ($reflector->isBindingRequired() || $reflector->isScopeRequired()) { + throw new InvalidDefinition('Cannot compile closures which use $this or self/static/parent references'); + } + + // Force all closures to be static (add the `static` keyword), i.e. they can't use + // $this, which makes sense since their code is copied into another class. + $code = ($reflector->isStatic() ? '' : 'static ') . $reflector->getCode(); + + $code = trim($code, "\t\n\r;"); + + return $code; + } +} diff --git a/vendor/php-di/php-di/src/Compiler/ObjectCreationCompiler.php b/vendor/php-di/php-di/src/Compiler/ObjectCreationCompiler.php new file mode 100644 index 0000000..9f19d4c --- /dev/null +++ b/vendor/php-di/php-di/src/Compiler/ObjectCreationCompiler.php @@ -0,0 +1,201 @@ + + */ +class ObjectCreationCompiler +{ + /** + * @var Compiler + */ + private $compiler; + + public function __construct(Compiler $compiler) + { + $this->compiler = $compiler; + } + + public function compile(ObjectDefinition $definition) : string + { + $this->assertClassIsNotAnonymous($definition); + $this->assertClassIsInstantiable($definition); + + // Lazy? + if ($definition->isLazy()) { + return $this->compileLazyDefinition($definition); + } + + try { + $classReflection = new ReflectionClass($definition->getClassName()); + $constructorArguments = $this->resolveParameters($definition->getConstructorInjection(), $classReflection->getConstructor()); + $dumpedConstructorArguments = array_map(function ($value) { + return $this->compiler->compileValue($value); + }, $constructorArguments); + + $code = []; + $code[] = sprintf( + '$object = new %s(%s);', + $definition->getClassName(), + implode(', ', $dumpedConstructorArguments) + ); + + // Property injections + foreach ($definition->getPropertyInjections() as $propertyInjection) { + $value = $propertyInjection->getValue(); + $value = $this->compiler->compileValue($value); + + $className = $propertyInjection->getClassName() ?: $definition->getClassName(); + $property = new ReflectionProperty($className, $propertyInjection->getPropertyName()); + if ($property->isPublic()) { + $code[] = sprintf('$object->%s = %s;', $propertyInjection->getPropertyName(), $value); + } else { + // Private/protected property + $code[] = sprintf( + '\DI\Definition\Resolver\ObjectCreator::setPrivatePropertyValue(%s, $object, \'%s\', %s);', + var_export($propertyInjection->getClassName(), true), + $propertyInjection->getPropertyName(), + $value + ); + } + } + + // Method injections + foreach ($definition->getMethodInjections() as $methodInjection) { + $methodReflection = new \ReflectionMethod($definition->getClassName(), $methodInjection->getMethodName()); + $parameters = $this->resolveParameters($methodInjection, $methodReflection); + + $dumpedParameters = array_map(function ($value) { + return $this->compiler->compileValue($value); + }, $parameters); + + $code[] = sprintf( + '$object->%s(%s);', + $methodInjection->getMethodName(), + implode(', ', $dumpedParameters) + ); + } + } catch (InvalidDefinition $e) { + throw InvalidDefinition::create($definition, sprintf( + 'Entry "%s" cannot be compiled: %s', + $definition->getName(), + $e->getMessage() + )); + } + + return implode("\n ", $code); + } + + public function resolveParameters(MethodInjection $definition = null, ReflectionMethod $method = null) : array + { + $args = []; + + if (! $method) { + return $args; + } + + $definitionParameters = $definition ? $definition->getParameters() : []; + + foreach ($method->getParameters() as $index => $parameter) { + if (array_key_exists($index, $definitionParameters)) { + // Look in the definition + $value = &$definitionParameters[$index]; + } elseif ($parameter->isOptional()) { + // If the parameter is optional and wasn't specified, we take its default value + $args[] = $this->getParameterDefaultValue($parameter, $method); + continue; + } else { + throw new InvalidDefinition(sprintf( + 'Parameter $%s of %s has no value defined or guessable', + $parameter->getName(), + $this->getFunctionName($method) + )); + } + + $args[] = &$value; + } + + return $args; + } + + private function compileLazyDefinition(ObjectDefinition $definition) : string + { + $subDefinition = clone $definition; + $subDefinition->setLazy(false); + $subDefinition = $this->compiler->compileValue($subDefinition); + + $this->compiler->getProxyFactory()->generateProxyClass($definition->getClassName()); + + return <<proxyFactory->createProxy( + '{$definition->getClassName()}', + function (&\$wrappedObject, \$proxy, \$method, \$params, &\$initializer) { + \$wrappedObject = $subDefinition; + \$initializer = null; // turning off further lazy initialization + return true; + } + ); +PHP; + } + + /** + * Returns the default value of a function parameter. + * + * @throws InvalidDefinition Can't get default values from PHP internal classes and functions + * @return mixed + */ + private function getParameterDefaultValue(ReflectionParameter $parameter, ReflectionMethod $function) + { + try { + return $parameter->getDefaultValue(); + } catch (\ReflectionException $e) { + throw new InvalidDefinition(sprintf( + 'The parameter "%s" of %s has no type defined or guessable. It has a default value, ' + . 'but the default value can\'t be read through Reflection because it is a PHP internal class.', + $parameter->getName(), + $this->getFunctionName($function) + )); + } + } + + private function getFunctionName(ReflectionMethod $method) : string + { + return $method->getName() . '()'; + } + + private function assertClassIsNotAnonymous(ObjectDefinition $definition) + { + if (strpos($definition->getClassName(), '@') !== false) { + throw InvalidDefinition::create($definition, sprintf( + 'Entry "%s" cannot be compiled: anonymous classes cannot be compiled', + $definition->getName() + )); + } + } + + private function assertClassIsInstantiable(ObjectDefinition $definition) + { + if ($definition->isInstantiable()) { + return; + } + + $message = ! $definition->classExists() + ? 'Entry "%s" cannot be compiled: the class doesn\'t exist' + : 'Entry "%s" cannot be compiled: the class is not instantiable'; + + throw InvalidDefinition::create($definition, sprintf($message, $definition->getName())); + } +} diff --git a/vendor/php-di/php-di/src/Compiler/RequestedEntryHolder.php b/vendor/php-di/php-di/src/Compiler/RequestedEntryHolder.php new file mode 100644 index 0000000..68b5bc2 --- /dev/null +++ b/vendor/php-di/php-di/src/Compiler/RequestedEntryHolder.php @@ -0,0 +1,28 @@ + + */ +class RequestedEntryHolder implements RequestedEntry +{ + /** + * @var string + */ + private $name; + + public function __construct(string $name) + { + $this->name = $name; + } + + public function getName() : string + { + return $this->name; + } +} diff --git a/vendor/php-di/php-di/src/Compiler/Template.php b/vendor/php-di/php-di/src/Compiler/Template.php new file mode 100644 index 0000000..e053639 --- /dev/null +++ b/vendor/php-di/php-di/src/Compiler/Template.php @@ -0,0 +1,16 @@ +/** + * This class has been auto-generated by PHP-DI. + */ +class containerClass; ?> extends containerParentClass; ?> +{ + const METHOD_MAPPING = entryToMethodMapping); ?>; + +methods as $methodName => $methodContent) : ?> + protected function () + { + + + } + + +} diff --git a/vendor/php-di/php-di/src/Container.php b/vendor/php-di/php-di/src/Container.php new file mode 100644 index 0000000..a9c95de --- /dev/null +++ b/vendor/php-di/php-di/src/Container.php @@ -0,0 +1,433 @@ + + */ +class Container implements ContainerInterface, FactoryInterface, InvokerInterface +{ + /** + * Map of entries that are already resolved. + * @var array + */ + protected $resolvedEntries = []; + + /** + * @var MutableDefinitionSource + */ + private $definitionSource; + + /** + * @var DefinitionResolver + */ + private $definitionResolver; + + /** + * Map of definitions that are already fetched (local cache). + * + * @var (Definition|null)[] + */ + private $fetchedDefinitions = []; + + /** + * Array of entries being resolved. Used to avoid circular dependencies and infinite loops. + * @var array + */ + protected $entriesBeingResolved = []; + + /** + * @var InvokerInterface|null + */ + private $invoker; + + /** + * Container that wraps this container. If none, points to $this. + * + * @var ContainerInterface + */ + protected $delegateContainer; + + /** + * @var ProxyFactory + */ + protected $proxyFactory; + + /** + * Use `$container = new Container()` if you want a container with the default configuration. + * + * If you want to customize the container's behavior, you are discouraged to create and pass the + * dependencies yourself, the ContainerBuilder class is here to help you instead. + * + * @see ContainerBuilder + * + * @param ContainerInterface $wrapperContainer If the container is wrapped by another container. + */ + public function __construct( + MutableDefinitionSource $definitionSource = null, + ProxyFactory $proxyFactory = null, + ContainerInterface $wrapperContainer = null + ) { + $this->delegateContainer = $wrapperContainer ?: $this; + + $this->definitionSource = $definitionSource ?: $this->createDefaultDefinitionSource(); + $this->proxyFactory = $proxyFactory ?: new ProxyFactory(false); + $this->definitionResolver = new ResolverDispatcher($this->delegateContainer, $this->proxyFactory); + + // Auto-register the container + $this->resolvedEntries = [ + self::class => $this, + ContainerInterface::class => $this->delegateContainer, + FactoryInterface::class => $this, + InvokerInterface::class => $this, + ]; + } + + /** + * Returns an entry of the container by its name. + * + * @template T + * @param string|class-string $name Entry name or a class name. + * + * @throws DependencyException Error while resolving the entry. + * @throws NotFoundException No entry found for the given name. + * @return mixed|T + */ + public function get($name) + { + // If the entry is already resolved we return it + if (isset($this->resolvedEntries[$name]) || array_key_exists($name, $this->resolvedEntries)) { + return $this->resolvedEntries[$name]; + } + + $definition = $this->getDefinition($name); + if (! $definition) { + throw new NotFoundException("No entry or class found for '$name'"); + } + + $value = $this->resolveDefinition($definition); + + $this->resolvedEntries[$name] = $value; + + return $value; + } + + /** + * @param string $name + * + * @return Definition|null + */ + private function getDefinition($name) + { + // Local cache that avoids fetching the same definition twice + if (!array_key_exists($name, $this->fetchedDefinitions)) { + $this->fetchedDefinitions[$name] = $this->definitionSource->getDefinition($name); + } + + return $this->fetchedDefinitions[$name]; + } + + /** + * Build an entry of the container by its name. + * + * This method behave like get() except resolves the entry again every time. + * For example if the entry is a class then a new instance will be created each time. + * + * This method makes the container behave like a factory. + * + * @template T + * @param string|class-string $name Entry name or a class name. + * @param array $parameters Optional parameters to use to build the entry. Use this to force + * specific parameters to specific values. Parameters not defined in this + * array will be resolved using the container. + * + * @throws InvalidArgumentException The name parameter must be of type string. + * @throws DependencyException Error while resolving the entry. + * @throws NotFoundException No entry found for the given name. + * @return mixed|T + */ + public function make($name, array $parameters = []) + { + if (! is_string($name)) { + throw new InvalidArgumentException(sprintf( + 'The name parameter must be of type string, %s given', + is_object($name) ? get_class($name) : gettype($name) + )); + } + + $definition = $this->getDefinition($name); + if (! $definition) { + // If the entry is already resolved we return it + if (array_key_exists($name, $this->resolvedEntries)) { + return $this->resolvedEntries[$name]; + } + + throw new NotFoundException("No entry or class found for '$name'"); + } + + return $this->resolveDefinition($definition, $parameters); + } + + /** + * Test if the container can provide something for the given name. + * + * @param string $name Entry name or a class name. + * + * @throws InvalidArgumentException The name parameter must be of type string. + * @return bool + */ + public function has($name) + { + if (! is_string($name)) { + throw new InvalidArgumentException(sprintf( + 'The name parameter must be of type string, %s given', + is_object($name) ? get_class($name) : gettype($name) + )); + } + + if (array_key_exists($name, $this->resolvedEntries)) { + return true; + } + + $definition = $this->getDefinition($name); + if ($definition === null) { + return false; + } + + return $this->definitionResolver->isResolvable($definition); + } + + /** + * Inject all dependencies on an existing instance. + * + * @template T + * @param object|T $instance Object to perform injection upon + * @throws InvalidArgumentException + * @throws DependencyException Error while injecting dependencies + * @return object|T $instance Returns the same instance + */ + public function injectOn($instance) + { + if (!$instance) { + return $instance; + } + + $className = get_class($instance); + + // If the class is anonymous, don't cache its definition + // Checking for anonymous classes is cleaner via Reflection, but also slower + $objectDefinition = false !== strpos($className, '@anonymous') + ? $this->definitionSource->getDefinition($className) + : $this->getDefinition($className); + + if (! $objectDefinition instanceof ObjectDefinition) { + return $instance; + } + + $definition = new InstanceDefinition($instance, $objectDefinition); + + $this->definitionResolver->resolve($definition); + + return $instance; + } + + /** + * Call the given function using the given parameters. + * + * Missing parameters will be resolved from the container. + * + * @param callable $callable Function to call. + * @param array $parameters Parameters to use. Can be indexed by the parameter names + * or not indexed (same order as the parameters). + * The array can also contain DI definitions, e.g. DI\get(). + * + * @return mixed Result of the function. + */ + public function call($callable, array $parameters = []) + { + return $this->getInvoker()->call($callable, $parameters); + } + + /** + * Define an object or a value in the container. + * + * @param string $name Entry name + * @param mixed|DefinitionHelper $value Value, use definition helpers to define objects + */ + public function set(string $name, $value) + { + if ($value instanceof DefinitionHelper) { + $value = $value->getDefinition($name); + } elseif ($value instanceof \Closure) { + $value = new FactoryDefinition($name, $value); + } + + if ($value instanceof ValueDefinition) { + $this->resolvedEntries[$name] = $value->getValue(); + } elseif ($value instanceof Definition) { + $value->setName($name); + $this->setDefinition($name, $value); + } else { + $this->resolvedEntries[$name] = $value; + } + } + + /** + * Get defined container entries. + * + * @return string[] + */ + public function getKnownEntryNames() : array + { + $entries = array_unique(array_merge( + array_keys($this->definitionSource->getDefinitions()), + array_keys($this->resolvedEntries) + )); + sort($entries); + + return $entries; + } + + /** + * Get entry debug information. + * + * @param string $name Entry name + * + * @throws InvalidDefinition + * @throws NotFoundException + */ + public function debugEntry(string $name) : string + { + $definition = $this->definitionSource->getDefinition($name); + if ($definition instanceof Definition) { + return (string) $definition; + } + + if (array_key_exists($name, $this->resolvedEntries)) { + return $this->getEntryType($this->resolvedEntries[$name]); + } + + throw new NotFoundException("No entry or class found for '$name'"); + } + + /** + * Get formatted entry type. + * + * @param mixed $entry + */ + private function getEntryType($entry) : string + { + if (is_object($entry)) { + return sprintf("Object (\n class = %s\n)", get_class($entry)); + } + + if (is_array($entry)) { + return preg_replace(['/^array \(/', '/\)$/'], ['[', ']'], var_export($entry, true)); + } + + if (is_string($entry)) { + return sprintf('Value (\'%s\')', $entry); + } + + if (is_bool($entry)) { + return sprintf('Value (%s)', $entry === true ? 'true' : 'false'); + } + + return sprintf('Value (%s)', is_scalar($entry) ? $entry : ucfirst(gettype($entry))); + } + + /** + * Resolves a definition. + * + * Checks for circular dependencies while resolving the definition. + * + * @throws DependencyException Error while resolving the entry. + * @return mixed + */ + private function resolveDefinition(Definition $definition, array $parameters = []) + { + $entryName = $definition->getName(); + + // Check if we are already getting this entry -> circular dependency + if (isset($this->entriesBeingResolved[$entryName])) { + throw new DependencyException("Circular dependency detected while trying to resolve entry '$entryName'"); + } + $this->entriesBeingResolved[$entryName] = true; + + // Resolve the definition + try { + $value = $this->definitionResolver->resolve($definition, $parameters); + } finally { + unset($this->entriesBeingResolved[$entryName]); + } + + return $value; + } + + protected function setDefinition(string $name, Definition $definition) + { + // Clear existing entry if it exists + if (array_key_exists($name, $this->resolvedEntries)) { + unset($this->resolvedEntries[$name]); + } + $this->fetchedDefinitions = []; // Completely clear this local cache + + $this->definitionSource->addDefinition($definition); + } + + private function getInvoker() : InvokerInterface + { + if (! $this->invoker) { + $parameterResolver = new ResolverChain([ + new DefinitionParameterResolver($this->definitionResolver), + new NumericArrayResolver, + new AssociativeArrayResolver, + new DefaultValueResolver, + new TypeHintContainerResolver($this->delegateContainer), + ]); + + $this->invoker = new Invoker($parameterResolver, $this); + } + + return $this->invoker; + } + + private function createDefaultDefinitionSource() : SourceChain + { + $source = new SourceChain([new ReflectionBasedAutowiring]); + $source->setMutableDefinitionSource(new DefinitionArray([], new ReflectionBasedAutowiring)); + + return $source; + } +} diff --git a/vendor/php-di/php-di/src/ContainerBuilder.php b/vendor/php-di/php-di/src/ContainerBuilder.php new file mode 100644 index 0000000..3ee747f --- /dev/null +++ b/vendor/php-di/php-di/src/ContainerBuilder.php @@ -0,0 +1,385 @@ +build(); + * + * @api + * + * @since 3.2 + * @author Matthieu Napoli + */ +class ContainerBuilder +{ + /** + * Name of the container class, used to create the container. + * @var string + */ + private $containerClass; + + /** + * Name of the container parent class, used on compiled container. + * @var string + */ + private $containerParentClass; + + /** + * @var bool + */ + private $useAutowiring = true; + + /** + * @var bool + */ + private $useAnnotations = false; + + /** + * @var bool + */ + private $ignorePhpDocErrors = false; + + /** + * If true, write the proxies to disk to improve performances. + * @var bool + */ + private $writeProxiesToFile = false; + + /** + * Directory where to write the proxies (if $writeProxiesToFile is enabled). + * @var string|null + */ + private $proxyDirectory; + + /** + * If PHP-DI is wrapped in another container, this references the wrapper. + * @var ContainerInterface + */ + private $wrapperContainer; + + /** + * @var DefinitionSource[]|string[]|array[] + */ + private $definitionSources = []; + + /** + * Whether the container has already been built. + * @var bool + */ + private $locked = false; + + /** + * @var string|null + */ + private $compileToDirectory; + + /** + * @var bool + */ + private $sourceCache = false; + + /** + * @var string + */ + protected $sourceCacheNamespace; + + /** + * Build a container configured for the dev environment. + */ + public static function buildDevContainer() : Container + { + return new Container; + } + + /** + * @param string $containerClass Name of the container class, used to create the container. + */ + public function __construct(string $containerClass = Container::class) + { + $this->containerClass = $containerClass; + } + + /** + * Build and return a container. + * + * @return Container + */ + public function build() + { + $sources = array_reverse($this->definitionSources); + + if ($this->useAnnotations) { + $autowiring = new AnnotationBasedAutowiring($this->ignorePhpDocErrors); + $sources[] = $autowiring; + } elseif ($this->useAutowiring) { + $autowiring = new ReflectionBasedAutowiring; + $sources[] = $autowiring; + } else { + $autowiring = new NoAutowiring; + } + + $sources = array_map(function ($definitions) use ($autowiring) { + if (is_string($definitions)) { + // File + return new DefinitionFile($definitions, $autowiring); + } elseif (is_array($definitions)) { + return new DefinitionArray($definitions, $autowiring); + } + + return $definitions; + }, $sources); + $source = new SourceChain($sources); + + // Mutable definition source + $source->setMutableDefinitionSource(new DefinitionArray([], $autowiring)); + + if ($this->sourceCache) { + if (!SourceCache::isSupported()) { + throw new \Exception('APCu is not enabled, PHP-DI cannot use it as a cache'); + } + // Wrap the source with the cache decorator + $source = new SourceCache($source, $this->sourceCacheNamespace); + } + + $proxyFactory = new ProxyFactory( + $this->writeProxiesToFile, + $this->proxyDirectory + ); + + $this->locked = true; + + $containerClass = $this->containerClass; + + if ($this->compileToDirectory) { + $compiler = new Compiler($proxyFactory); + $compiledContainerFile = $compiler->compile( + $source, + $this->compileToDirectory, + $containerClass, + $this->containerParentClass, + $this->useAutowiring || $this->useAnnotations + ); + // Only load the file if it hasn't been already loaded + // (the container can be created multiple times in the same process) + if (!class_exists($containerClass, false)) { + require $compiledContainerFile; + } + } + + return new $containerClass($source, $proxyFactory, $this->wrapperContainer); + } + + /** + * Compile the container for optimum performances. + * + * Be aware that the container is compiled once and never updated! + * + * Therefore: + * + * - in production you should clear that directory every time you deploy + * - in development you should not compile the container + * + * @see https://php-di.org/doc/performances.html + * + * @param string $directory Directory in which to put the compiled container. + * @param string $containerClass Name of the compiled class. Customize only if necessary. + * @param string $containerParentClass Name of the compiled container parent class. Customize only if necessary. + */ + public function enableCompilation( + string $directory, + string $containerClass = 'CompiledContainer', + string $containerParentClass = CompiledContainer::class + ) : self { + $this->ensureNotLocked(); + + $this->compileToDirectory = $directory; + $this->containerClass = $containerClass; + $this->containerParentClass = $containerParentClass; + + return $this; + } + + /** + * Enable or disable the use of autowiring to guess injections. + * + * Enabled by default. + * + * @return $this + */ + public function useAutowiring(bool $bool) : self + { + $this->ensureNotLocked(); + + $this->useAutowiring = $bool; + + return $this; + } + + /** + * Enable or disable the use of annotations to guess injections. + * + * Disabled by default. + * + * @return $this + */ + public function useAnnotations(bool $bool) : self + { + $this->ensureNotLocked(); + + $this->useAnnotations = $bool; + + return $this; + } + + /** + * Enable or disable ignoring phpdoc errors (non-existent classes in `@param` or `@var`). + * + * @return $this + */ + public function ignorePhpDocErrors(bool $bool) : self + { + $this->ensureNotLocked(); + + $this->ignorePhpDocErrors = $bool; + + return $this; + } + + /** + * Configure the proxy generation. + * + * For dev environment, use `writeProxiesToFile(false)` (default configuration) + * For production environment, use `writeProxiesToFile(true, 'tmp/proxies')` + * + * @see https://php-di.org/doc/lazy-injection.html + * + * @param bool $writeToFile If true, write the proxies to disk to improve performances + * @param string|null $proxyDirectory Directory where to write the proxies + * @throws InvalidArgumentException when writeToFile is set to true and the proxy directory is null + * @return $this + */ + public function writeProxiesToFile(bool $writeToFile, string $proxyDirectory = null) : self + { + $this->ensureNotLocked(); + + $this->writeProxiesToFile = $writeToFile; + + if ($writeToFile && $proxyDirectory === null) { + throw new InvalidArgumentException( + 'The proxy directory must be specified if you want to write proxies on disk' + ); + } + $this->proxyDirectory = $proxyDirectory; + + return $this; + } + + /** + * If PHP-DI's container is wrapped by another container, we can + * set this so that PHP-DI will use the wrapper rather than itself for building objects. + * + * @return $this + */ + public function wrapContainer(ContainerInterface $otherContainer) : self + { + $this->ensureNotLocked(); + + $this->wrapperContainer = $otherContainer; + + return $this; + } + + /** + * Add definitions to the container. + * + * @param string|array|DefinitionSource ...$definitions Can be an array of definitions, the + * name of a file containing definitions + * or a DefinitionSource object. + * @return $this + */ + public function addDefinitions(...$definitions) : self + { + $this->ensureNotLocked(); + + foreach ($definitions as $definition) { + if (!is_string($definition) && !is_array($definition) && !($definition instanceof DefinitionSource)) { + throw new InvalidArgumentException(sprintf( + '%s parameter must be a string, an array or a DefinitionSource object, %s given', + 'ContainerBuilder::addDefinitions()', + is_object($definition) ? get_class($definition) : gettype($definition) + )); + } + + $this->definitionSources[] = $definition; + } + + return $this; + } + + /** + * Enables the use of APCu to cache definitions. + * + * You must have APCu enabled to use it. + * + * Before using this feature, you should try these steps first: + * - enable compilation if not already done (see `enableCompilation()`) + * - if you use autowiring or annotations, add all the classes you are using into your configuration so that + * PHP-DI knows about them and compiles them + * Once this is done, you can try to optimize performances further with APCu. It can also be useful if you use + * `Container::make()` instead of `get()` (`make()` calls cannot be compiled so they are not optimized). + * + * Remember to clear APCu on each deploy else your application will have a stale cache. Do not enable the cache + * in development environment: any change you will make to the code will be ignored because of the cache. + * + * @see https://php-di.org/doc/performances.html + * + * @param string $cacheNamespace use unique namespace per container when sharing a single APC memory pool to prevent cache collisions + * @return $this + */ + public function enableDefinitionCache(string $cacheNamespace = '') : self + { + $this->ensureNotLocked(); + + $this->sourceCache = true; + $this->sourceCacheNamespace = $cacheNamespace; + + return $this; + } + + /** + * Are we building a compiled container? + */ + public function isCompilationEnabled() : bool + { + return (bool) $this->compileToDirectory; + } + + private function ensureNotLocked() + { + if ($this->locked) { + throw new \LogicException('The ContainerBuilder cannot be modified after the container has been built'); + } + } +} diff --git a/vendor/php-di/php-di/src/Definition/ArrayDefinition.php b/vendor/php-di/php-di/src/Definition/ArrayDefinition.php new file mode 100644 index 0000000..ef77100 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/ArrayDefinition.php @@ -0,0 +1,73 @@ + + */ +class ArrayDefinition implements Definition +{ + /** + * Entry name. + * @var string + */ + private $name = ''; + + /** + * @var array + */ + private $values; + + public function __construct(array $values) + { + $this->values = $values; + } + + public function getName() : string + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + public function getValues() : array + { + return $this->values; + } + + public function replaceNestedDefinitions(callable $replacer) + { + $this->values = array_map($replacer, $this->values); + } + + public function __toString() + { + $str = '[' . \PHP_EOL; + + foreach ($this->values as $key => $value) { + if (is_string($key)) { + $key = "'" . $key . "'"; + } + + $str .= ' ' . $key . ' => '; + + if ($value instanceof Definition) { + $str .= str_replace(\PHP_EOL, \PHP_EOL . ' ', (string) $value); + } else { + $str .= var_export($value, true); + } + + $str .= ',' . \PHP_EOL; + } + + return $str . ']'; + } +} diff --git a/vendor/php-di/php-di/src/Definition/ArrayDefinitionExtension.php b/vendor/php-di/php-di/src/Definition/ArrayDefinitionExtension.php new file mode 100644 index 0000000..b494873 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/ArrayDefinitionExtension.php @@ -0,0 +1,42 @@ + + */ +class ArrayDefinitionExtension extends ArrayDefinition implements ExtendsPreviousDefinition +{ + /** + * @var ArrayDefinition + */ + private $subDefinition; + + public function getValues() : array + { + if (! $this->subDefinition) { + return parent::getValues(); + } + + return array_merge($this->subDefinition->getValues(), parent::getValues()); + } + + public function setExtendedDefinition(Definition $definition) + { + if (! $definition instanceof ArrayDefinition) { + throw new InvalidDefinition(sprintf( + 'Definition %s tries to add array entries but the previous definition is not an array', + $this->getName() + )); + } + + $this->subDefinition = $definition; + } +} diff --git a/vendor/php-di/php-di/src/Definition/AutowireDefinition.php b/vendor/php-di/php-di/src/Definition/AutowireDefinition.php new file mode 100644 index 0000000..25dc3ec --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/AutowireDefinition.php @@ -0,0 +1,12 @@ + + */ +class AutowireDefinition extends ObjectDefinition +{ +} diff --git a/vendor/php-di/php-di/src/Definition/DecoratorDefinition.php b/vendor/php-di/php-di/src/Definition/DecoratorDefinition.php new file mode 100644 index 0000000..4489485 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/DecoratorDefinition.php @@ -0,0 +1,42 @@ + + */ +class DecoratorDefinition extends FactoryDefinition implements Definition, ExtendsPreviousDefinition +{ + /** + * @var Definition|null + */ + private $decorated; + + public function setExtendedDefinition(Definition $definition) + { + $this->decorated = $definition; + } + + /** + * @return Definition|null + */ + public function getDecoratedDefinition() + { + return $this->decorated; + } + + public function replaceNestedDefinitions(callable $replacer) + { + // no nested definitions + } + + public function __toString() + { + return 'Decorate(' . $this->getName() . ')'; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Definition.php b/vendor/php-di/php-di/src/Definition/Definition.php new file mode 100644 index 0000000..696838d --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Definition.php @@ -0,0 +1,37 @@ + + */ +interface Definition extends RequestedEntry +{ + /** + * Returns the name of the entry in the container. + */ + public function getName() : string; + + /** + * Set the name of the entry in the container. + */ + public function setName(string $name); + + /** + * Apply a callable that replaces the definitions nested in this definition. + */ + public function replaceNestedDefinitions(callable $replacer); + + /** + * Definitions can be cast to string for debugging information. + */ + public function __toString(); +} diff --git a/vendor/php-di/php-di/src/Definition/Dumper/ObjectDefinitionDumper.php b/vendor/php-di/php-di/src/Definition/Dumper/ObjectDefinitionDumper.php new file mode 100644 index 0000000..b99695f --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Dumper/ObjectDefinitionDumper.php @@ -0,0 +1,135 @@ + + */ +class ObjectDefinitionDumper +{ + /** + * Returns the definition as string representation. + */ + public function dump(ObjectDefinition $definition) : string + { + $className = $definition->getClassName(); + $classExist = class_exists($className) || interface_exists($className); + + // Class + if (! $classExist) { + $warning = '#UNKNOWN# '; + } else { + $class = new \ReflectionClass($className); + $warning = $class->isInstantiable() ? '' : '#NOT INSTANTIABLE# '; + } + $str = sprintf(' class = %s%s', $warning, $className); + + // Lazy + $str .= \PHP_EOL . ' lazy = ' . var_export($definition->isLazy(), true); + + if ($classExist) { + // Constructor + $str .= $this->dumpConstructor($className, $definition); + + // Properties + $str .= $this->dumpProperties($definition); + + // Methods + $str .= $this->dumpMethods($className, $definition); + } + + return sprintf('Object (' . \PHP_EOL . '%s' . \PHP_EOL . ')', $str); + } + + private function dumpConstructor(string $className, ObjectDefinition $definition) : string + { + $str = ''; + + $constructorInjection = $definition->getConstructorInjection(); + + if ($constructorInjection !== null) { + $parameters = $this->dumpMethodParameters($className, $constructorInjection); + + $str .= sprintf(\PHP_EOL . ' __construct(' . \PHP_EOL . ' %s' . \PHP_EOL . ' )', $parameters); + } + + return $str; + } + + private function dumpProperties(ObjectDefinition $definition) : string + { + $str = ''; + + foreach ($definition->getPropertyInjections() as $propertyInjection) { + $value = $propertyInjection->getValue(); + $valueStr = $value instanceof Definition ? (string) $value : var_export($value, true); + + $str .= sprintf(\PHP_EOL . ' $%s = %s', $propertyInjection->getPropertyName(), $valueStr); + } + + return $str; + } + + private function dumpMethods(string $className, ObjectDefinition $definition) : string + { + $str = ''; + + foreach ($definition->getMethodInjections() as $methodInjection) { + $parameters = $this->dumpMethodParameters($className, $methodInjection); + + $str .= sprintf(\PHP_EOL . ' %s(' . \PHP_EOL . ' %s' . \PHP_EOL . ' )', $methodInjection->getMethodName(), $parameters); + } + + return $str; + } + + private function dumpMethodParameters(string $className, MethodInjection $methodInjection) : string + { + $methodReflection = new \ReflectionMethod($className, $methodInjection->getMethodName()); + + $args = []; + + $definitionParameters = $methodInjection->getParameters(); + + foreach ($methodReflection->getParameters() as $index => $parameter) { + if (array_key_exists($index, $definitionParameters)) { + $value = $definitionParameters[$index]; + $valueStr = $value instanceof Definition ? (string) $value : var_export($value, true); + + $args[] = sprintf('$%s = %s', $parameter->getName(), $valueStr); + + continue; + } + + // If the parameter is optional and wasn't specified, we take its default value + if ($parameter->isOptional()) { + try { + $value = $parameter->getDefaultValue(); + + $args[] = sprintf( + '$%s = (default value) %s', + $parameter->getName(), + var_export($value, true) + ); + continue; + } catch (ReflectionException $e) { + // The default value can't be read through Reflection because it is a PHP internal class + } + } + + $args[] = sprintf('$%s = #UNDEFINED#', $parameter->getName()); + } + + return implode(\PHP_EOL . ' ', $args); + } +} diff --git a/vendor/php-di/php-di/src/Definition/EnvironmentVariableDefinition.php b/vendor/php-di/php-di/src/Definition/EnvironmentVariableDefinition.php new file mode 100644 index 0000000..b2a80c3 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/EnvironmentVariableDefinition.php @@ -0,0 +1,112 @@ + + */ +class EnvironmentVariableDefinition implements Definition +{ + /** + * Entry name. + * @var string + */ + private $name = ''; + + /** + * The name of the environment variable. + * @var string + */ + private $variableName; + + /** + * Whether or not the environment variable definition is optional. + * + * If true and the environment variable given by $variableName has not been + * defined, $defaultValue is used. + * + * @var bool + */ + private $isOptional; + + /** + * The default value to use if the environment variable is optional and not provided. + * @var mixed + */ + private $defaultValue; + + /** + * @param string $variableName The name of the environment variable + * @param bool $isOptional Whether or not the environment variable definition is optional + * @param mixed $defaultValue The default value to use if the environment variable is optional and not provided + */ + public function __construct(string $variableName, bool $isOptional = false, $defaultValue = null) + { + $this->variableName = $variableName; + $this->isOptional = $isOptional; + $this->defaultValue = $defaultValue; + } + + public function getName() : string + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + /** + * @return string The name of the environment variable + */ + public function getVariableName() : string + { + return $this->variableName; + } + + /** + * @return bool Whether or not the environment variable definition is optional + */ + public function isOptional() : bool + { + return $this->isOptional; + } + + /** + * @return mixed The default value to use if the environment variable is optional and not provided + */ + public function getDefaultValue() + { + return $this->defaultValue; + } + + public function replaceNestedDefinitions(callable $replacer) + { + $this->defaultValue = $replacer($this->defaultValue); + } + + public function __toString() + { + $str = ' variable = ' . $this->variableName . \PHP_EOL + . ' optional = ' . ($this->isOptional ? 'yes' : 'no'); + + if ($this->isOptional) { + if ($this->defaultValue instanceof Definition) { + $nestedDefinition = (string) $this->defaultValue; + $defaultValueStr = str_replace(\PHP_EOL, \PHP_EOL . ' ', $nestedDefinition); + } else { + $defaultValueStr = var_export($this->defaultValue, true); + } + + $str .= \PHP_EOL . ' default = ' . $defaultValueStr; + } + + return sprintf('Environment variable (' . \PHP_EOL . '%s' . \PHP_EOL . ')', $str); + } +} diff --git a/vendor/php-di/php-di/src/Definition/Exception/InvalidAnnotation.php b/vendor/php-di/php-di/src/Definition/Exception/InvalidAnnotation.php new file mode 100644 index 0000000..630c34a --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Exception/InvalidAnnotation.php @@ -0,0 +1,14 @@ + + */ +class InvalidAnnotation extends InvalidDefinition +{ +} diff --git a/vendor/php-di/php-di/src/Definition/Exception/InvalidDefinition.php b/vendor/php-di/php-di/src/Definition/Exception/InvalidDefinition.php new file mode 100644 index 0000000..f00d93e --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Exception/InvalidDefinition.php @@ -0,0 +1,25 @@ + + */ +class InvalidDefinition extends \Exception implements ContainerExceptionInterface +{ + public static function create(Definition $definition, string $message, \Exception $previous = null) : self + { + return new self(sprintf( + '%s' . \PHP_EOL . 'Full definition:' . \PHP_EOL . '%s', + $message, + (string) $definition + ), 0, $previous); + } +} diff --git a/vendor/php-di/php-di/src/Definition/ExtendsPreviousDefinition.php b/vendor/php-di/php-di/src/Definition/ExtendsPreviousDefinition.php new file mode 100644 index 0000000..0b26933 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/ExtendsPreviousDefinition.php @@ -0,0 +1,15 @@ + + */ +interface ExtendsPreviousDefinition extends Definition +{ + public function setExtendedDefinition(Definition $definition); +} diff --git a/vendor/php-di/php-di/src/Definition/FactoryDefinition.php b/vendor/php-di/php-di/src/Definition/FactoryDefinition.php new file mode 100644 index 0000000..ed0936f --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/FactoryDefinition.php @@ -0,0 +1,79 @@ + + */ +class FactoryDefinition implements Definition +{ + /** + * Entry name. + * @var string + */ + private $name; + + /** + * Callable that returns the value. + * @var callable + */ + private $factory; + + /** + * Factory parameters. + * @var mixed[] + */ + private $parameters = []; + + /** + * @param string $name Entry name + * @param callable $factory Callable that returns the value associated to the entry name. + * @param array $parameters Parameters to be passed to the callable + */ + public function __construct(string $name, $factory, array $parameters = []) + { + $this->name = $name; + $this->factory = $factory; + $this->parameters = $parameters; + } + + public function getName() : string + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + /** + * @return callable Callable that returns the value associated to the entry name. + */ + public function getCallable() + { + return $this->factory; + } + + /** + * @return array Array containing the parameters to be passed to the callable, indexed by name. + */ + public function getParameters() : array + { + return $this->parameters; + } + + public function replaceNestedDefinitions(callable $replacer) + { + $this->parameters = array_map($replacer, $this->parameters); + } + + public function __toString() + { + return 'Factory'; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Helper/AutowireDefinitionHelper.php b/vendor/php-di/php-di/src/Definition/Helper/AutowireDefinitionHelper.php new file mode 100644 index 0000000..8dfa4e2 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Helper/AutowireDefinitionHelper.php @@ -0,0 +1,72 @@ + + */ +class AutowireDefinitionHelper extends CreateDefinitionHelper +{ + const DEFINITION_CLASS = AutowireDefinition::class; + + /** + * Defines a value for a specific argument of the constructor. + * + * This method is usually used together with annotations or autowiring, when a parameter + * is not (or cannot be) type-hinted. Using this method instead of constructor() allows to + * avoid defining all the parameters (letting them being resolved using annotations or autowiring) + * and only define one. + * + * @param string|int $parameter Parameter name of position for which the value will be given. + * @param mixed $value Value to give to this parameter. + * + * @return $this + */ + public function constructorParameter($parameter, $value) + { + $this->constructor[$parameter] = $value; + + return $this; + } + + /** + * Defines a method to call and a value for a specific argument. + * + * This method is usually used together with annotations or autowiring, when a parameter + * is not (or cannot be) type-hinted. Using this method instead of method() allows to + * avoid defining all the parameters (letting them being resolved using annotations or + * autowiring) and only define one. + * + * If multiple calls to the method have been configured already (e.g. in a previous definition) + * then this method only overrides the parameter for the *first* call. + * + * @param string $method Name of the method to call. + * @param string|int $parameter Parameter name of position for which the value will be given. + * @param mixed $value Value to give to this parameter. + * + * @return $this + */ + public function methodParameter(string $method, $parameter, $value) + { + // Special case for the constructor + if ($method === '__construct') { + $this->constructor[$parameter] = $value; + + return $this; + } + + if (! isset($this->methods[$method])) { + $this->methods[$method] = [0 => []]; + } + + $this->methods[$method][0][$parameter] = $value; + + return $this; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Helper/CreateDefinitionHelper.php b/vendor/php-di/php-di/src/Definition/Helper/CreateDefinitionHelper.php new file mode 100644 index 0000000..aeae071 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Helper/CreateDefinitionHelper.php @@ -0,0 +1,202 @@ + + */ +class CreateDefinitionHelper implements DefinitionHelper +{ + const DEFINITION_CLASS = ObjectDefinition::class; + + /** + * @var string|null + */ + private $className; + + /** + * @var bool|null + */ + private $lazy; + + /** + * Array of constructor parameters. + * @var array + */ + protected $constructor = []; + + /** + * Array of properties and their value. + * @var array + */ + private $properties = []; + + /** + * Array of methods and their parameters. + * @var array + */ + protected $methods = []; + + /** + * Helper for defining an object. + * + * @param string|null $className Class name of the object. + * If null, the name of the entry (in the container) will be used as class name. + */ + public function __construct(string $className = null) + { + $this->className = $className; + } + + /** + * Define the entry as lazy. + * + * A lazy entry is created only when it is used, a proxy is injected instead. + * + * @return $this + */ + public function lazy() + { + $this->lazy = true; + + return $this; + } + + /** + * Defines the arguments to use to call the constructor. + * + * This method takes a variable number of arguments, example: + * ->constructor($param1, $param2, $param3) + * + * @param mixed... $parameters Parameters to use for calling the constructor of the class. + * + * @return $this + */ + public function constructor(...$parameters) + { + $this->constructor = $parameters; + + return $this; + } + + /** + * Defines a value to inject in a property of the object. + * + * @param string $property Entry in which to inject the value. + * @param mixed $value Value to inject in the property. + * + * @return $this + */ + public function property(string $property, $value) + { + $this->properties[$property] = $value; + + return $this; + } + + /** + * Defines a method to call and the arguments to use. + * + * This method takes a variable number of arguments after the method name, example: + * + * ->method('myMethod', $param1, $param2) + * + * Can be used multiple times to declare multiple calls. + * + * @param string $method Name of the method to call. + * @param mixed... $parameters Parameters to use for calling the method. + * + * @return $this + */ + public function method(string $method, ...$parameters) + { + if (! isset($this->methods[$method])) { + $this->methods[$method] = []; + } + + $this->methods[$method][] = $parameters; + + return $this; + } + + /** + * @return ObjectDefinition + */ + public function getDefinition(string $entryName) : Definition + { + $class = $this::DEFINITION_CLASS; + /** @var ObjectDefinition $definition */ + $definition = new $class($entryName, $this->className); + + if ($this->lazy !== null) { + $definition->setLazy($this->lazy); + } + + if (! empty($this->constructor)) { + $parameters = $this->fixParameters($definition, '__construct', $this->constructor); + $constructorInjection = MethodInjection::constructor($parameters); + $definition->setConstructorInjection($constructorInjection); + } + + if (! empty($this->properties)) { + foreach ($this->properties as $property => $value) { + $definition->addPropertyInjection( + new PropertyInjection($property, $value) + ); + } + } + + if (! empty($this->methods)) { + foreach ($this->methods as $method => $calls) { + foreach ($calls as $parameters) { + $parameters = $this->fixParameters($definition, $method, $parameters); + $methodInjection = new MethodInjection($method, $parameters); + $definition->addMethodInjection($methodInjection); + } + } + } + + return $definition; + } + + /** + * Fixes parameters indexed by the parameter name -> reindex by position. + * + * This is necessary so that merging definitions between sources is possible. + * + * @throws InvalidDefinition + */ + private function fixParameters(ObjectDefinition $definition, string $method, array $parameters) : array + { + $fixedParameters = []; + + foreach ($parameters as $index => $parameter) { + // Parameter indexed by the parameter name, we reindex it with its position + if (is_string($index)) { + $callable = [$definition->getClassName(), $method]; + + try { + $reflectionParameter = new \ReflectionParameter($callable, $index); + } catch (\ReflectionException $e) { + throw InvalidDefinition::create($definition, sprintf("Parameter with name '%s' could not be found. %s.", $index, $e->getMessage())); + } + + $index = $reflectionParameter->getPosition(); + } + + $fixedParameters[$index] = $parameter; + } + + return $fixedParameters; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Helper/DefinitionHelper.php b/vendor/php-di/php-di/src/Definition/Helper/DefinitionHelper.php new file mode 100644 index 0000000..327167e --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Helper/DefinitionHelper.php @@ -0,0 +1,20 @@ + + */ +interface DefinitionHelper +{ + /** + * @param string $entryName Container entry name + */ + public function getDefinition(string $entryName) : Definition; +} diff --git a/vendor/php-di/php-di/src/Definition/Helper/FactoryDefinitionHelper.php b/vendor/php-di/php-di/src/Definition/Helper/FactoryDefinitionHelper.php new file mode 100644 index 0000000..0a22319 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Helper/FactoryDefinitionHelper.php @@ -0,0 +1,75 @@ + + */ +class FactoryDefinitionHelper implements DefinitionHelper +{ + /** + * @var callable + */ + private $factory; + + /** + * @var bool + */ + private $decorate; + + /** + * @var array + */ + private $parameters = []; + + /** + * @param callable $factory + * @param bool $decorate Is the factory decorating a previous definition? + */ + public function __construct($factory, bool $decorate = false) + { + $this->factory = $factory; + $this->decorate = $decorate; + } + + /** + * @param string $entryName Container entry name + * @return FactoryDefinition + */ + public function getDefinition(string $entryName) : Definition + { + if ($this->decorate) { + return new DecoratorDefinition($entryName, $this->factory, $this->parameters); + } + + return new FactoryDefinition($entryName, $this->factory, $this->parameters); + } + + /** + * Defines arguments to pass to the factory. + * + * Because factory methods do not yet support annotations or autowiring, this method + * should be used to define all parameters except the ContainerInterface and RequestedEntry. + * + * Multiple calls can be made to the method to override individual values. + * + * @param string $parameter Name or index of the parameter for which the value will be given. + * @param mixed $value Value to give to this parameter. + * + * @return $this + */ + public function parameter(string $parameter, $value) + { + $this->parameters[$parameter] = $value; + + return $this; + } +} diff --git a/vendor/php-di/php-di/src/Definition/InstanceDefinition.php b/vendor/php-di/php-di/src/Definition/InstanceDefinition.php new file mode 100644 index 0000000..4c281c6 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/InstanceDefinition.php @@ -0,0 +1,69 @@ + + */ +class InstanceDefinition implements Definition +{ + /** + * Instance on which to inject dependencies. + * + * @var object + */ + private $instance; + + /** + * @var ObjectDefinition + */ + private $objectDefinition; + + /** + * @param object $instance + */ + public function __construct($instance, ObjectDefinition $objectDefinition) + { + $this->instance = $instance; + $this->objectDefinition = $objectDefinition; + } + + public function getName() : string + { + // Name are superfluous for instance definitions + return ''; + } + + public function setName(string $name) + { + // Name are superfluous for instance definitions + } + + /** + * @return object + */ + public function getInstance() + { + return $this->instance; + } + + public function getObjectDefinition() : ObjectDefinition + { + return $this->objectDefinition; + } + + public function replaceNestedDefinitions(callable $replacer) + { + $this->objectDefinition->replaceNestedDefinitions($replacer); + } + + public function __toString() + { + return 'Instance'; + } +} diff --git a/vendor/php-di/php-di/src/Definition/ObjectDefinition.php b/vendor/php-di/php-di/src/Definition/ObjectDefinition.php new file mode 100644 index 0000000..8d8d5b6 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/ObjectDefinition.php @@ -0,0 +1,266 @@ + + */ +class ObjectDefinition implements Definition +{ + /** + * Entry name (most of the time, same as $classname). + * @var string + */ + private $name; + + /** + * Class name (if null, then the class name is $name). + * @var string|null + */ + protected $className; + + /** + * Constructor parameter injection. + * @var MethodInjection|null + */ + protected $constructorInjection; + + /** + * Property injections. + * @var PropertyInjection[] + */ + protected $propertyInjections = []; + + /** + * Method calls. + * @var MethodInjection[][] + */ + protected $methodInjections = []; + + /** + * @var bool|null + */ + protected $lazy; + + /** + * Store if the class exists. Storing it (in cache) avoids recomputing this. + * + * @var bool + */ + private $classExists; + + /** + * Store if the class is instantiable. Storing it (in cache) avoids recomputing this. + * + * @var bool + */ + private $isInstantiable; + + /** + * @param string $name Entry name + */ + public function __construct(string $name, string $className = null) + { + $this->name = $name; + $this->setClassName($className); + } + + public function getName() : string + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + public function setClassName(string $className = null) + { + $this->className = $className; + + $this->updateCache(); + } + + public function getClassName() : string + { + if ($this->className !== null) { + return $this->className; + } + + return $this->name; + } + + /** + * @return MethodInjection|null + */ + public function getConstructorInjection() + { + return $this->constructorInjection; + } + + public function setConstructorInjection(MethodInjection $constructorInjection) + { + $this->constructorInjection = $constructorInjection; + } + + public function completeConstructorInjection(MethodInjection $injection) + { + if ($this->constructorInjection !== null) { + // Merge + $this->constructorInjection->merge($injection); + } else { + // Set + $this->constructorInjection = $injection; + } + } + + /** + * @return PropertyInjection[] Property injections + */ + public function getPropertyInjections() : array + { + return $this->propertyInjections; + } + + public function addPropertyInjection(PropertyInjection $propertyInjection) + { + $className = $propertyInjection->getClassName(); + if ($className) { + // Index with the class name to avoid collisions between parent and + // child private properties with the same name + $key = $className . '::' . $propertyInjection->getPropertyName(); + } else { + $key = $propertyInjection->getPropertyName(); + } + + $this->propertyInjections[$key] = $propertyInjection; + } + + /** + * @return MethodInjection[] Method injections + */ + public function getMethodInjections() : array + { + // Return array leafs + $injections = []; + array_walk_recursive($this->methodInjections, function ($injection) use (&$injections) { + $injections[] = $injection; + }); + + return $injections; + } + + public function addMethodInjection(MethodInjection $methodInjection) + { + $method = $methodInjection->getMethodName(); + if (! isset($this->methodInjections[$method])) { + $this->methodInjections[$method] = []; + } + $this->methodInjections[$method][] = $methodInjection; + } + + public function completeFirstMethodInjection(MethodInjection $injection) + { + $method = $injection->getMethodName(); + + if (isset($this->methodInjections[$method][0])) { + // Merge + $this->methodInjections[$method][0]->merge($injection); + } else { + // Set + $this->addMethodInjection($injection); + } + } + + public function setLazy(bool $lazy = null) + { + $this->lazy = $lazy; + } + + public function isLazy() : bool + { + if ($this->lazy !== null) { + return $this->lazy; + } + // Default value + return false; + } + + public function classExists() : bool + { + return $this->classExists; + } + + public function isInstantiable() : bool + { + return $this->isInstantiable; + } + + public function replaceNestedDefinitions(callable $replacer) + { + array_walk($this->propertyInjections, function (PropertyInjection $propertyInjection) use ($replacer) { + $propertyInjection->replaceNestedDefinition($replacer); + }); + + if ($this->constructorInjection) { + $this->constructorInjection->replaceNestedDefinitions($replacer); + } + + array_walk($this->methodInjections, function ($injectionArray) use ($replacer) { + array_walk($injectionArray, function (MethodInjection $methodInjection) use ($replacer) { + $methodInjection->replaceNestedDefinitions($replacer); + }); + }); + } + + /** + * Replaces all the wildcards in the string with the given replacements. + * + * @param string[] $replacements + */ + public function replaceWildcards(array $replacements) + { + $className = $this->getClassName(); + + foreach ($replacements as $replacement) { + $pos = strpos($className, DefinitionArray::WILDCARD); + if ($pos !== false) { + $className = substr_replace($className, $replacement, $pos, 1); + } + } + + $this->setClassName($className); + } + + public function __toString() + { + return (new ObjectDefinitionDumper)->dump($this); + } + + private function updateCache() + { + $className = $this->getClassName(); + + $this->classExists = class_exists($className) || interface_exists($className); + + if (! $this->classExists) { + $this->isInstantiable = false; + + return; + } + + $class = new ReflectionClass($className); + $this->isInstantiable = $class->isInstantiable(); + } +} diff --git a/vendor/php-di/php-di/src/Definition/ObjectDefinition/MethodInjection.php b/vendor/php-di/php-di/src/Definition/ObjectDefinition/MethodInjection.php new file mode 100644 index 0000000..5fb67ce --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/ObjectDefinition/MethodInjection.php @@ -0,0 +1,86 @@ + + */ +class MethodInjection implements Definition +{ + /** + * @var string + */ + private $methodName; + + /** + * @var mixed[] + */ + private $parameters = []; + + public function __construct(string $methodName, array $parameters = []) + { + $this->methodName = $methodName; + $this->parameters = $parameters; + } + + public static function constructor(array $parameters = []) : self + { + return new self('__construct', $parameters); + } + + public function getMethodName() : string + { + return $this->methodName; + } + + /** + * @return mixed[] + */ + public function getParameters() : array + { + return $this->parameters; + } + + /** + * Replace the parameters of the definition by a new array of parameters. + */ + public function replaceParameters(array $parameters) + { + $this->parameters = $parameters; + } + + public function merge(self $definition) + { + // In case of conflicts, the current definition prevails. + $this->parameters = $this->parameters + $definition->parameters; + } + + public function getName() : string + { + return ''; + } + + public function setName(string $name) + { + // The name does not matter for method injections + } + + public function replaceNestedDefinitions(callable $replacer) + { + $this->parameters = array_map($replacer, $this->parameters); + } + + /** + * {@inheritdoc} + */ + public function __toString() + { + return sprintf('method(%s)', $this->methodName); + } +} diff --git a/vendor/php-di/php-di/src/Definition/ObjectDefinition/PropertyInjection.php b/vendor/php-di/php-di/src/Definition/ObjectDefinition/PropertyInjection.php new file mode 100644 index 0000000..307ba64 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/ObjectDefinition/PropertyInjection.php @@ -0,0 +1,70 @@ + + */ +class PropertyInjection +{ + /** + * Property name. + * @var string + */ + private $propertyName; + + /** + * Value that should be injected in the property. + * @var mixed + */ + private $value; + + /** + * Use for injecting in properties of parent classes: the class name + * must be the name of the parent class because private properties + * can be attached to the parent classes, not the one we are resolving. + * @var string|null + */ + private $className; + + /** + * @param string $propertyName Property name + * @param mixed $value Value that should be injected in the property + */ + public function __construct(string $propertyName, $value, string $className = null) + { + $this->propertyName = $propertyName; + $this->value = $value; + $this->className = $className; + } + + public function getPropertyName() : string + { + return $this->propertyName; + } + + /** + * @return mixed Value that should be injected in the property + */ + public function getValue() + { + return $this->value; + } + + /** + * @return string|null + */ + public function getClassName() + { + return $this->className; + } + + public function replaceNestedDefinition(callable $replacer) + { + $this->value = $replacer($this->value); + } +} diff --git a/vendor/php-di/php-di/src/Definition/Reference.php b/vendor/php-di/php-di/src/Definition/Reference.php new file mode 100644 index 0000000..5b4597a --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Reference.php @@ -0,0 +1,73 @@ + + */ +class Reference implements Definition, SelfResolvingDefinition +{ + /** + * Entry name. + * @var string + */ + private $name = ''; + + /** + * Name of the target entry. + * @var string + */ + private $targetEntryName; + + /** + * @param string $targetEntryName Name of the target entry + */ + public function __construct(string $targetEntryName) + { + $this->targetEntryName = $targetEntryName; + } + + public function getName() : string + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + public function getTargetEntryName() : string + { + return $this->targetEntryName; + } + + public function resolve(ContainerInterface $container) + { + return $container->get($this->getTargetEntryName()); + } + + public function isResolvable(ContainerInterface $container) : bool + { + return $container->has($this->getTargetEntryName()); + } + + public function replaceNestedDefinitions(callable $replacer) + { + // no nested definitions + } + + public function __toString() + { + return sprintf( + 'get(%s)', + $this->targetEntryName + ); + } +} diff --git a/vendor/php-di/php-di/src/Definition/Resolver/ArrayResolver.php b/vendor/php-di/php-di/src/Definition/Resolver/ArrayResolver.php new file mode 100644 index 0000000..30a715b --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Resolver/ArrayResolver.php @@ -0,0 +1,74 @@ + + */ +class ArrayResolver implements DefinitionResolver +{ + /** + * @var DefinitionResolver + */ + private $definitionResolver; + + /** + * @param DefinitionResolver $definitionResolver Used to resolve nested definitions. + */ + public function __construct(DefinitionResolver $definitionResolver) + { + $this->definitionResolver = $definitionResolver; + } + + /** + * Resolve an array definition to a value. + * + * An array definition can contain simple values or references to other entries. + * + * @param ArrayDefinition $definition + */ + public function resolve(Definition $definition, array $parameters = []) : array + { + $values = $definition->getValues(); + + // Resolve nested definitions + array_walk_recursive($values, function (& $value, $key) use ($definition) { + if ($value instanceof Definition) { + $value = $this->resolveDefinition($value, $definition, $key); + } + }); + + return $values; + } + + public function isResolvable(Definition $definition, array $parameters = []) : bool + { + return true; + } + + private function resolveDefinition(Definition $value, ArrayDefinition $definition, $key) + { + try { + return $this->definitionResolver->resolve($value); + } catch (DependencyException $e) { + throw $e; + } catch (Exception $e) { + throw new DependencyException(sprintf( + 'Error while resolving %s[%s]. %s', + $definition->getName(), + $key, + $e->getMessage() + ), 0, $e); + } + } +} diff --git a/vendor/php-di/php-di/src/Definition/Resolver/DecoratorResolver.php b/vendor/php-di/php-di/src/Definition/Resolver/DecoratorResolver.php new file mode 100644 index 0000000..03585ea --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Resolver/DecoratorResolver.php @@ -0,0 +1,82 @@ + + */ +class DecoratorResolver implements DefinitionResolver +{ + /** + * @var ContainerInterface + */ + private $container; + + /** + * @var DefinitionResolver + */ + private $definitionResolver; + + /** + * The resolver needs a container. This container will be passed to the factory as a parameter + * so that the factory can access other entries of the container. + * + * @param DefinitionResolver $definitionResolver Used to resolve nested definitions. + */ + public function __construct(ContainerInterface $container, DefinitionResolver $definitionResolver) + { + $this->container = $container; + $this->definitionResolver = $definitionResolver; + } + + /** + * Resolve a decorator definition to a value. + * + * This will call the callable of the definition and pass it the decorated entry. + * + * @param DecoratorDefinition $definition + */ + public function resolve(Definition $definition, array $parameters = []) + { + $callable = $definition->getCallable(); + + if (! is_callable($callable)) { + throw new InvalidDefinition(sprintf( + 'The decorator "%s" is not callable', + $definition->getName() + )); + } + + $decoratedDefinition = $definition->getDecoratedDefinition(); + + if (! $decoratedDefinition instanceof Definition) { + if (! $definition->getName()) { + throw new InvalidDefinition('Decorators cannot be nested in another definition'); + } + + throw new InvalidDefinition(sprintf( + 'Entry "%s" decorates nothing: no previous definition with the same name was found', + $definition->getName() + )); + } + + $decorated = $this->definitionResolver->resolve($decoratedDefinition, $parameters); + + return call_user_func($callable, $decorated, $this->container); + } + + public function isResolvable(Definition $definition, array $parameters = []) : bool + { + return true; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Resolver/DefinitionResolver.php b/vendor/php-di/php-di/src/Definition/Resolver/DefinitionResolver.php new file mode 100644 index 0000000..56b5383 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Resolver/DefinitionResolver.php @@ -0,0 +1,37 @@ + + */ +interface DefinitionResolver +{ + /** + * Resolve a definition to a value. + * + * @param Definition $definition Object that defines how the value should be obtained. + * @param array $parameters Optional parameters to use to build the entry. + * + * @throws InvalidDefinition If the definition cannot be resolved. + * + * @return mixed Value obtained from the definition. + */ + public function resolve(Definition $definition, array $parameters = []); + + /** + * Check if a definition can be resolved. + * + * @param Definition $definition Object that defines how the value should be obtained. + * @param array $parameters Optional parameters to use to build the entry. + */ + public function isResolvable(Definition $definition, array $parameters = []) : bool; +} diff --git a/vendor/php-di/php-di/src/Definition/Resolver/EnvironmentVariableResolver.php b/vendor/php-di/php-di/src/Definition/Resolver/EnvironmentVariableResolver.php new file mode 100644 index 0000000..77f5b92 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Resolver/EnvironmentVariableResolver.php @@ -0,0 +1,79 @@ + + */ +class EnvironmentVariableResolver implements DefinitionResolver +{ + /** + * @var DefinitionResolver + */ + private $definitionResolver; + + /** + * @var callable + */ + private $variableReader; + + public function __construct(DefinitionResolver $definitionResolver, $variableReader = null) + { + $this->definitionResolver = $definitionResolver; + $this->variableReader = $variableReader ?? [$this, 'getEnvVariable']; + } + + /** + * Resolve an environment variable definition to a value. + * + * @param EnvironmentVariableDefinition $definition + */ + public function resolve(Definition $definition, array $parameters = []) + { + $value = call_user_func($this->variableReader, $definition->getVariableName()); + + if (false !== $value) { + return $value; + } + + if (!$definition->isOptional()) { + throw new InvalidDefinition(sprintf( + "The environment variable '%s' has not been defined", + $definition->getVariableName() + )); + } + + $value = $definition->getDefaultValue(); + + // Nested definition + if ($value instanceof Definition) { + return $this->definitionResolver->resolve($value); + } + + return $value; + } + + public function isResolvable(Definition $definition, array $parameters = []) : bool + { + return true; + } + + protected function getEnvVariable(string $variableName) + { + if (isset($_ENV[$variableName])) { + return $_ENV[$variableName]; + } elseif (isset($_SERVER[$variableName])) { + return $_SERVER[$variableName]; + } + + return getenv($variableName); + } +} diff --git a/vendor/php-di/php-di/src/Definition/Resolver/FactoryResolver.php b/vendor/php-di/php-di/src/Definition/Resolver/FactoryResolver.php new file mode 100644 index 0000000..c36a1aa --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Resolver/FactoryResolver.php @@ -0,0 +1,123 @@ + + */ +class FactoryResolver implements DefinitionResolver +{ + /** + * @var ContainerInterface + */ + private $container; + + /** + * @var Invoker|null + */ + private $invoker; + + /** + * @var DefinitionResolver + */ + private $resolver; + + /** + * The resolver needs a container. This container will be passed to the factory as a parameter + * so that the factory can access other entries of the container. + */ + public function __construct(ContainerInterface $container, DefinitionResolver $resolver) + { + $this->container = $container; + $this->resolver = $resolver; + } + + /** + * Resolve a factory definition to a value. + * + * This will call the callable of the definition. + * + * @param FactoryDefinition $definition + */ + public function resolve(Definition $definition, array $parameters = []) + { + if (! $this->invoker) { + $parameterResolver = new ResolverChain([ + new AssociativeArrayResolver, + new FactoryParameterResolver($this->container), + new NumericArrayResolver, + new DefaultValueResolver, + ]); + + $this->invoker = new Invoker($parameterResolver, $this->container); + } + + $callable = $definition->getCallable(); + + try { + $providedParams = [$this->container, $definition]; + $extraParams = $this->resolveExtraParams($definition->getParameters()); + $providedParams = array_merge($providedParams, $extraParams, $parameters); + + return $this->invoker->call($callable, $providedParams); + } catch (NotCallableException $e) { + // Custom error message to help debugging + if (is_string($callable) && class_exists($callable) && method_exists($callable, '__invoke')) { + throw new InvalidDefinition(sprintf( + 'Entry "%s" cannot be resolved: factory %s. Invokable classes cannot be automatically resolved if autowiring is disabled on the container, you need to enable autowiring or define the entry manually.', + $definition->getName(), + $e->getMessage() + )); + } + + throw new InvalidDefinition(sprintf( + 'Entry "%s" cannot be resolved: factory %s', + $definition->getName(), + $e->getMessage() + )); + } catch (NotEnoughParametersException $e) { + throw new InvalidDefinition(sprintf( + 'Entry "%s" cannot be resolved: %s', + $definition->getName(), + $e->getMessage() + )); + } + } + + public function isResolvable(Definition $definition, array $parameters = []) : bool + { + return true; + } + + private function resolveExtraParams(array $params) : array + { + $resolved = []; + foreach ($params as $key => $value) { + // Nested definitions + if ($value instanceof Definition) { + $value = $this->resolver->resolve($value); + } + $resolved[$key] = $value; + } + + return $resolved; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Resolver/InstanceInjector.php b/vendor/php-di/php-di/src/Definition/Resolver/InstanceInjector.php new file mode 100644 index 0000000..60ea24a --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Resolver/InstanceInjector.php @@ -0,0 +1,46 @@ + + */ +class InstanceInjector extends ObjectCreator +{ + /** + * Injects dependencies on an existing instance. + * + * @param InstanceDefinition $definition + */ + public function resolve(Definition $definition, array $parameters = []) + { + try { + $this->injectMethodsAndProperties($definition->getInstance(), $definition->getObjectDefinition()); + } catch (NotFoundExceptionInterface $e) { + $message = sprintf( + 'Error while injecting dependencies into %s: %s', + get_class($definition->getInstance()), + $e->getMessage() + ); + + throw new DependencyException($message, 0, $e); + } + + return $definition; + } + + public function isResolvable(Definition $definition, array $parameters = []) : bool + { + return true; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Resolver/ObjectCreator.php b/vendor/php-di/php-di/src/Definition/Resolver/ObjectCreator.php new file mode 100644 index 0000000..3f1f1e6 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Resolver/ObjectCreator.php @@ -0,0 +1,222 @@ + + */ +class ObjectCreator implements DefinitionResolver +{ + /** + * @var ProxyFactory + */ + private $proxyFactory; + + /** + * @var ParameterResolver + */ + private $parameterResolver; + + /** + * @var DefinitionResolver + */ + private $definitionResolver; + + /** + * @param DefinitionResolver $definitionResolver Used to resolve nested definitions. + * @param ProxyFactory $proxyFactory Used to create proxies for lazy injections. + */ + public function __construct( + DefinitionResolver $definitionResolver, + ProxyFactory $proxyFactory + ) { + $this->definitionResolver = $definitionResolver; + $this->proxyFactory = $proxyFactory; + $this->parameterResolver = new ParameterResolver($definitionResolver); + } + + /** + * Resolve a class definition to a value. + * + * This will create a new instance of the class using the injections points defined. + * + * @param ObjectDefinition $definition + * + * @return object|null + */ + public function resolve(Definition $definition, array $parameters = []) + { + // Lazy? + if ($definition->isLazy()) { + return $this->createProxy($definition, $parameters); + } + + return $this->createInstance($definition, $parameters); + } + + /** + * The definition is not resolvable if the class is not instantiable (interface or abstract) + * or if the class doesn't exist. + * + * @param ObjectDefinition $definition + */ + public function isResolvable(Definition $definition, array $parameters = []) : bool + { + return $definition->isInstantiable(); + } + + /** + * Returns a proxy instance. + */ + private function createProxy(ObjectDefinition $definition, array $parameters) : LazyLoadingInterface + { + /** @noinspection PhpUnusedParameterInspection */ + $proxy = $this->proxyFactory->createProxy( + $definition->getClassName(), + function (& $wrappedObject, $proxy, $method, $params, & $initializer) use ($definition, $parameters) { + $wrappedObject = $this->createInstance($definition, $parameters); + $initializer = null; // turning off further lazy initialization + + return true; + } + ); + + return $proxy; + } + + /** + * Creates an instance of the class and injects dependencies.. + * + * @param array $parameters Optional parameters to use to create the instance. + * + * @throws InvalidDefinition + * @throws DependencyException + * @return object + */ + private function createInstance(ObjectDefinition $definition, array $parameters) + { + // Check that the class is instantiable + if (! $definition->isInstantiable()) { + // Check that the class exists + if (! $definition->classExists()) { + throw InvalidDefinition::create($definition, sprintf( + 'Entry "%s" cannot be resolved: the class doesn\'t exist', + $definition->getName() + )); + } + + throw InvalidDefinition::create($definition, sprintf( + 'Entry "%s" cannot be resolved: the class is not instantiable', + $definition->getName() + )); + } + + $classname = $definition->getClassName(); + $classReflection = new ReflectionClass($classname); + + $constructorInjection = $definition->getConstructorInjection(); + + try { + $args = $this->parameterResolver->resolveParameters( + $constructorInjection, + $classReflection->getConstructor(), + $parameters + ); + + $object = new $classname(...$args); + + $this->injectMethodsAndProperties($object, $definition); + } catch (NotFoundExceptionInterface $e) { + throw new DependencyException(sprintf( + 'Error while injecting dependencies into %s: %s', + $classReflection->getName(), + $e->getMessage() + ), 0, $e); + } catch (InvalidDefinition $e) { + throw InvalidDefinition::create($definition, sprintf( + 'Entry "%s" cannot be resolved: %s', + $definition->getName(), + $e->getMessage() + )); + } + + return $object; + } + + protected function injectMethodsAndProperties($object, ObjectDefinition $objectDefinition) + { + // Property injections + foreach ($objectDefinition->getPropertyInjections() as $propertyInjection) { + $this->injectProperty($object, $propertyInjection); + } + + // Method injections + foreach ($objectDefinition->getMethodInjections() as $methodInjection) { + $methodReflection = new \ReflectionMethod($object, $methodInjection->getMethodName()); + $args = $this->parameterResolver->resolveParameters($methodInjection, $methodReflection); + + $methodReflection->invokeArgs($object, $args); + } + } + + /** + * Inject dependencies into properties. + * + * @param object $object Object to inject dependencies into + * @param PropertyInjection $propertyInjection Property injection definition + * + * @throws DependencyException + * @throws InvalidDefinition + */ + private function injectProperty($object, PropertyInjection $propertyInjection) + { + $propertyName = $propertyInjection->getPropertyName(); + + $value = $propertyInjection->getValue(); + + if ($value instanceof Definition) { + try { + $value = $this->definitionResolver->resolve($value); + } catch (DependencyException $e) { + throw $e; + } catch (Exception $e) { + throw new DependencyException(sprintf( + 'Error while injecting in %s::%s. %s', + get_class($object), + $propertyName, + $e->getMessage() + ), 0, $e); + } + } + + self::setPrivatePropertyValue($propertyInjection->getClassName(), $object, $propertyName, $value); + } + + public static function setPrivatePropertyValue(string $className = null, $object, string $propertyName, $propertyValue) + { + $className = $className ?: get_class($object); + + $property = new ReflectionProperty($className, $propertyName); + if (! $property->isPublic()) { + $property->setAccessible(true); + } + $property->setValue($object, $propertyValue); + } +} diff --git a/vendor/php-di/php-di/src/Definition/Resolver/ParameterResolver.php b/vendor/php-di/php-di/src/Definition/Resolver/ParameterResolver.php new file mode 100644 index 0000000..c9a4640 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Resolver/ParameterResolver.php @@ -0,0 +1,112 @@ + + */ +class ParameterResolver +{ + /** + * @var DefinitionResolver + */ + private $definitionResolver; + + /** + * @param DefinitionResolver $definitionResolver Will be used to resolve nested definitions. + */ + public function __construct(DefinitionResolver $definitionResolver) + { + $this->definitionResolver = $definitionResolver; + } + + /** + * @throws InvalidDefinition A parameter has no value defined or guessable. + * @return array Parameters to use to call the function. + */ + public function resolveParameters( + MethodInjection $definition = null, + ReflectionMethod $method = null, + array $parameters = [] + ) { + $args = []; + + if (! $method) { + return $args; + } + + $definitionParameters = $definition ? $definition->getParameters() : []; + + foreach ($method->getParameters() as $index => $parameter) { + if (array_key_exists($parameter->getName(), $parameters)) { + // Look in the $parameters array + $value = &$parameters[$parameter->getName()]; + } elseif (array_key_exists($index, $definitionParameters)) { + // Look in the definition + $value = &$definitionParameters[$index]; + } else { + // If the parameter is optional and wasn't specified, we take its default value + if ($parameter->isDefaultValueAvailable() || $parameter->isOptional()) { + $args[] = $this->getParameterDefaultValue($parameter, $method); + continue; + } + + throw new InvalidDefinition(sprintf( + 'Parameter $%s of %s has no value defined or guessable', + $parameter->getName(), + $this->getFunctionName($method) + )); + } + + // Nested definitions + if ($value instanceof Definition) { + // If the container cannot produce the entry, we can use the default parameter value + if ($parameter->isOptional() && ! $this->definitionResolver->isResolvable($value)) { + $value = $this->getParameterDefaultValue($parameter, $method); + } else { + $value = $this->definitionResolver->resolve($value); + } + } + + $args[] = &$value; + } + + return $args; + } + + /** + * Returns the default value of a function parameter. + * + * @throws InvalidDefinition Can't get default values from PHP internal classes and functions + * @return mixed + */ + private function getParameterDefaultValue(ReflectionParameter $parameter, ReflectionMethod $function) + { + try { + return $parameter->getDefaultValue(); + } catch (\ReflectionException $e) { + throw new InvalidDefinition(sprintf( + 'The parameter "%s" of %s has no type defined or guessable. It has a default value, ' + . 'but the default value can\'t be read through Reflection because it is a PHP internal class.', + $parameter->getName(), + $this->getFunctionName($function) + )); + } + } + + private function getFunctionName(ReflectionMethod $method) : string + { + return $method->getName() . '()'; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Resolver/ResolverDispatcher.php b/vendor/php-di/php-di/src/Definition/Resolver/ResolverDispatcher.php new file mode 100644 index 0000000..7c0edcc --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Resolver/ResolverDispatcher.php @@ -0,0 +1,134 @@ + + */ +class ResolverDispatcher implements DefinitionResolver +{ + /** + * @var ContainerInterface + */ + private $container; + + /** + * @var ProxyFactory + */ + private $proxyFactory; + + private $arrayResolver; + private $factoryResolver; + private $decoratorResolver; + private $objectResolver; + private $instanceResolver; + private $envVariableResolver; + + public function __construct(ContainerInterface $container, ProxyFactory $proxyFactory) + { + $this->container = $container; + $this->proxyFactory = $proxyFactory; + } + + /** + * Resolve a definition to a value. + * + * @param Definition $definition Object that defines how the value should be obtained. + * @param array $parameters Optional parameters to use to build the entry. + * + * @throws InvalidDefinition If the definition cannot be resolved. + * + * @return mixed Value obtained from the definition. + */ + public function resolve(Definition $definition, array $parameters = []) + { + // Special case, tested early for speed + if ($definition instanceof SelfResolvingDefinition) { + return $definition->resolve($this->container); + } + + $definitionResolver = $this->getDefinitionResolver($definition); + + return $definitionResolver->resolve($definition, $parameters); + } + + public function isResolvable(Definition $definition, array $parameters = []) : bool + { + // Special case, tested early for speed + if ($definition instanceof SelfResolvingDefinition) { + return $definition->isResolvable($this->container); + } + + $definitionResolver = $this->getDefinitionResolver($definition); + + return $definitionResolver->isResolvable($definition, $parameters); + } + + /** + * Returns a resolver capable of handling the given definition. + * + * @throws \RuntimeException No definition resolver was found for this type of definition. + */ + private function getDefinitionResolver(Definition $definition) : DefinitionResolver + { + switch (true) { + case $definition instanceof ObjectDefinition: + if (! $this->objectResolver) { + $this->objectResolver = new ObjectCreator($this, $this->proxyFactory); + } + + return $this->objectResolver; + case $definition instanceof DecoratorDefinition: + if (! $this->decoratorResolver) { + $this->decoratorResolver = new DecoratorResolver($this->container, $this); + } + + return $this->decoratorResolver; + case $definition instanceof FactoryDefinition: + if (! $this->factoryResolver) { + $this->factoryResolver = new FactoryResolver($this->container, $this); + } + + return $this->factoryResolver; + case $definition instanceof ArrayDefinition: + if (! $this->arrayResolver) { + $this->arrayResolver = new ArrayResolver($this); + } + + return $this->arrayResolver; + case $definition instanceof EnvironmentVariableDefinition: + if (! $this->envVariableResolver) { + $this->envVariableResolver = new EnvironmentVariableResolver($this); + } + + return $this->envVariableResolver; + case $definition instanceof InstanceDefinition: + if (! $this->instanceResolver) { + $this->instanceResolver = new InstanceInjector($this, $this->proxyFactory); + } + + return $this->instanceResolver; + default: + throw new \RuntimeException('No definition resolver was configured for definition of type ' . get_class($definition)); + } + } +} diff --git a/vendor/php-di/php-di/src/Definition/SelfResolvingDefinition.php b/vendor/php-di/php-di/src/Definition/SelfResolvingDefinition.php new file mode 100644 index 0000000..7452403 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/SelfResolvingDefinition.php @@ -0,0 +1,27 @@ + + */ +interface SelfResolvingDefinition +{ + /** + * Resolve the definition and return the resulting value. + * + * @return mixed + */ + public function resolve(ContainerInterface $container); + + /** + * Check if a definition can be resolved. + */ + public function isResolvable(ContainerInterface $container) : bool; +} diff --git a/vendor/php-di/php-di/src/Definition/Source/AnnotationBasedAutowiring.php b/vendor/php-di/php-di/src/Definition/Source/AnnotationBasedAutowiring.php new file mode 100644 index 0000000..ee3273a --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/AnnotationBasedAutowiring.php @@ -0,0 +1,297 @@ + + */ +class AnnotationBasedAutowiring implements DefinitionSource, Autowiring +{ + /** + * @var Reader + */ + private $annotationReader; + + /** + * @var PhpDocReader + */ + private $phpDocReader; + + /** + * @var bool + */ + private $ignorePhpDocErrors; + + public function __construct($ignorePhpDocErrors = false) + { + $this->ignorePhpDocErrors = (bool) $ignorePhpDocErrors; + } + + public function autowire(string $name, ObjectDefinition $definition = null) + { + $className = $definition ? $definition->getClassName() : $name; + + if (!class_exists($className) && !interface_exists($className)) { + return $definition; + } + + $definition = $definition ?: new ObjectDefinition($name); + + $class = new ReflectionClass($className); + + $this->readInjectableAnnotation($class, $definition); + + // Browse the class properties looking for annotated properties + $this->readProperties($class, $definition); + + // Browse the object's methods looking for annotated methods + $this->readMethods($class, $definition); + + return $definition; + } + + /** + * {@inheritdoc} + * @throws InvalidAnnotation + * @throws InvalidArgumentException The class doesn't exist + */ + public function getDefinition(string $name) + { + return $this->autowire($name); + } + + /** + * Autowiring cannot guess all existing definitions. + */ + public function getDefinitions() : array + { + return []; + } + + /** + * Browse the class properties looking for annotated properties. + */ + private function readProperties(ReflectionClass $class, ObjectDefinition $definition) + { + foreach ($class->getProperties() as $property) { + if ($property->isStatic()) { + continue; + } + $this->readProperty($property, $definition); + } + + // Read also the *private* properties of the parent classes + /** @noinspection PhpAssignmentInConditionInspection */ + while ($class = $class->getParentClass()) { + foreach ($class->getProperties(ReflectionProperty::IS_PRIVATE) as $property) { + if ($property->isStatic()) { + continue; + } + $this->readProperty($property, $definition, $class->getName()); + } + } + } + + private function readProperty(ReflectionProperty $property, ObjectDefinition $definition, $classname = null) + { + // Look for @Inject annotation + $annotation = $this->getAnnotationReader()->getPropertyAnnotation($property, 'DI\Annotation\Inject'); + if (!$annotation instanceof Inject) { + return; + } + + // Try to @Inject("name") or look for @var content + $entryName = $annotation->getName() ?: $this->getPhpDocReader()->getPropertyClass($property); + + // Try using PHP7.4 typed properties + if (\PHP_VERSION_ID > 70400 + && $entryName === null + && $property->getType() instanceof ReflectionNamedType + && (class_exists($property->getType()->getName()) || interface_exists($property->getType()->getName())) + ) { + $entryName = $property->getType()->getName(); + } + + if ($entryName === null) { + throw new InvalidAnnotation(sprintf( + '@Inject found on property %s::%s but unable to guess what to inject, use a @var annotation', + $property->getDeclaringClass()->getName(), + $property->getName() + )); + } + + $definition->addPropertyInjection( + new PropertyInjection($property->getName(), new Reference($entryName), $classname) + ); + } + + /** + * Browse the object's methods looking for annotated methods. + */ + private function readMethods(ReflectionClass $class, ObjectDefinition $objectDefinition) + { + // This will look in all the methods, including those of the parent classes + foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { + if ($method->isStatic()) { + continue; + } + + $methodInjection = $this->getMethodInjection($method); + + if (! $methodInjection) { + continue; + } + + if ($method->isConstructor()) { + $objectDefinition->completeConstructorInjection($methodInjection); + } else { + $objectDefinition->completeFirstMethodInjection($methodInjection); + } + } + } + + /** + * @return MethodInjection|null + */ + private function getMethodInjection(ReflectionMethod $method) + { + // Look for @Inject annotation + try { + $annotation = $this->getAnnotationReader()->getMethodAnnotation($method, 'DI\Annotation\Inject'); + } catch (InvalidAnnotation $e) { + throw new InvalidAnnotation(sprintf( + '@Inject annotation on %s::%s is malformed. %s', + $method->getDeclaringClass()->getName(), + $method->getName(), + $e->getMessage() + ), 0, $e); + } + + // @Inject on constructor is implicit + if (! ($annotation || $method->isConstructor())) { + return null; + } + + $annotationParameters = $annotation instanceof Inject ? $annotation->getParameters() : []; + + $parameters = []; + foreach ($method->getParameters() as $index => $parameter) { + $entryName = $this->getMethodParameter($index, $parameter, $annotationParameters); + + if ($entryName !== null) { + $parameters[$index] = new Reference($entryName); + } + } + + if ($method->isConstructor()) { + return MethodInjection::constructor($parameters); + } + + return new MethodInjection($method->getName(), $parameters); + } + + /** + * @param int $parameterIndex + * + * @return string|null Entry name or null if not found. + */ + private function getMethodParameter($parameterIndex, ReflectionParameter $parameter, array $annotationParameters) + { + // @Inject has definition for this parameter (by index, or by name) + if (isset($annotationParameters[$parameterIndex])) { + return $annotationParameters[$parameterIndex]; + } + if (isset($annotationParameters[$parameter->getName()])) { + return $annotationParameters[$parameter->getName()]; + } + + // Skip optional parameters if not explicitly defined + if ($parameter->isOptional()) { + return null; + } + + // Try to use the type-hinting + $parameterType = $parameter->getType(); + if ($parameterType && $parameterType instanceof ReflectionNamedType && !$parameterType->isBuiltin()) { + return $parameterType->getName(); + } + + // Last resort, look for @param tag + return $this->getPhpDocReader()->getParameterClass($parameter); + } + + /** + * @return Reader The annotation reader + */ + public function getAnnotationReader() + { + if ($this->annotationReader === null) { + AnnotationRegistry::registerLoader('class_exists'); + $this->annotationReader = new SimpleAnnotationReader(); + $this->annotationReader->addNamespace('DI\Annotation'); + } + + return $this->annotationReader; + } + + /** + * @return PhpDocReader + */ + private function getPhpDocReader() + { + if ($this->phpDocReader === null) { + $this->phpDocReader = new PhpDocReader($this->ignorePhpDocErrors); + } + + return $this->phpDocReader; + } + + private function readInjectableAnnotation(ReflectionClass $class, ObjectDefinition $definition) + { + try { + /** @var Injectable|null $annotation */ + $annotation = $this->getAnnotationReader() + ->getClassAnnotation($class, 'DI\Annotation\Injectable'); + } catch (UnexpectedValueException $e) { + throw new InvalidAnnotation(sprintf( + 'Error while reading @Injectable on %s: %s', + $class->getName(), + $e->getMessage() + ), 0, $e); + } + + if (! $annotation) { + return; + } + + if ($annotation->isLazy() !== null) { + $definition->setLazy($annotation->isLazy()); + } + } +} diff --git a/vendor/php-di/php-di/src/Definition/Source/Autowiring.php b/vendor/php-di/php-di/src/Definition/Source/Autowiring.php new file mode 100644 index 0000000..ae7682a --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/Autowiring.php @@ -0,0 +1,24 @@ + + */ +interface Autowiring +{ + /** + * Autowire the given definition. + * + * @throws InvalidDefinition An invalid definition was found. + * @return ObjectDefinition|null + */ + public function autowire(string $name, ObjectDefinition $definition = null); +} diff --git a/vendor/php-di/php-di/src/Definition/Source/DefinitionArray.php b/vendor/php-di/php-di/src/Definition/Source/DefinitionArray.php new file mode 100644 index 0000000..88f2cac --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/DefinitionArray.php @@ -0,0 +1,127 @@ + + */ +class DefinitionArray implements DefinitionSource, MutableDefinitionSource +{ + const WILDCARD = '*'; + /** + * Matches anything except "\". + */ + const WILDCARD_PATTERN = '([^\\\\]+)'; + + /** + * DI definitions in a PHP array. + * @var array + */ + private $definitions = []; + + /** + * Cache of wildcard definitions. + * @var array|null + */ + private $wildcardDefinitions; + + /** + * @var DefinitionNormalizer + */ + private $normalizer; + + public function __construct(array $definitions = [], Autowiring $autowiring = null) + { + if (isset($definitions[0])) { + throw new \Exception('The PHP-DI definition is not indexed by an entry name in the definition array'); + } + + $this->definitions = $definitions; + + $autowiring = $autowiring ?: new NoAutowiring; + $this->normalizer = new DefinitionNormalizer($autowiring); + } + + /** + * @param array $definitions DI definitions in a PHP array indexed by the definition name. + */ + public function addDefinitions(array $definitions) + { + if (isset($definitions[0])) { + throw new \Exception('The PHP-DI definition is not indexed by an entry name in the definition array'); + } + + // The newly added data prevails + // "for keys that exist in both arrays, the elements from the left-hand array will be used" + $this->definitions = $definitions + $this->definitions; + + // Clear cache + $this->wildcardDefinitions = null; + } + + /** + * {@inheritdoc} + */ + public function addDefinition(Definition $definition) + { + $this->definitions[$definition->getName()] = $definition; + + // Clear cache + $this->wildcardDefinitions = null; + } + + public function getDefinition(string $name) + { + // Look for the definition by name + if (array_key_exists($name, $this->definitions)) { + $definition = $this->definitions[$name]; + $definition = $this->normalizer->normalizeRootDefinition($definition, $name); + + return $definition; + } + + // Build the cache of wildcard definitions + if ($this->wildcardDefinitions === null) { + $this->wildcardDefinitions = []; + foreach ($this->definitions as $key => $definition) { + if (strpos($key, self::WILDCARD) !== false) { + $this->wildcardDefinitions[$key] = $definition; + } + } + } + + // Look in wildcards definitions + foreach ($this->wildcardDefinitions as $key => $definition) { + // Turn the pattern into a regex + $key = preg_quote($key); + $key = '#' . str_replace('\\' . self::WILDCARD, self::WILDCARD_PATTERN, $key) . '#'; + if (preg_match($key, $name, $matches) === 1) { + array_shift($matches); + $definition = $this->normalizer->normalizeRootDefinition($definition, $name, $matches); + + return $definition; + } + } + + return null; + } + + public function getDefinitions() : array + { + // Return all definitions except wildcard definitions + $definitions = []; + foreach ($this->definitions as $key => $definition) { + if (strpos($key, self::WILDCARD) === false) { + $definitions[$key] = $definition; + } + } + + return $definitions; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Source/DefinitionFile.php b/vendor/php-di/php-di/src/Definition/Source/DefinitionFile.php new file mode 100644 index 0000000..0c6caff --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/DefinitionFile.php @@ -0,0 +1,69 @@ + + */ +class DefinitionFile extends DefinitionArray +{ + /** + * @var bool + */ + private $initialized = false; + + /** + * File containing definitions, or null if the definitions are given as a PHP array. + * @var string|null + */ + private $file; + + /** + * @param string $file File in which the definitions are returned as an array. + */ + public function __construct($file, Autowiring $autowiring = null) + { + // Lazy-loading to improve performances + $this->file = $file; + + parent::__construct([], $autowiring); + } + + public function getDefinition(string $name) + { + $this->initialize(); + + return parent::getDefinition($name); + } + + public function getDefinitions() : array + { + $this->initialize(); + + return parent::getDefinitions(); + } + + /** + * Lazy-loading of the definitions. + */ + private function initialize() + { + if ($this->initialized === true) { + return; + } + + $definitions = require $this->file; + + if (! is_array($definitions)) { + throw new \Exception("File {$this->file} should return an array of definitions"); + } + + $this->addDefinitions($definitions); + + $this->initialized = true; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Source/DefinitionNormalizer.php b/vendor/php-di/php-di/src/Definition/Source/DefinitionNormalizer.php new file mode 100644 index 0000000..99ea36b --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/DefinitionNormalizer.php @@ -0,0 +1,120 @@ + + */ +class DefinitionNormalizer +{ + /** + * @var Autowiring + */ + private $autowiring; + + public function __construct(Autowiring $autowiring) + { + $this->autowiring = $autowiring; + } + + /** + * Normalize a definition that is *not* nested in another one. + * + * This is usually a definition declared at the root of a definition array. + * + * @param mixed $definition + * @param string $name The definition name. + * @param string[] $wildcardsReplacements Replacements for wildcard definitions. + * + * @throws InvalidDefinition + */ + public function normalizeRootDefinition($definition, string $name, array $wildcardsReplacements = null) : Definition + { + if ($definition instanceof DefinitionHelper) { + $definition = $definition->getDefinition($name); + } elseif (is_array($definition)) { + $definition = new ArrayDefinition($definition); + } elseif ($definition instanceof \Closure) { + $definition = new FactoryDefinition($name, $definition); + } elseif (! $definition instanceof Definition) { + $definition = new ValueDefinition($definition); + } + + // For a class definition, we replace * in the class name with the matches + // *Interface -> *Impl => FooInterface -> FooImpl + if ($wildcardsReplacements && $definition instanceof ObjectDefinition) { + $definition->replaceWildcards($wildcardsReplacements); + } + + if ($definition instanceof AutowireDefinition) { + $definition = $this->autowiring->autowire($name, $definition); + } + + $definition->setName($name); + + try { + $definition->replaceNestedDefinitions([$this, 'normalizeNestedDefinition']); + } catch (InvalidDefinition $e) { + throw InvalidDefinition::create($definition, sprintf( + 'Definition "%s" contains an error: %s', + $definition->getName(), + $e->getMessage() + ), $e); + } + + return $definition; + } + + /** + * Normalize a definition that is nested in another one. + * + * @param mixed $definition + * @return mixed + * + * @throws InvalidDefinition + */ + public function normalizeNestedDefinition($definition) + { + $name = ''; + + if ($definition instanceof DefinitionHelper) { + $definition = $definition->getDefinition($name); + } elseif (is_array($definition)) { + $definition = new ArrayDefinition($definition); + } elseif ($definition instanceof \Closure) { + $definition = new FactoryDefinition($name, $definition); + } + + if ($definition instanceof DecoratorDefinition) { + throw new InvalidDefinition('Decorators cannot be nested in another definition'); + } + + if ($definition instanceof AutowireDefinition) { + $definition = $this->autowiring->autowire($name, $definition); + } + + if ($definition instanceof Definition) { + $definition->setName($name); + + // Recursively traverse nested definitions + $definition->replaceNestedDefinitions([$this, 'normalizeNestedDefinition']); + } + + return $definition; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Source/DefinitionSource.php b/vendor/php-di/php-di/src/Definition/Source/DefinitionSource.php new file mode 100644 index 0000000..5aa95dd --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/DefinitionSource.php @@ -0,0 +1,29 @@ + + */ +interface DefinitionSource +{ + /** + * Returns the DI definition for the entry name. + * + * @throws InvalidDefinition An invalid definition was found. + * @return Definition|null + */ + public function getDefinition(string $name); + + /** + * @return Definition[] Definitions indexed by their name. + */ + public function getDefinitions() : array; +} diff --git a/vendor/php-di/php-di/src/Definition/Source/MutableDefinitionSource.php b/vendor/php-di/php-di/src/Definition/Source/MutableDefinitionSource.php new file mode 100644 index 0000000..0422174 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/MutableDefinitionSource.php @@ -0,0 +1,17 @@ + + */ +interface MutableDefinitionSource extends DefinitionSource +{ + public function addDefinition(Definition $definition); +} diff --git a/vendor/php-di/php-di/src/Definition/Source/NoAutowiring.php b/vendor/php-di/php-di/src/Definition/Source/NoAutowiring.php new file mode 100644 index 0000000..dda3e30 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/NoAutowiring.php @@ -0,0 +1,24 @@ + + */ +class NoAutowiring implements Autowiring +{ + public function autowire(string $name, ObjectDefinition $definition = null) + { + throw new InvalidDefinition(sprintf( + 'Cannot autowire entry "%s" because autowiring is disabled', + $name + )); + } +} diff --git a/vendor/php-di/php-di/src/Definition/Source/ReflectionBasedAutowiring.php b/vendor/php-di/php-di/src/Definition/Source/ReflectionBasedAutowiring.php new file mode 100644 index 0000000..fdc3748 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/ReflectionBasedAutowiring.php @@ -0,0 +1,85 @@ + + */ +class ReflectionBasedAutowiring implements DefinitionSource, Autowiring +{ + public function autowire(string $name, ObjectDefinition $definition = null) + { + $className = $definition ? $definition->getClassName() : $name; + + if (!class_exists($className) && !interface_exists($className)) { + return $definition; + } + + $definition = $definition ?: new ObjectDefinition($name); + + // Constructor + $class = new \ReflectionClass($className); + $constructor = $class->getConstructor(); + if ($constructor && $constructor->isPublic()) { + $constructorInjection = MethodInjection::constructor($this->getParametersDefinition($constructor)); + $definition->completeConstructorInjection($constructorInjection); + } + + return $definition; + } + + public function getDefinition(string $name) + { + return $this->autowire($name); + } + + /** + * Autowiring cannot guess all existing definitions. + */ + public function getDefinitions() : array + { + return []; + } + + /** + * Read the type-hinting from the parameters of the function. + */ + private function getParametersDefinition(\ReflectionFunctionAbstract $constructor) : array + { + $parameters = []; + + foreach ($constructor->getParameters() as $index => $parameter) { + // Skip optional parameters + if ($parameter->isOptional()) { + continue; + } + + $parameterType = $parameter->getType(); + if (!$parameterType) { + // No type + continue; + } + if (!$parameterType instanceof ReflectionNamedType) { + // Union types are not supported + continue; + } + if ($parameterType->isBuiltin()) { + // Primitive types are not supported + continue; + } + + $parameters[$index] = new Reference($parameterType->getName()); + } + + return $parameters; + } +} diff --git a/vendor/php-di/php-di/src/Definition/Source/SourceCache.php b/vendor/php-di/php-di/src/Definition/Source/SourceCache.php new file mode 100644 index 0000000..6487c2c --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/SourceCache.php @@ -0,0 +1,88 @@ + + */ +class SourceCache implements DefinitionSource, MutableDefinitionSource +{ + /** + * @var string + */ + const CACHE_KEY = 'php-di.definitions.'; + + /** + * @var DefinitionSource + */ + private $cachedSource; + + /** + * @var string + */ + private $cacheNamespace; + + public function __construct(DefinitionSource $cachedSource, string $cacheNamespace = '') + { + $this->cachedSource = $cachedSource; + $this->cacheNamespace = $cacheNamespace; + } + + public function getDefinition(string $name) + { + $definition = apcu_fetch($this->getCacheKey($name)); + + if ($definition === false) { + $definition = $this->cachedSource->getDefinition($name); + + // Update the cache + if ($this->shouldBeCached($definition)) { + apcu_store($this->getCacheKey($name), $definition); + } + } + + return $definition; + } + + /** + * Used only for the compilation so we can skip the cache safely. + */ + public function getDefinitions() : array + { + return $this->cachedSource->getDefinitions(); + } + + public static function isSupported() : bool + { + return function_exists('apcu_fetch') + && ini_get('apc.enabled') + && ! ('cli' === \PHP_SAPI && ! ini_get('apc.enable_cli')); + } + + public function getCacheKey(string $name) : string + { + return self::CACHE_KEY . $this->cacheNamespace . $name; + } + + public function addDefinition(Definition $definition) + { + throw new \LogicException('You cannot set a definition at runtime on a container that has caching enabled. Doing so would risk caching the definition for the next execution, where it might be different. You can either put your definitions in a file, remove the cache or ->set() a raw value directly (PHP object, string, int, ...) instead of a PHP-DI definition.'); + } + + private function shouldBeCached(Definition $definition = null) : bool + { + return + // Cache missing definitions + ($definition === null) + // Object definitions are used with `make()` + || ($definition instanceof ObjectDefinition) + // Autowired definitions cannot be all compiled and are used with `make()` + || ($definition instanceof AutowireDefinition); + } +} diff --git a/vendor/php-di/php-di/src/Definition/Source/SourceChain.php b/vendor/php-di/php-di/src/Definition/Source/SourceChain.php new file mode 100644 index 0000000..b82d618 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/Source/SourceChain.php @@ -0,0 +1,110 @@ + + */ +class SourceChain implements DefinitionSource, MutableDefinitionSource +{ + /** + * @var DefinitionSource[] + */ + private $sources; + + /** + * @var DefinitionSource + */ + private $rootSource; + + /** + * @var MutableDefinitionSource|null + */ + private $mutableSource; + + /** + * @param DefinitionSource[] $sources + */ + public function __construct(array $sources) + { + // We want a numerically indexed array to ease the traversal later + $this->sources = array_values($sources); + $this->rootSource = $this; + } + + /** + * {@inheritdoc} + * + * @param int $startIndex Use this parameter to start looking from a specific + * point in the source chain. + */ + public function getDefinition(string $name, int $startIndex = 0) + { + $count = count($this->sources); + for ($i = $startIndex; $i < $count; ++$i) { + $source = $this->sources[$i]; + + $definition = $source->getDefinition($name); + + if ($definition) { + if ($definition instanceof ExtendsPreviousDefinition) { + $this->resolveExtendedDefinition($definition, $i); + } + + return $definition; + } + } + + return null; + } + + public function getDefinitions() : array + { + $names = []; + foreach ($this->sources as $source) { + $names = array_merge($names, $source->getDefinitions()); + } + $names = array_keys($names); + + $definitions = array_combine($names, array_map(function (string $name) { + return $this->getDefinition($name); + }, $names)); + + return $definitions; + } + + public function addDefinition(Definition $definition) + { + if (! $this->mutableSource) { + throw new \LogicException("The container's definition source has not been initialized correctly"); + } + + $this->mutableSource->addDefinition($definition); + } + + private function resolveExtendedDefinition(ExtendsPreviousDefinition $definition, int $currentIndex) + { + // Look in the next sources only (else infinite recursion, and we can only extend + // entries defined in the previous definition files - a previous == next here because + // the array was reversed ;) ) + $subDefinition = $this->getDefinition($definition->getName(), $currentIndex + 1); + + if ($subDefinition) { + $definition->setExtendedDefinition($subDefinition); + } + } + + public function setMutableDefinitionSource(MutableDefinitionSource $mutableSource) + { + $this->mutableSource = $mutableSource; + + array_unshift($this->sources, $mutableSource); + } +} diff --git a/vendor/php-di/php-di/src/Definition/StringDefinition.php b/vendor/php-di/php-di/src/Definition/StringDefinition.php new file mode 100644 index 0000000..52207e7 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/StringDefinition.php @@ -0,0 +1,97 @@ + + */ +class StringDefinition implements Definition, SelfResolvingDefinition +{ + /** + * Entry name. + * @var string + */ + private $name = ''; + + /** + * @var string + */ + private $expression; + + public function __construct(string $expression) + { + $this->expression = $expression; + } + + public function getName() : string + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + public function getExpression() : string + { + return $this->expression; + } + + public function resolve(ContainerInterface $container) : string + { + return self::resolveExpression($this->name, $this->expression, $container); + } + + public function isResolvable(ContainerInterface $container) : bool + { + return true; + } + + public function replaceNestedDefinitions(callable $replacer) + { + // no nested definitions + } + + public function __toString() + { + return $this->expression; + } + + /** + * Resolve a string expression. + */ + public static function resolveExpression( + string $entryName, + string $expression, + ContainerInterface $container + ) : string { + $callback = function (array $matches) use ($entryName, $container) { + try { + return $container->get($matches[1]); + } catch (NotFoundExceptionInterface $e) { + throw new DependencyException(sprintf( + "Error while parsing string expression for entry '%s': %s", + $entryName, + $e->getMessage() + ), 0, $e); + } + }; + + $result = preg_replace_callback('#\{([^\{\}]+)\}#', $callback, $expression); + if ($result === null) { + throw new \RuntimeException(sprintf('An unknown error occurred while parsing the string definition: \'%s\'', $expression)); + } + + return $result; + } +} diff --git a/vendor/php-di/php-di/src/Definition/ValueDefinition.php b/vendor/php-di/php-di/src/Definition/ValueDefinition.php new file mode 100644 index 0000000..d647582 --- /dev/null +++ b/vendor/php-di/php-di/src/Definition/ValueDefinition.php @@ -0,0 +1,72 @@ + + */ +class ValueDefinition implements Definition, SelfResolvingDefinition +{ + /** + * Entry name. + * @var string + */ + private $name = ''; + + /** + * @var mixed + */ + private $value; + + /** + * @param mixed $value + */ + public function __construct($value) + { + $this->value = $value; + } + + public function getName() : string + { + return $this->name; + } + + public function setName(string $name) + { + $this->name = $name; + } + + /** + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + public function resolve(ContainerInterface $container) + { + return $this->getValue(); + } + + public function isResolvable(ContainerInterface $container) : bool + { + return true; + } + + public function replaceNestedDefinitions(callable $replacer) + { + // no nested definitions + } + + public function __toString() + { + return sprintf('Value (%s)', var_export($this->value, true)); + } +} diff --git a/vendor/php-di/php-di/src/DependencyException.php b/vendor/php-di/php-di/src/DependencyException.php new file mode 100644 index 0000000..63b5fdd --- /dev/null +++ b/vendor/php-di/php-di/src/DependencyException.php @@ -0,0 +1,14 @@ + + */ +interface RequestedEntry +{ + /** + * Returns the name of the entry that was requested by the container. + */ + public function getName() : string; +} diff --git a/vendor/php-di/php-di/src/FactoryInterface.php b/vendor/php-di/php-di/src/FactoryInterface.php new file mode 100644 index 0000000..59b410f --- /dev/null +++ b/vendor/php-di/php-di/src/FactoryInterface.php @@ -0,0 +1,31 @@ + + */ +interface FactoryInterface +{ + /** + * Resolves an entry by its name. If given a class name, it will return a new instance of that class. + * + * @param string $name Entry name or a class name. + * @param array $parameters Optional parameters to use to build the entry. Use this to force specific + * parameters to specific values. Parameters not defined in this array will + * be automatically resolved. + * + * @throws \InvalidArgumentException The name parameter must be of type string. + * @throws DependencyException Error while resolving the entry. + * @throws NotFoundException No entry or class found for the given name. + * @return mixed + */ + public function make($name, array $parameters = []); +} diff --git a/vendor/php-di/php-di/src/Invoker/DefinitionParameterResolver.php b/vendor/php-di/php-di/src/Invoker/DefinitionParameterResolver.php new file mode 100644 index 0000000..b17ebd9 --- /dev/null +++ b/vendor/php-di/php-di/src/Invoker/DefinitionParameterResolver.php @@ -0,0 +1,69 @@ + + */ +class DefinitionParameterResolver implements ParameterResolver +{ + /** + * @var DefinitionResolver + */ + private $definitionResolver; + + public function __construct(DefinitionResolver $definitionResolver) + { + $this->definitionResolver = $definitionResolver; + } + + public function getParameters( + ReflectionFunctionAbstract $reflection, + array $providedParameters, + array $resolvedParameters + ) : array { + // Skip parameters already resolved + if (! empty($resolvedParameters)) { + $providedParameters = array_diff_key($providedParameters, $resolvedParameters); + } + + foreach ($providedParameters as $key => $value) { + if ($value instanceof DefinitionHelper) { + $value = $value->getDefinition(''); + } + + if (! $value instanceof Definition) { + continue; + } + + $value = $this->definitionResolver->resolve($value); + + if (is_int($key)) { + // Indexed by position + $resolvedParameters[$key] = $value; + } else { + // Indexed by parameter name + // TODO optimize? + $reflectionParameters = $reflection->getParameters(); + foreach ($reflectionParameters as $reflectionParameter) { + if ($key === $reflectionParameter->name) { + $resolvedParameters[$reflectionParameter->getPosition()] = $value; + } + } + } + } + + return $resolvedParameters; + } +} diff --git a/vendor/php-di/php-di/src/Invoker/FactoryParameterResolver.php b/vendor/php-di/php-di/src/Invoker/FactoryParameterResolver.php new file mode 100644 index 0000000..f5ace87 --- /dev/null +++ b/vendor/php-di/php-di/src/Invoker/FactoryParameterResolver.php @@ -0,0 +1,74 @@ + + * @author Matthieu Napoli + */ +class FactoryParameterResolver implements ParameterResolver +{ + /** + * @var ContainerInterface + */ + private $container; + + public function __construct(ContainerInterface $container) + { + $this->container = $container; + } + + public function getParameters( + ReflectionFunctionAbstract $reflection, + array $providedParameters, + array $resolvedParameters + ) : array { + $parameters = $reflection->getParameters(); + + // Skip parameters already resolved + if (! empty($resolvedParameters)) { + $parameters = array_diff_key($parameters, $resolvedParameters); + } + + foreach ($parameters as $index => $parameter) { + $parameterType = $parameter->getType(); + if (!$parameterType) { + // No type + continue; + } + if (!$parameterType instanceof ReflectionNamedType) { + // Union types are not supported + continue; + } + if ($parameterType->isBuiltin()) { + // Primitive types are not supported + continue; + } + + $parameterClass = $parameterType->getName(); + + if ($parameterClass === 'Psr\Container\ContainerInterface') { + $resolvedParameters[$index] = $this->container; + } elseif ($parameterClass === 'DI\Factory\RequestedEntry') { + // By convention the second parameter is the definition + $resolvedParameters[$index] = $providedParameters[1]; + } elseif ($this->container->has($parameterClass)) { + $resolvedParameters[$index] = $this->container->get($parameterClass); + } + } + + return $resolvedParameters; + } +} diff --git a/vendor/php-di/php-di/src/NotFoundException.php b/vendor/php-di/php-di/src/NotFoundException.php new file mode 100644 index 0000000..67dbacd --- /dev/null +++ b/vendor/php-di/php-di/src/NotFoundException.php @@ -0,0 +1,14 @@ + + */ +class ProxyFactory +{ + /** + * If true, write the proxies to disk to improve performances. + * @var bool + */ + private $writeProxiesToFile; + + /** + * Directory where to write the proxies (if $writeProxiesToFile is enabled). + * @var string|null + */ + private $proxyDirectory; + + /** + * @var LazyLoadingValueHolderFactory|null + */ + private $proxyManager; + + public function __construct(bool $writeProxiesToFile = false, string $proxyDirectory = null) + { + $this->writeProxiesToFile = $writeProxiesToFile; + $this->proxyDirectory = $proxyDirectory; + } + + /** + * Creates a new lazy proxy instance of the given class with + * the given initializer. + * + * @param string $className name of the class to be proxied + * @param \Closure $initializer initializer to be passed to the proxy + */ + public function createProxy(string $className, \Closure $initializer) : LazyLoadingInterface + { + $this->createProxyManager(); + + return $this->proxyManager->createProxy($className, $initializer); + } + + /** + * Generates and writes the proxy class to file. + * + * @param string $className name of the class to be proxied + */ + public function generateProxyClass(string $className) + { + // If proxy classes a written to file then we pre-generate the class + // If they are not written to file then there is no point to do this + if ($this->writeProxiesToFile) { + $this->createProxyManager(); + $this->createProxy($className, function () {}); + } + } + + private function createProxyManager() + { + if ($this->proxyManager !== null) { + return; + } + + if (! class_exists(Configuration::class)) { + throw new \RuntimeException('The ocramius/proxy-manager library is not installed. Lazy injection requires that library to be installed with Composer in order to work. Run "composer require ocramius/proxy-manager:~2.0".'); + } + + $config = new Configuration(); + + if ($this->writeProxiesToFile) { + $config->setProxiesTargetDir($this->proxyDirectory); + $config->setGeneratorStrategy(new FileWriterGeneratorStrategy(new FileLocator($this->proxyDirectory))); + // @phpstan-ignore-next-line + spl_autoload_register($config->getProxyAutoloader()); + } else { + $config->setGeneratorStrategy(new EvaluatingGeneratorStrategy()); + } + + $this->proxyManager = new LazyLoadingValueHolderFactory($config); + } +} diff --git a/vendor/php-di/php-di/src/functions.php b/vendor/php-di/php-di/src/functions.php new file mode 100644 index 0000000..0504edb --- /dev/null +++ b/vendor/php-di/php-di/src/functions.php @@ -0,0 +1,156 @@ + decorate(function ($foo, $container) { + * return new CachedFoo($foo, $container->get('cache')); + * }) + * + * @param callable $callable The callable takes the decorated object as first parameter and + * the container as second. + */ + function decorate($callable) : FactoryDefinitionHelper + { + return new FactoryDefinitionHelper($callable, true); + } +} + +if (! function_exists('DI\get')) { + /** + * Helper for referencing another container entry in an object definition. + */ + function get(string $entryName) : Reference + { + return new Reference($entryName); + } +} + +if (! function_exists('DI\env')) { + /** + * Helper for referencing environment variables. + * + * @param string $variableName The name of the environment variable. + * @param mixed $defaultValue The default value to be used if the environment variable is not defined. + */ + function env(string $variableName, $defaultValue = null) : EnvironmentVariableDefinition + { + // Only mark as optional if the default value was *explicitly* provided. + $isOptional = 2 === func_num_args(); + + return new EnvironmentVariableDefinition($variableName, $isOptional, $defaultValue); + } +} + +if (! function_exists('DI\add')) { + /** + * Helper for extending another definition. + * + * Example: + * + * 'log.backends' => DI\add(DI\get('My\Custom\LogBackend')) + * + * or: + * + * 'log.backends' => DI\add([ + * DI\get('My\Custom\LogBackend') + * ]) + * + * @param mixed|array $values A value or an array of values to add to the array. + * + * @since 5.0 + */ + function add($values) : ArrayDefinitionExtension + { + if (! is_array($values)) { + $values = [$values]; + } + + return new ArrayDefinitionExtension($values); + } +} + +if (! function_exists('DI\string')) { + /** + * Helper for concatenating strings. + * + * Example: + * + * 'log.filename' => DI\string('{app.path}/app.log') + * + * @param string $expression A string expression. Use the `{}` placeholders to reference other container entries. + * + * @since 5.0 + */ + function string(string $expression) : StringDefinition + { + return new StringDefinition($expression); + } +} diff --git a/vendor/php-di/php-di/support.md b/vendor/php-di/php-di/support.md new file mode 100644 index 0000000..22dd39a --- /dev/null +++ b/vendor/php-di/php-di/support.md @@ -0,0 +1,42 @@ +--- +layout: documentation +current_menu: enterprise-support +title: Enterprise support for PHP-DI +--- + +# PHP-DI for Enterprise + +> *Available as part of the Tidelift Subscription* + +Tidelift is working with the maintainers of PHP-DI and thousands of other +open source projects to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. + +#### [Learn more](https://tidelift.com/subscription/pkg/packagist-php-di-php-di?utm_source=packagist-php-di-php-di&utm_medium=referral&utm_campaign=enterprise) | [**Request a demo**](https://tidelift.com/subscription/request-a-demo?utm_source=packagist-php-di-php-di&utm_medium=referral&utm_campaign=enterprise) + +## Enterprise-ready open source software—managed for you + +The Tidelift Subscription is a managed open source subscription for application dependencies covering millions of open source projects across JavaScript, Python, Java, PHP, Ruby, .NET, and more. + +Your subscription includes: + +- **Security updates** + Tidelift’s security response team coordinates patches for new breaking security vulnerabilities and alerts immediately through a private channel, so your software supply chain is always secure. + +- **Licensing verification and indemnification** + Tidelift verifies license information to enable easy policy enforcement and adds intellectual property indemnification to cover creators and users in case something goes wrong. You always have a 100% up-to-date bill of materials for your dependencies to share with your legal team, customers, or partners. + +- **Maintenance and code improvement** + Tidelift ensures the software you rely on keeps working as long as you need it to work. Your managed dependencies are actively maintained and we recruit additional maintainers where required. + +- **Package selection and version guidance** + We help you choose the best open source packages from the start—and then guide you through updates to stay on the best releases as new issues arise. + +- **Roadmap input** + Take a seat at the table with the creators behind the software you use. Tidelift’s participating maintainers earn more income as their software is used by more subscribers, so they’re interested in knowing what you need. + +- **Tooling and cloud integration** + Tidelift works with GitHub, GitLab, BitBucket, and more. We support every cloud platform (and other deployment targets, too). + +The end result? All of the capabilities you expect from commercial-grade software, for the full breadth of open source you use. That means less time grappling with esoteric open source trivia, and more time building your own applications—and your business. + +[Learn more](https://tidelift.com/subscription/pkg/packagist-php-di-php-di?utm_source=packagist-php-di-php-di&utm_medium=referral&utm_campaign=enterprise) | [**Request a demo**](https://tidelift.com/subscription/request-a-demo?utm_source=packagist-php-di-php-di&utm_medium=referral&utm_campaign=enterprise) diff --git a/vendor/php-di/phpdoc-reader/.gitattributes b/vendor/php-di/phpdoc-reader/.gitattributes new file mode 100644 index 0000000..912292c --- /dev/null +++ b/vendor/php-di/phpdoc-reader/.gitattributes @@ -0,0 +1,7 @@ +# .gitattributes +tests/ export-ignore +phpunit.xml.dist export-ignore +.travis.yml export-ignore + +# Auto detect text files and perform LF normalization +* text=auto diff --git a/vendor/php-di/phpdoc-reader/.github/workflows/ci.yml b/vendor/php-di/phpdoc-reader/.github/workflows/ci.yml new file mode 100644 index 0000000..5b7421d --- /dev/null +++ b/vendor/php-di/phpdoc-reader/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +name: CI + +on: + push: + branches: ['master'] + pull_request: + branches: ['*'] + schedule: + - cron: '0 0 * * *' + +jobs: + + tests: + name: Tests - PHP ${{ matrix.php }} ${{ matrix.dependency-version }} + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + matrix: + php: [ '7.2', '7.3', '7.4', '8.0' ] + dependency-version: [ '' ] + include: + - php: '7.2' + dependency-version: '--prefer-lowest' + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + tools: composer:v2 + coverage: none + - name: Cache Composer dependencies + uses: actions/cache@v2 + with: + path: ~/.composer/cache + key: php-${{ matrix.php }}-composer-locked-${{ hashFiles('composer.lock') }} + restore-keys: php-${{ matrix.php }}-composer-locked- + - name: Install PHP dependencies + run: composer update ${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-progress --no-suggest + - name: PHPUnit + run: vendor/bin/phpunit + + cs: + name: Coding standards + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 7.4 + tools: composer:v2, cs2pr + coverage: none + - name: Cache Composer dependencies + uses: actions/cache@v2 + with: + path: ~/.composer/cache + key: php-74-composer-locked-${{ hashFiles('composer.lock') }} + restore-keys: php-74-composer-locked- + - name: Install PHP dependencies + run: composer install --no-interaction --no-progress --no-suggest + - name: PHP CodeSniffer + run: vendor/bin/phpcs -q --no-colors --report=checkstyle | cs2pr diff --git a/vendor/php-di/phpdoc-reader/.gitignore b/vendor/php-di/phpdoc-reader/.gitignore new file mode 100644 index 0000000..9abe135 --- /dev/null +++ b/vendor/php-di/phpdoc-reader/.gitignore @@ -0,0 +1,7 @@ +.DS_Store +.idea/* +vendor/* +composer.phar +composer.lock +.phpcs-cache +.phpunit.result.cache diff --git a/vendor/php-di/phpdoc-reader/.phpcs.xml.dist b/vendor/php-di/phpdoc-reader/.phpcs.xml.dist new file mode 100644 index 0000000..191db96 --- /dev/null +++ b/vendor/php-di/phpdoc-reader/.phpcs.xml.dist @@ -0,0 +1,21 @@ + + + + + + + + + src + src/PhpDocReader/PhpParser/TokenParser.php + tests + tests/Fixtures + + + + + + 0 + + + diff --git a/vendor/php-di/phpdoc-reader/LICENSE b/vendor/php-di/phpdoc-reader/LICENSE new file mode 100644 index 0000000..f3d2a02 --- /dev/null +++ b/vendor/php-di/phpdoc-reader/LICENSE @@ -0,0 +1,16 @@ +Copyright (C) 2019 Matthieu Napoli + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/php-di/phpdoc-reader/README.md b/vendor/php-di/phpdoc-reader/README.md new file mode 100644 index 0000000..bfaa6c3 --- /dev/null +++ b/vendor/php-di/phpdoc-reader/README.md @@ -0,0 +1,57 @@ +# PhpDocReader + +![](https://img.shields.io/packagist/dt/PHP-DI/phpdoc-reader.svg) + +This project is used by: + +- [PHP-DI 6](http://php-di.org/) +- [phockito-unit-php-di](https://github.com/balihoo/phockito-unit-php-di) + +Fork the README to add your project here. + +## Features + +PhpDocReader parses `@var` and `@param` values in PHP docblocks: + +```php + +use My\Cache\Backend; + +class Cache +{ + /** + * @var Backend + */ + protected $backend; + + /** + * @param Backend $backend + */ + public function __construct($backend) + { + } +} +``` + +It supports namespaced class names with the same resolution rules as PHP: + +- fully qualified name (starting with `\`) +- imported class name (eg. `use My\Cache\Backend;`) +- relative class name (from the current namespace, like `SubNamespace\MyClass`) +- aliased class name (eg. `use My\Cache\Backend as FooBar;`) + +Primitive types (`@var string`) are ignored (returns null), only valid class names are returned. + +## Usage + +```php +$reader = new PhpDocReader(); + +// Read a property type (@var phpdoc) +$property = new ReflectionProperty($className, $propertyName); +$propertyClass = $reader->getPropertyClass($property); + +// Read a parameter type (@param phpdoc) +$parameter = new ReflectionParameter(array($className, $methodName), $parameterName); +$parameterClass = $reader->getParameterClass($parameter); +``` diff --git a/vendor/php-di/phpdoc-reader/composer.json b/vendor/php-di/phpdoc-reader/composer.json new file mode 100644 index 0000000..64d7262 --- /dev/null +++ b/vendor/php-di/phpdoc-reader/composer.json @@ -0,0 +1,24 @@ +{ + "name": "php-di/phpdoc-reader", + "type": "library", + "description": "PhpDocReader parses @var and @param values in PHP docblocks (supports namespaced class names with the same resolution rules as PHP)", + "keywords": ["phpdoc", "reflection"], + "license": "MIT", + "autoload": { + "psr-4": { + "PhpDocReader\\": "src/PhpDocReader" + } + }, + "autoload-dev": { + "psr-4": { + "UnitTest\\PhpDocReader\\": "tests/" + } + }, + "require": { + "php": ">=7.2.0" + }, + "require-dev": { + "phpunit/phpunit": "^8.5|^9.0", + "mnapoli/hard-mode": "~0.3.0" + } +} diff --git a/vendor/php-di/phpdoc-reader/src/PhpDocReader/AnnotationException.php b/vendor/php-di/phpdoc-reader/src/PhpDocReader/AnnotationException.php new file mode 100644 index 0000000..1466a9b --- /dev/null +++ b/vendor/php-di/phpdoc-reader/src/PhpDocReader/AnnotationException.php @@ -0,0 +1,10 @@ + 'bool', + 'boolean' => 'bool', + 'string' => 'string', + 'int' => 'int', + 'integer' => 'int', + 'float' => 'float', + 'double' => 'float', + 'array' => 'array', + 'object' => 'object', + 'callable' => 'callable', + 'resource' => 'resource', + 'mixed' => 'mixed', + 'iterable' => 'iterable', + ]; + + /** @var bool */ + private $ignorePhpDocErrors; + + /** + * @param bool $ignorePhpDocErrors Enable or disable throwing errors when PhpDoc errors occur (when parsing annotations). + */ + public function __construct(bool $ignorePhpDocErrors = false) + { + $this->parser = new UseStatementParser; + $this->ignorePhpDocErrors = $ignorePhpDocErrors; + } + + /** + * Parse the docblock of the property to get the type (class or primitive type) of the var annotation. + * + * @return string|null Type of the property (content of var annotation) + * @throws AnnotationException + */ + public function getPropertyType(ReflectionProperty $property): ?string + { + return $this->readPropertyType($property, true); + } + + /** + * Parse the docblock of the property to get the class of the var annotation. + * + * @return string|null Type of the property (content of var annotation) + * @throws AnnotationException + */ + public function getPropertyClass(ReflectionProperty $property): ?string + { + return $this->readPropertyType($property, false); + } + + private function readPropertyType(ReflectionProperty $property, bool $allowPrimitiveTypes): ?string + { + // Get the content of the @var annotation + $docComment = $property->getDocComment(); + if (! $docComment) { + return null; + } + if (preg_match('/@var\s+([^\s]+)/', $docComment, $matches)) { + [, $type] = $matches; + } else { + return null; + } + + // Ignore primitive types + if (isset(self::PRIMITIVE_TYPES[$type])) { + if ($allowPrimitiveTypes) { + return self::PRIMITIVE_TYPES[$type]; + } + return null; + } + + // Ignore types containing special characters ([], <> ...) + if (! preg_match('/^[a-zA-Z0-9\\\\_]+$/', $type)) { + return null; + } + + $class = $property->getDeclaringClass(); + + // If the class name is not fully qualified (i.e. doesn't start with a \) + if ($type[0] !== '\\') { + // Try to resolve the FQN using the class context + $resolvedType = $this->tryResolveFqn($type, $class, $property); + + if (! $resolvedType && ! $this->ignorePhpDocErrors) { + throw new AnnotationException(sprintf( + 'The @var annotation on %s::%s contains a non existent class "%s". ' + . 'Did you maybe forget to add a "use" statement for this annotation?', + $class->name, + $property->getName(), + $type + )); + } + + $type = $resolvedType; + } + + if (! $this->ignorePhpDocErrors && ! $this->classExists($type)) { + throw new AnnotationException(sprintf( + 'The @var annotation on %s::%s contains a non existent class "%s"', + $class->name, + $property->getName(), + $type + )); + } + + // Remove the leading \ (FQN shouldn't contain it) + $type = is_string($type) ? ltrim($type, '\\') : null; + + return $type; + } + + /** + * Parse the docblock of the property to get the type (class or primitive type) of the param annotation. + * + * @return string|null Type of the property (content of var annotation) + * @throws AnnotationException + */ + public function getParameterType(ReflectionParameter $parameter): ?string + { + return $this->readParameterClass($parameter, true); + } + + /** + * Parse the docblock of the property to get the class of the param annotation. + * + * @return string|null Type of the property (content of var annotation) + * @throws AnnotationException + */ + public function getParameterClass(ReflectionParameter $parameter): ?string + { + return $this->readParameterClass($parameter, false); + } + + private function readParameterClass(ReflectionParameter $parameter, bool $allowPrimitiveTypes): ?string + { + // Use reflection + $parameterType = $parameter->getType(); + if ($parameterType && $parameterType instanceof \ReflectionNamedType && ! $parameterType->isBuiltin()) { + return $parameterType->getName(); + } + + $parameterName = $parameter->name; + // Get the content of the @param annotation + $method = $parameter->getDeclaringFunction(); + $docComment = $method->getDocComment(); + if (! $docComment) { + return null; + } + if (preg_match('/@param\s+([^\s]+)\s+\$' . $parameterName . '/', $docComment, $matches)) { + [, $type] = $matches; + } else { + return null; + } + + // Ignore primitive types + if (isset(self::PRIMITIVE_TYPES[$type])) { + if ($allowPrimitiveTypes) { + return self::PRIMITIVE_TYPES[$type]; + } + return null; + } + + // Ignore types containing special characters ([], <> ...) + if (! preg_match('/^[a-zA-Z0-9\\\\_]+$/', $type)) { + return null; + } + + $class = $parameter->getDeclaringClass(); + + // If the class name is not fully qualified (i.e. doesn't start with a \) + if ($type[0] !== '\\') { + // Try to resolve the FQN using the class context + $resolvedType = $this->tryResolveFqn($type, $class, $parameter); + + if (! $resolvedType && ! $this->ignorePhpDocErrors) { + throw new AnnotationException(sprintf( + 'The @param annotation for parameter "%s" of %s::%s contains a non existent class "%s". ' + . 'Did you maybe forget to add a "use" statement for this annotation?', + $parameterName, + $class->name, + $method->name, + $type + )); + } + + $type = $resolvedType; + } + + if (! $this->ignorePhpDocErrors && ! $this->classExists($type)) { + throw new AnnotationException(sprintf( + 'The @param annotation for parameter "%s" of %s::%s contains a non existent class "%s"', + $parameterName, + $class->name, + $method->name, + $type + )); + } + + // Remove the leading \ (FQN shouldn't contain it) + $type = is_string($type) ? ltrim($type, '\\') : null; + + return $type; + } + + /** + * Attempts to resolve the FQN of the provided $type based on the $class and $member context. + * + * @return string|null Fully qualified name of the type, or null if it could not be resolved + */ + private function tryResolveFqn(string $type, ReflectionClass $class, Reflector $member): ?string + { + $alias = ($pos = strpos($type, '\\')) === false ? $type : substr($type, 0, $pos); + $loweredAlias = strtolower($alias); + + // Retrieve "use" statements + $uses = $this->parser->parseUseStatements($class); + + if (isset($uses[$loweredAlias])) { + // Imported classes + if ($pos !== false) { + return $uses[$loweredAlias] . substr($type, $pos); + } + return $uses[$loweredAlias]; + } + + if ($this->classExists($class->getNamespaceName() . '\\' . $type)) { + return $class->getNamespaceName() . '\\' . $type; + } + + if (isset($uses['__NAMESPACE__']) && $this->classExists($uses['__NAMESPACE__'] . '\\' . $type)) { + // Class namespace + return $uses['__NAMESPACE__'] . '\\' . $type; + } + + if ($this->classExists($type)) { + // No namespace + return $type; + } + + // If all fail, try resolving through related traits + return $this->tryResolveFqnInTraits($type, $class, $member); + } + + /** + * Attempts to resolve the FQN of the provided $type based on the $class and $member context, specifically searching + * through the traits that are used by the provided $class. + * + * @return string|null Fully qualified name of the type, or null if it could not be resolved + */ + private function tryResolveFqnInTraits(string $type, ReflectionClass $class, Reflector $member): ?string + { + /** @var ReflectionClass[] $traits */ + $traits = []; + + // Get traits for the class and its parents + while ($class) { + $traits = array_merge($traits, $class->getTraits()); + $class = $class->getParentClass(); + } + + foreach ($traits as $trait) { + // Eliminate traits that don't have the property/method/parameter + if ($member instanceof ReflectionProperty && ! $trait->hasProperty($member->name)) { + continue; + } + if ($member instanceof ReflectionMethod && ! $trait->hasMethod($member->name)) { + continue; + } + if ($member instanceof ReflectionParameter && ! $trait->hasMethod($member->getDeclaringFunction()->name)) { + continue; + } + + // Run the resolver again with the ReflectionClass instance for the trait + $resolvedType = $this->tryResolveFqn($type, $trait, $member); + + if ($resolvedType) { + return $resolvedType; + } + } + + return null; + } + + private function classExists(string $class): bool + { + return class_exists($class) || interface_exists($class); + } +} diff --git a/vendor/php-di/phpdoc-reader/src/PhpDocReader/PhpParser/TokenParser.php b/vendor/php-di/phpdoc-reader/src/PhpDocReader/PhpParser/TokenParser.php new file mode 100644 index 0000000..1f6ec70 --- /dev/null +++ b/vendor/php-di/phpdoc-reader/src/PhpDocReader/PhpParser/TokenParser.php @@ -0,0 +1,182 @@ + + * @author Christian Kaps + */ +class TokenParser +{ + /** + * The token list. + * + * @var list + */ + private $tokens; + + /** + * The number of tokens. + * + * @var int + */ + private $numTokens; + + /** + * The current array pointer. + * + * @var int + */ + private $pointer = 0; + + /** + * @param string $contents + */ + public function __construct($contents) + { + $this->tokens = token_get_all($contents); + + // The PHP parser sets internal compiler globals for certain things. Annoyingly, the last docblock comment it + // saw gets stored in doc_comment. When it comes to compile the next thing to be include()d this stored + // doc_comment becomes owned by the first thing the compiler sees in the file that it considers might have a + // docblock. If the first thing in the file is a class without a doc block this would cause calls to + // getDocBlock() on said class to return our long lost doc_comment. Argh. + // To workaround, cause the parser to parse an empty docblock. Sure getDocBlock() will return this, but at least + // it's harmless to us. + token_get_all("numTokens = count($this->tokens); + } + + /** + * Gets all use statements. + * + * @param string $namespaceName The namespace name of the reflected class. + * + * @return array A list with all found use statements. + */ + public function parseUseStatements($namespaceName) + { + $statements = []; + while (($token = $this->next())) { + if ($token[0] === T_USE) { + $statements = array_merge($statements, $this->parseUseStatement()); + continue; + } + + if ($token[0] !== T_NAMESPACE || $this->parseNamespace() !== $namespaceName) { + continue; + } + + // Get fresh array for new namespace. This is to prevent the parser to collect the use statements + // for a previous namespace with the same name. This is the case if a namespace is defined twice + // or if a namespace with the same name is commented out. + $statements = []; + } + + return $statements; + } + + /** + * Gets the next non whitespace and non comment token. + * + * @param bool $docCommentIsComment If TRUE then a doc comment is considered a comment and skipped. + * If FALSE then only whitespace and normal comments are skipped. + * + * @return mixed[]|string|null The token if exists, null otherwise. + */ + private function next($docCommentIsComment = true) + { + for ($i = $this->pointer; $i < $this->numTokens; $i++) { + $this->pointer++; + if ( + $this->tokens[$i][0] === T_WHITESPACE || + $this->tokens[$i][0] === T_COMMENT || + ($docCommentIsComment && $this->tokens[$i][0] === T_DOC_COMMENT) + ) { + continue; + } + + return $this->tokens[$i]; + } + + return null; + } + + /** + * Parses a single use statement. + * + * @return array A list with all found class names for a use statement. + */ + private function parseUseStatement() + { + $groupRoot = ''; + $class = ''; + $alias = ''; + $statements = []; + $explicitAlias = false; + while (($token = $this->next())) { + if (! $explicitAlias && $token[0] === T_STRING) { + $class .= $token[1]; + $alias = $token[1]; + } elseif ($explicitAlias && $token[0] === T_STRING) { + $alias = $token[1]; + } elseif ( + PHP_VERSION_ID >= 80000 && + ($token[0] === T_NAME_QUALIFIED || $token[0] === T_NAME_FULLY_QUALIFIED) + ) { + $class .= $token[1]; + + $classSplit = explode('\\', $token[1]); + $alias = $classSplit[count($classSplit) - 1]; + } elseif ($token[0] === T_NS_SEPARATOR) { + $class .= '\\'; + $alias = ''; + } elseif ($token[0] === T_AS) { + $explicitAlias = true; + $alias = ''; + } elseif ($token === ',') { + $statements[strtolower($alias)] = $groupRoot . $class; + $class = ''; + $alias = ''; + $explicitAlias = false; + } elseif ($token === ';') { + $statements[strtolower($alias)] = $groupRoot . $class; + break; + } elseif ($token === '{') { + $groupRoot = $class; + $class = ''; + } elseif ($token === '}') { + continue; + } else { + break; + } + } + + return $statements; + } + + /** + * Gets the namespace. + * + * @return string The found namespace. + */ + private function parseNamespace() + { + $name = ''; + while ( + ($token = $this->next()) && ($token[0] === T_STRING || $token[0] === T_NS_SEPARATOR || ( + PHP_VERSION_ID >= 80000 && + ($token[0] === T_NAME_QUALIFIED || $token[0] === T_NAME_FULLY_QUALIFIED) + )) + ) { + $name .= $token[1]; + } + + return $name; + } +} diff --git a/vendor/php-di/phpdoc-reader/src/PhpDocReader/PhpParser/UseStatementParser.php b/vendor/php-di/phpdoc-reader/src/PhpDocReader/PhpParser/UseStatementParser.php new file mode 100644 index 0000000..39515df --- /dev/null +++ b/vendor/php-di/phpdoc-reader/src/PhpDocReader/PhpParser/UseStatementParser.php @@ -0,0 +1,64 @@ + and Christian Kaps + */ +class UseStatementParser +{ + /** + * @return array A list with use statements in the form (Alias => FQN). + */ + public function parseUseStatements(\ReflectionClass $class): array + { + $filename = $class->getFilename(); + if ($filename === false) { + return []; + } + + $content = $this->getFileContent($filename, $class->getStartLine()); + + if ($content === null) { + return []; + } + + $namespace = preg_quote($class->getNamespaceName(), '/'); + $content = preg_replace('/^.*?(\bnamespace\s+' . $namespace . '\s*[;{].*)$/s', '\\1', $content); + $tokenizer = new TokenParser('parseUseStatements($class->getNamespaceName()); + } + + /** + * Gets the content of the file right up to the given line number. + * + * @param string $filename The name of the file to load. + * @param int $lineNumber The number of lines to read from file. + */ + private function getFileContent(string $filename, int $lineNumber): string + { + if (! is_file($filename)) { + throw new \RuntimeException("Unable to read file $filename"); + } + + $content = ''; + $lineCnt = 0; + $file = new SplFileObject($filename); + while (! $file->eof()) { + if ($lineCnt++ === $lineNumber) { + break; + } + + $content .= $file->fgets(); + } + + return $content; + } +} diff --git a/vendor/psr/container/.gitignore b/vendor/psr/container/.gitignore new file mode 100644 index 0000000..b2395aa --- /dev/null +++ b/vendor/psr/container/.gitignore @@ -0,0 +1,3 @@ +composer.lock +composer.phar +/vendor/ diff --git a/vendor/psr/container/LICENSE b/vendor/psr/container/LICENSE new file mode 100644 index 0000000..2877a48 --- /dev/null +++ b/vendor/psr/container/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2016 container-interop +Copyright (c) 2016 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/psr/container/README.md b/vendor/psr/container/README.md new file mode 100644 index 0000000..1b9d9e5 --- /dev/null +++ b/vendor/psr/container/README.md @@ -0,0 +1,13 @@ +Container interface +============== + +This repository holds all interfaces related to [PSR-11 (Container Interface)][psr-url]. + +Note that this is not a Container implementation of its own. It is merely abstractions that describe the components of a Dependency Injection Container. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-11/ +[package-url]: https://packagist.org/packages/psr/container +[implementation-url]: https://packagist.org/providers/psr/container-implementation + diff --git a/vendor/psr/container/composer.json b/vendor/psr/container/composer.json new file mode 100644 index 0000000..017f41e --- /dev/null +++ b/vendor/psr/container/composer.json @@ -0,0 +1,22 @@ +{ + "name": "psr/container", + "type": "library", + "description": "Common Container Interface (PHP FIG PSR-11)", + "keywords": ["psr", "psr-11", "container", "container-interop", "container-interface"], + "homepage": "https://github.com/php-fig/container", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=7.4.0" + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + } +} diff --git a/vendor/psr/container/src/ContainerExceptionInterface.php b/vendor/psr/container/src/ContainerExceptionInterface.php new file mode 100644 index 0000000..0f213f2 --- /dev/null +++ b/vendor/psr/container/src/ContainerExceptionInterface.php @@ -0,0 +1,12 @@ +=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/vendor/psr/http-factory/src/RequestFactoryInterface.php b/vendor/psr/http-factory/src/RequestFactoryInterface.php new file mode 100644 index 0000000..cb39a08 --- /dev/null +++ b/vendor/psr/http-factory/src/RequestFactoryInterface.php @@ -0,0 +1,18 @@ + `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. +> When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. + diff --git a/vendor/psr/http-message/docs/PSR7-Usage.md b/vendor/psr/http-message/docs/PSR7-Usage.md new file mode 100644 index 0000000..b6d048a --- /dev/null +++ b/vendor/psr/http-message/docs/PSR7-Usage.md @@ -0,0 +1,159 @@ +### PSR-7 Usage + +All PSR-7 applications comply with these interfaces +They were created to establish a standard between middleware implementations. + +> `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. +> When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. + + +The following examples will illustrate how basic operations are done in PSR-7. + +##### Examples + + +For this examples to work (at least) a PSR-7 implementation package is required. (eg: zendframework/zend-diactoros, guzzlehttp/psr7, slim/slim, etc) +All PSR-7 implementations should have the same behaviour. + +The following will be assumed: +`$request` is an object of `Psr\Http\Message\RequestInterface` and + +`$response` is an object implementing `Psr\Http\Message\RequestInterface` + + +### Working with HTTP Headers + +#### Adding headers to response: + +```php +$response->withHeader('My-Custom-Header', 'My Custom Message'); +``` + +#### Appending values to headers + +```php +$response->withAddedHeader('My-Custom-Header', 'The second message'); +``` + +#### Checking if header exists: + +```php +$request->hasHeader('My-Custom-Header'); // will return false +$response->hasHeader('My-Custom-Header'); // will return true +``` + +> Note: My-Custom-Header was only added in the Response + +#### Getting comma-separated values from a header (also applies to request) + +```php +// getting value from request headers +$request->getHeaderLine('Content-Type'); // will return: "text/html; charset=UTF-8" +// getting value from response headers +$response->getHeaderLine('My-Custom-Header'); // will return: "My Custom Message; The second message" +``` + +#### Getting array of value from a header (also applies to request) +```php +// getting value from request headers +$request->getHeader('Content-Type'); // will return: ["text/html", "charset=UTF-8"] +// getting value from response headers +$response->getHeader('My-Custom-Header'); // will return: ["My Custom Message", "The second message"] +``` + +#### Removing headers from HTTP Messages +```php +// removing a header from Request, removing deprecated "Content-MD5" header +$request->withoutHeader('Content-MD5'); + +// removing a header from Response +// effect: the browser won't know the size of the stream +// the browser will download the stream till it ends +$response->withoutHeader('Content-Length'); +``` + +### Working with HTTP Message Body + +When working with the PSR-7 there are two methods of implementation: +#### 1. Getting the body separately + +> This method makes the body handling easier to understand and is useful when repeatedly calling body methods. (You only call `getBody()` once). Using this method mistakes like `$response->write()` are also prevented. + +```php +$body = $response->getBody(); +// operations on body, eg. read, write, seek +// ... +// replacing the old body +$response->withBody($body); +// this last statement is optional as we working with objects +// in this case the "new" body is same with the "old" one +// the $body variable has the same value as the one in $request, only the reference is passed +``` + +#### 2. Working directly on response + +> This method is useful when only performing few operations as the `$request->getBody()` statement fragment is required + +```php +$response->getBody()->write('hello'); +``` + +### Getting the body contents + +The following snippet gets the contents of a stream contents. +> Note: Streams must be rewinded, if content was written into streams, it will be ignored when calling `getContents()` because the stream pointer is set to the last character, which is `\0` - meaning end of stream. +```php +$body = $response->getBody(); +$body->rewind(); // or $body->seek(0); +$bodyText = $body->getContents(); +``` +> Note: If `$body->seek(1)` is called before `$body->getContents()`, the first character will be ommited as the starting pointer is set to `1`, not `0`. This is why using `$body->rewind()` is recommended. + +### Append to body + +```php +$response->getBody()->write('Hello'); // writing directly +$body = $request->getBody(); // which is a `StreamInterface` +$body->write('xxxxx'); +``` + +### Prepend to body +Prepending is different when it comes to streams. The content must be copied before writing the content to be prepended. +The following example will explain the behaviour of streams. + +```php +// assuming our response is initially empty +$body = $repsonse->getBody(); +// writing the string "abcd" +$body->write('abcd'); + +// seeking to start of stream +$body->seek(0); +// writing 'ef' +$body->write('ef'); // at this point the stream contains "efcd" +``` + +#### Prepending by rewriting separately + +```php +// assuming our response body stream only contains: "abcd" +$body = $response->getBody(); +$body->rewind(); +$contents = $body->getContents(); // abcd +// seeking the stream to beginning +$body->rewind(); +$body->write('ef'); // stream contains "efcd" +$body->write($contents); // stream contains "efabcd" +``` + +> Note: `getContents()` seeks the stream while reading it, therefore if the second `rewind()` method call was not present the stream would have resulted in `abcdefabcd` because the `write()` method appends to stream if not preceeded by `rewind()` or `seek(0)`. + +#### Prepending by using contents as a string +```php +$body = $response->getBody(); +$body->rewind(); +$contents = $body->getContents(); // efabcd +$contents = 'ef'.$contents; +$body->rewind(); +$body->write($contents); +``` diff --git a/vendor/psr/http-message/src/MessageInterface.php b/vendor/psr/http-message/src/MessageInterface.php new file mode 100644 index 0000000..a83c985 --- /dev/null +++ b/vendor/psr/http-message/src/MessageInterface.php @@ -0,0 +1,187 @@ +getHeaders() as $name => $values) { + * echo $name . ": " . implode(", ", $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @return string[][] Returns an associative array of the message's headers. Each + * key MUST be a header name, and each value MUST be an array of strings + * for that header. + */ + public function getHeaders(): array; + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name Case-insensitive header field name. + * @return bool Returns true if any header names match the given header + * name using a case-insensitive string comparison. Returns false if + * no matching header name is found in the message. + */ + public function hasHeader(string $name): bool; + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name Case-insensitive header field name. + * @return string[] An array of string values as provided for the given + * header. If the header does not appear in the message, this method MUST + * return an empty array. + */ + public function getHeader(string $name): array; + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name Case-insensitive header field name. + * @return string A string of values as provided for the given header + * concatenated together using a comma. If the header does not appear in + * the message, this method MUST return an empty string. + */ + public function getHeaderLine(string $name): string; + + /** + * Return an instance with the provided value replacing the specified header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string $name Case-insensitive header field name. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withHeader(string $name, $value): MessageInterface; + + /** + * Return an instance with the specified header appended with the given value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string $name Case-insensitive header field name to add. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withAddedHeader(string $name, $value): MessageInterface; + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name Case-insensitive header field name to remove. + * @return static + */ + public function withoutHeader(string $name): MessageInterface; + + /** + * Gets the body of the message. + * + * @return StreamInterface Returns the body as a stream. + */ + public function getBody(): StreamInterface; + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body Body. + * @return static + * @throws \InvalidArgumentException When the body is not valid. + */ + public function withBody(StreamInterface $body): MessageInterface; +} diff --git a/vendor/psr/http-message/src/RequestInterface.php b/vendor/psr/http-message/src/RequestInterface.php new file mode 100644 index 0000000..33f85e5 --- /dev/null +++ b/vendor/psr/http-message/src/RequestInterface.php @@ -0,0 +1,130 @@ +getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(): array; + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static + */ + public function withQueryParams(array $query): ServerRequestInterface; + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. + */ + public function getUploadedFiles(): array; + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. + */ + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface; + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + */ + public function getParsedBody(); + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. + */ + public function withParsedBody($data): ServerRequestInterface; + + /** + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. + */ + public function getAttributes(): array; + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed + */ + public function getAttribute(string $name, $default = null); + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static + */ + public function withAttribute(string $name, $value): ServerRequestInterface; + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute(string $name): ServerRequestInterface; +} diff --git a/vendor/psr/http-message/src/StreamInterface.php b/vendor/psr/http-message/src/StreamInterface.php new file mode 100644 index 0000000..a62aabb --- /dev/null +++ b/vendor/psr/http-message/src/StreamInterface.php @@ -0,0 +1,158 @@ + + * [user-info@]host[:port] + * + * + * If the port component is not set or is the standard port for the current + * scheme, it SHOULD NOT be included. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.2 + * @return string The URI authority, in "[user-info@]host[:port]" format. + */ + public function getAuthority(): string; + + /** + * Retrieve the user information component of the URI. + * + * If no user information is present, this method MUST return an empty + * string. + * + * If a user is present in the URI, this will return that value; + * additionally, if the password is also present, it will be appended to the + * user value, with a colon (":") separating the values. + * + * The trailing "@" character is not part of the user information and MUST + * NOT be added. + * + * @return string The URI user information, in "username[:password]" format. + */ + public function getUserInfo(): string; + + /** + * Retrieve the host component of the URI. + * + * If no host is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.2.2. + * + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @return string The URI host. + */ + public function getHost(): string; + + /** + * Retrieve the port component of the URI. + * + * If a port is present, and it is non-standard for the current scheme, + * this method MUST return it as an integer. If the port is the standard port + * used with the current scheme, this method SHOULD return null. + * + * If no port is present, and no scheme is present, this method MUST return + * a null value. + * + * If no port is present, but a scheme is present, this method MAY return + * the standard port for that scheme, but SHOULD return null. + * + * @return null|int The URI port. + */ + public function getPort(): ?int; + + /** + * Retrieve the path component of the URI. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * Normally, the empty path "" and absolute path "/" are considered equal as + * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically + * do this normalization because in contexts with a trimmed base path, e.g. + * the front controller, this difference becomes significant. It's the task + * of the user to handle both "" and "/". + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.3. + * + * As an example, if the value should include a slash ("/") not intended as + * delimiter between path segments, that value MUST be passed in encoded + * form (e.g., "%2F") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @return string The URI path. + */ + public function getPath(): string; + + /** + * Retrieve the query string of the URI. + * + * If no query string is present, this method MUST return an empty string. + * + * The leading "?" character is not part of the query and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.4. + * + * As an example, if a value in a key/value pair of the query string should + * include an ampersand ("&") not intended as a delimiter between values, + * that value MUST be passed in encoded form (e.g., "%26") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.4 + * @return string The URI query string. + */ + public function getQuery(): string; + + /** + * Retrieve the fragment component of the URI. + * + * If no fragment is present, this method MUST return an empty string. + * + * The leading "#" character is not part of the fragment and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.5. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.5 + * @return string The URI fragment. + */ + public function getFragment(): string; + + /** + * Return an instance with the specified scheme. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified scheme. + * + * Implementations MUST support the schemes "http" and "https" case + * insensitively, and MAY accommodate other schemes if required. + * + * An empty scheme is equivalent to removing the scheme. + * + * @param string $scheme The scheme to use with the new instance. + * @return static A new instance with the specified scheme. + * @throws \InvalidArgumentException for invalid or unsupported schemes. + */ + public function withScheme(string $scheme): UriInterface; + + /** + * Return an instance with the specified user information. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified user information. + * + * Password is optional, but the user information MUST include the + * user; an empty string for the user is equivalent to removing user + * information. + * + * @param string $user The user name to use for authority. + * @param null|string $password The password associated with $user. + * @return static A new instance with the specified user information. + */ + public function withUserInfo(string $user, ?string $password = null): UriInterface; + + /** + * Return an instance with the specified host. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified host. + * + * An empty host value is equivalent to removing the host. + * + * @param string $host The hostname to use with the new instance. + * @return static A new instance with the specified host. + * @throws \InvalidArgumentException for invalid hostnames. + */ + public function withHost(string $host): UriInterface; + + /** + * Return an instance with the specified port. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified port. + * + * Implementations MUST raise an exception for ports outside the + * established TCP and UDP port ranges. + * + * A null value provided for the port is equivalent to removing the port + * information. + * + * @param null|int $port The port to use with the new instance; a null value + * removes the port information. + * @return static A new instance with the specified port. + * @throws \InvalidArgumentException for invalid ports. + */ + public function withPort(?int $port): UriInterface; + + /** + * Return an instance with the specified path. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified path. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * If the path is intended to be domain-relative rather than path relative then + * it must begin with a slash ("/"). Paths not starting with a slash ("/") + * are assumed to be relative to some base path known to the application or + * consumer. + * + * Users can provide both encoded and decoded path characters. + * Implementations ensure the correct encoding as outlined in getPath(). + * + * @param string $path The path to use with the new instance. + * @return static A new instance with the specified path. + * @throws \InvalidArgumentException for invalid paths. + */ + public function withPath(string $path): UriInterface; + + /** + * Return an instance with the specified query string. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified query string. + * + * Users can provide both encoded and decoded query characters. + * Implementations ensure the correct encoding as outlined in getQuery(). + * + * An empty query string value is equivalent to removing the query string. + * + * @param string $query The query string to use with the new instance. + * @return static A new instance with the specified query string. + * @throws \InvalidArgumentException for invalid query strings. + */ + public function withQuery(string $query): UriInterface; + + /** + * Return an instance with the specified URI fragment. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified URI fragment. + * + * Users can provide both encoded and decoded fragment characters. + * Implementations ensure the correct encoding as outlined in getFragment(). + * + * An empty fragment value is equivalent to removing the fragment. + * + * @param string $fragment The fragment to use with the new instance. + * @return static A new instance with the specified fragment. + */ + public function withFragment(string $fragment): UriInterface; + + /** + * Return the string representation as a URI reference. + * + * Depending on which components of the URI are present, the resulting + * string is either a full URI or relative reference according to RFC 3986, + * Section 4.1. The method concatenates the various components of the URI, + * using the appropriate delimiters: + * + * - If a scheme is present, it MUST be suffixed by ":". + * - If an authority is present, it MUST be prefixed by "//". + * - The path can be concatenated without delimiters. But there are two + * cases where the path has to be adjusted to make the URI reference + * valid as PHP does not allow to throw an exception in __toString(): + * - If the path is rootless and an authority is present, the path MUST + * be prefixed by "/". + * - If the path is starting with more than one "/" and no authority is + * present, the starting slashes MUST be reduced to one. + * - If a query is present, it MUST be prefixed by "?". + * - If a fragment is present, it MUST be prefixed by "#". + * + * @see http://tools.ietf.org/html/rfc3986#section-4.1 + * @return string + */ + public function __toString(): string; +} diff --git a/vendor/psr/http-server-handler/LICENSE b/vendor/psr/http-server-handler/LICENSE new file mode 100644 index 0000000..b71ec5d --- /dev/null +++ b/vendor/psr/http-server-handler/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/psr/http-server-handler/README.md b/vendor/psr/http-server-handler/README.md new file mode 100644 index 0000000..111a9ed --- /dev/null +++ b/vendor/psr/http-server-handler/README.md @@ -0,0 +1,12 @@ +HTTP Server Request Handlers for Middleware +=========================================== + +This repository holds the `RequestHandlerInterface` related to [PSR-15 (HTTP Server Request Handlers)][psr-url]. + +Note that this is not a Server Request Handler implementation of its own. It is merely the interface that describe a Server Request Handler. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-15/ +[package-url]: https://packagist.org/packages/psr/http-server-handler +[implementation-url]: https://packagist.org/providers/psr/http-server-handler-implementation diff --git a/vendor/psr/http-server-handler/composer.json b/vendor/psr/http-server-handler/composer.json new file mode 100644 index 0000000..c54b2de --- /dev/null +++ b/vendor/psr/http-server-handler/composer.json @@ -0,0 +1,36 @@ +{ + "name": "psr/http-server-handler", + "description": "Common interface for HTTP server-side request handler", + "keywords": [ + "psr", + "psr-7", + "psr-15", + "http-interop", + "http", + "server", + "handler", + "request", + "response" + ], + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=7.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Server\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/vendor/psr/http-server-handler/src/RequestHandlerInterface.php b/vendor/psr/http-server-handler/src/RequestHandlerInterface.php new file mode 100644 index 0000000..83911e2 --- /dev/null +++ b/vendor/psr/http-server-handler/src/RequestHandlerInterface.php @@ -0,0 +1,22 @@ +=7.0", + "psr/http-message": "^1.0 || ^2.0", + "psr/http-server-handler": "^1.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Server\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/vendor/psr/http-server-middleware/src/MiddlewareInterface.php b/vendor/psr/http-server-middleware/src/MiddlewareInterface.php new file mode 100644 index 0000000..a6c14f8 --- /dev/null +++ b/vendor/psr/http-server-middleware/src/MiddlewareInterface.php @@ -0,0 +1,25 @@ +logger = $logger; + } + + public function doSomething() + { + if ($this->logger) { + $this->logger->info('Doing work'); + } + + try { + $this->doSomethingElse(); + } catch (Exception $exception) { + $this->logger->error('Oh no!', array('exception' => $exception)); + } + + // do something useful + } +} +``` + +You can then pick one of the implementations of the interface to get a logger. + +If you want to implement the interface, you can require this package and +implement `Psr\Log\LoggerInterface` in your code. Please read the +[specification text](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) +for details. diff --git a/vendor/psr/log/composer.json b/vendor/psr/log/composer.json new file mode 100644 index 0000000..879fc6f --- /dev/null +++ b/vendor/psr/log/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/log", + "description": "Common interface for logging libraries", + "keywords": ["psr", "psr-3", "log"], + "homepage": "https://github.com/php-fig/log", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=8.0.0" + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + } +} diff --git a/vendor/psr/log/src/AbstractLogger.php b/vendor/psr/log/src/AbstractLogger.php new file mode 100644 index 0000000..d60a091 --- /dev/null +++ b/vendor/psr/log/src/AbstractLogger.php @@ -0,0 +1,15 @@ +logger = $logger; + } +} diff --git a/vendor/psr/log/src/LoggerInterface.php b/vendor/psr/log/src/LoggerInterface.php new file mode 100644 index 0000000..cb4cf64 --- /dev/null +++ b/vendor/psr/log/src/LoggerInterface.php @@ -0,0 +1,98 @@ +log(LogLevel::EMERGENCY, $message, $context); + } + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + */ + public function alert(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ALERT, $message, $context); + } + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + */ + public function critical(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::CRITICAL, $message, $context); + } + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + */ + public function error(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ERROR, $message, $context); + } + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + */ + public function warning(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::WARNING, $message, $context); + } + + /** + * Normal but significant events. + */ + public function notice(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::NOTICE, $message, $context); + } + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + */ + public function info(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::INFO, $message, $context); + } + + /** + * Detailed debug information. + */ + public function debug(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::DEBUG, $message, $context); + } + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * + * @throws \Psr\Log\InvalidArgumentException + */ + abstract public function log($level, string|\Stringable $message, array $context = []): void; +} diff --git a/vendor/psr/log/src/NullLogger.php b/vendor/psr/log/src/NullLogger.php new file mode 100644 index 0000000..de0561e --- /dev/null +++ b/vendor/psr/log/src/NullLogger.php @@ -0,0 +1,26 @@ +logger) { }` + * blocks. + */ +class NullLogger extends AbstractLogger +{ + /** + * Logs with an arbitrary level. + * + * @param mixed[] $context + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, string|\Stringable $message, array $context = []): void + { + // noop + } +} diff --git a/vendor/ralouphie/getallheaders/LICENSE b/vendor/ralouphie/getallheaders/LICENSE new file mode 100644 index 0000000..be5540c --- /dev/null +++ b/vendor/ralouphie/getallheaders/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ralph Khattar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/ralouphie/getallheaders/README.md b/vendor/ralouphie/getallheaders/README.md new file mode 100644 index 0000000..9430d76 --- /dev/null +++ b/vendor/ralouphie/getallheaders/README.md @@ -0,0 +1,27 @@ +getallheaders +============= + +PHP `getallheaders()` polyfill. Compatible with PHP >= 5.3. + +[![Build Status](https://travis-ci.org/ralouphie/getallheaders.svg?branch=master)](https://travis-ci.org/ralouphie/getallheaders) +[![Coverage Status](https://coveralls.io/repos/ralouphie/getallheaders/badge.png?branch=master)](https://coveralls.io/r/ralouphie/getallheaders?branch=master) +[![Latest Stable Version](https://poser.pugx.org/ralouphie/getallheaders/v/stable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![Latest Unstable Version](https://poser.pugx.org/ralouphie/getallheaders/v/unstable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![License](https://poser.pugx.org/ralouphie/getallheaders/license.png)](https://packagist.org/packages/ralouphie/getallheaders) + + +This is a simple polyfill for [`getallheaders()`](http://www.php.net/manual/en/function.getallheaders.php). + +## Install + +For PHP version **`>= 5.6`**: + +``` +composer require ralouphie/getallheaders +``` + +For PHP version **`< 5.6`**: + +``` +composer require ralouphie/getallheaders "^2" +``` diff --git a/vendor/ralouphie/getallheaders/composer.json b/vendor/ralouphie/getallheaders/composer.json new file mode 100644 index 0000000..de8ce62 --- /dev/null +++ b/vendor/ralouphie/getallheaders/composer.json @@ -0,0 +1,26 @@ +{ + "name": "ralouphie/getallheaders", + "description": "A polyfill for getallheaders.", + "license": "MIT", + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "require": { + "php": ">=5.6" + }, + "require-dev": { + "phpunit/phpunit": "^5 || ^6.5", + "php-coveralls/php-coveralls": "^2.1" + }, + "autoload": { + "files": ["src/getallheaders.php"] + }, + "autoload-dev": { + "psr-4": { + "getallheaders\\Tests\\": "tests/" + } + } +} diff --git a/vendor/ralouphie/getallheaders/src/getallheaders.php b/vendor/ralouphie/getallheaders/src/getallheaders.php new file mode 100644 index 0000000..c7285a5 --- /dev/null +++ b/vendor/ralouphie/getallheaders/src/getallheaders.php @@ -0,0 +1,46 @@ + 'Content-Type', + 'CONTENT_LENGTH' => 'Content-Length', + 'CONTENT_MD5' => 'Content-Md5', + ); + + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) === 'HTTP_') { + $key = substr($key, 5); + if (!isset($copy_server[$key]) || !isset($_SERVER[$key])) { + $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $key)))); + $headers[$key] = $value; + } + } elseif (isset($copy_server[$key])) { + $headers[$copy_server[$key]] = $value; + } + } + + if (!isset($headers['Authorization'])) { + if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + } elseif (isset($_SERVER['PHP_AUTH_USER'])) { + $basic_pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; + $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $basic_pass); + } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { + $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; + } + } + + return $headers; + } + +} diff --git a/vendor/slim/psr7/LICENSE.md b/vendor/slim/psr7/LICENSE.md new file mode 100644 index 0000000..2bd2d5a --- /dev/null +++ b/vendor/slim/psr7/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Slim Framework + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/vendor/slim/psr7/composer.json b/vendor/slim/psr7/composer.json new file mode 100644 index 0000000..02976cf --- /dev/null +++ b/vendor/slim/psr7/composer.json @@ -0,0 +1,82 @@ +{ + "name": "slim/psr7", + "type": "library", + "description": "Strict PSR-7 implementation", + "keywords": ["psr7","psr-7","http"], + "homepage": "https://www.slimframework.com", + "license": "MIT", + "authors": [ + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "http://joshlockhart.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" + }, + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, + { + "name": "Pierre Berube", + "email": "pierre@lgse.com", + "homepage": "http://www.lgse.com" + } + ], + "require": { + "php": "^8.0", + "fig/http-message-util": "^1.1.5", + "psr/http-factory": "^1.1", + "psr/http-message": "^1.0 || ^2.0", + "ralouphie/getallheaders": "^3.0", + "symfony/polyfill-php80": "^1.29" + }, + "require-dev": { + "ext-json": "*", + "adriansuter/php-autoload-override": "^1.4", + "http-interop/http-factory-tests": "^1.1.0", + "php-http/psr7-integration-tests": "1.3.0", + "phpspec/prophecy": "^1.19", + "phpspec/prophecy-phpunit": "^2.2", + "phpstan/phpstan": "^1.11", + "phpunit/phpunit": "^9.6", + "squizlabs/php_codesniffer": "^3.10" + }, + "provide": { + "psr/http-message-implementation": "^1.0 || ^2.0", + "psr/http-factory-implementation": "^1.0" + }, + "autoload": { + "psr-4": { + "Slim\\Psr7\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Slim\\Tests\\Psr7\\": "tests" + } + }, + "scripts": { + "test": [ + "@phpunit", + "@phpcs", + "@phpstan" + ], + "phpunit": "phpunit", + "phpcs": "phpcs", + "phpstan": "phpstan --memory-limit=-1" + }, + "config": { + "sort-packages": true + }, + "archive": { + "exclude": [ + "/tests", + "/phpunit.xml.dist" + ] + } +} diff --git a/vendor/slim/psr7/phpunit.xml.dist b/vendor/slim/psr7/phpunit.xml.dist new file mode 100644 index 0000000..a65dc57 --- /dev/null +++ b/vendor/slim/psr7/phpunit.xml.dist @@ -0,0 +1,23 @@ + + + + + tests + + + + + + src + + + + + + diff --git a/vendor/slim/psr7/src/Cookies.php b/vendor/slim/psr7/src/Cookies.php new file mode 100644 index 0000000..044d438 --- /dev/null +++ b/vendor/slim/psr7/src/Cookies.php @@ -0,0 +1,218 @@ + '', + 'domain' => null, + 'hostonly' => null, + 'path' => null, + 'expires' => null, + 'secure' => false, + 'httponly' => false, + 'samesite' => null + ]; + + /** + * @param array $cookies + */ + public function __construct(array $cookies = []) + { + $this->requestCookies = $cookies; + } + + /** + * Set default cookie properties + * + * @param array $settings + * + * @return static + */ + public function setDefaults(array $settings): self + { + $this->defaults = array_replace($this->defaults, $settings); + + return $this; + } + + /** + * Get cookie + * + * @param string $name + * @param string|array|null $default + * @return mixed|null + */ + public function get(string $name, $default = null) + { + return array_key_exists($name, $this->requestCookies) ? $this->requestCookies[$name] : $default; + } + + /** + * Set cookie + * + * @param string $name + * @param string|array $value + * @return static + */ + public function set(string $name, $value): self + { + if (!is_array($value)) { + $value = ['value' => $value]; + } + + $this->responseCookies[$name] = array_replace($this->defaults, $value); + + return $this; + } + + /** + * Convert all response cookies into an associate array of header values + * + * @return array + */ + public function toHeaders(): array + { + $headers = []; + + foreach ($this->responseCookies as $name => $properties) { + $headers[] = $this->toHeader($name, $properties); + } + + return $headers; + } + + /** + * Convert to `Set-Cookie` header + * + * @param string $name Cookie name + * @param array $properties Cookie properties + * + * @return string + */ + protected function toHeader(string $name, array $properties): string + { + $result = urlencode($name) . '=' . urlencode($properties['value']); + + if (isset($properties['domain'])) { + $result .= '; domain=' . $properties['domain']; + } + + if (isset($properties['path'])) { + $result .= '; path=' . $properties['path']; + } + + if (isset($properties['expires'])) { + if (is_string($properties['expires'])) { + $timestamp = strtotime($properties['expires']); + } else { + $timestamp = (int) $properties['expires']; + } + if ($timestamp && $timestamp !== 0) { + $result .= '; expires=' . gmdate('D, d-M-Y H:i:s e', $timestamp); + } + } + + if (isset($properties['secure']) && $properties['secure']) { + $result .= '; secure'; + } + + if (isset($properties['hostonly']) && $properties['hostonly']) { + $result .= '; HostOnly'; + } + + if (isset($properties['httponly']) && $properties['httponly']) { + $result .= '; HttpOnly'; + } + + if ( + isset($properties['samesite']) + && in_array(strtolower($properties['samesite']), ['lax', 'strict', 'none'], true) + ) { + // While strtolower is needed for correct comparison, the RFC doesn't care about case + $result .= '; SameSite=' . $properties['samesite']; + } + + return $result; + } + + /** + * Parse cookie values from header value + * + * Returns an associative array of cookie names and values + * + * @param string|array $header + * + * @return array + */ + public static function parseHeader($header): array + { + if (is_array($header)) { + $header = $header[0] ?? ''; + } + + if (!is_string($header)) { + throw new InvalidArgumentException('Cannot parse Cookie data. Header value must be a string.'); + } + + $header = rtrim($header, "\r\n"); + $pieces = preg_split('@[;]\s*@', $header); + $cookies = []; + + if (is_array($pieces)) { + foreach ($pieces as $cookie) { + $cookie = explode('=', $cookie, 2); + + if (count($cookie) === 2) { + $key = urldecode($cookie[0]); + $value = urldecode($cookie[1]); + + if (!isset($cookies[$key])) { + $cookies[$key] = $value; + } + } + } + } + + return $cookies; + } +} diff --git a/vendor/slim/psr7/src/Environment.php b/vendor/slim/psr7/src/Environment.php new file mode 100644 index 0000000..55f187b --- /dev/null +++ b/vendor/slim/psr7/src/Environment.php @@ -0,0 +1,55 @@ + 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', + 'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8', + 'HTTP_USER_AGENT' => 'Slim Framework', + 'QUERY_STRING' => '', + 'REMOTE_ADDR' => '127.0.0.1', + 'REQUEST_METHOD' => 'GET', + 'REQUEST_SCHEME' => $scheme, + 'REQUEST_TIME' => time(), + 'REQUEST_TIME_FLOAT' => microtime(true), + 'REQUEST_URI' => '', + 'SCRIPT_NAME' => '', + 'SERVER_NAME' => 'localhost', + 'SERVER_PORT' => $port, + 'SERVER_PROTOCOL' => 'HTTP/1.1', + ], $data); + } +} diff --git a/vendor/slim/psr7/src/Factory/RequestFactory.php b/vendor/slim/psr7/src/Factory/RequestFactory.php new file mode 100644 index 0000000..e825ee3 --- /dev/null +++ b/vendor/slim/psr7/src/Factory/RequestFactory.php @@ -0,0 +1,59 @@ +streamFactory = $streamFactory ?? new StreamFactory(); + $this->uriFactory = $uriFactory ?? new UriFactory(); + } + + /** + * {@inheritdoc} + */ + public function createRequest(string $method, $uri): RequestInterface + { + if (is_string($uri)) { + $uri = $this->uriFactory->createUri($uri); + } + + if (!$uri instanceof UriInterface) { + throw new InvalidArgumentException( + 'Parameter 2 of RequestFactory::createRequest() must be a string or a compatible UriInterface.' + ); + } + + $body = $this->streamFactory->createStream(); + + return new Request($method, $uri, new Headers(), [], [], $body); + } +} diff --git a/vendor/slim/psr7/src/Factory/ResponseFactory.php b/vendor/slim/psr7/src/Factory/ResponseFactory.php new file mode 100644 index 0000000..c1a23a7 --- /dev/null +++ b/vendor/slim/psr7/src/Factory/ResponseFactory.php @@ -0,0 +1,35 @@ +withStatus($code, $reasonPhrase); + } + + return $res; + } +} diff --git a/vendor/slim/psr7/src/Factory/ServerRequestFactory.php b/vendor/slim/psr7/src/Factory/ServerRequestFactory.php new file mode 100644 index 0000000..5bc2447 --- /dev/null +++ b/vendor/slim/psr7/src/Factory/ServerRequestFactory.php @@ -0,0 +1,110 @@ +streamFactory = $streamFactory ?? new StreamFactory(); + $this->uriFactory = $uriFactory ?? new UriFactory(); + } + + /** + * {@inheritdoc} + */ + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface + { + if (is_string($uri)) { + $uri = $this->uriFactory->createUri($uri); + } + + if (!$uri instanceof UriInterface) { + throw new InvalidArgumentException('URI must either be string or instance of ' . UriInterface::class); + } + + $body = $this->streamFactory->createStream(); + $headers = new Headers(); + $cookies = []; + + if (!empty($serverParams)) { + $headers = Headers::createFromGlobals(); + $cookies = Cookies::parseHeader($headers->getHeader('Cookie', [])); + } + + return new Request($method, $uri, $headers, $cookies, $serverParams, $body); + } + + /** + * Create new ServerRequest from environment. + * + * @internal This method is not part of PSR-17 + * + * @return Request + */ + public static function createFromGlobals(): Request + { + $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; + $uri = (new UriFactory())->createFromGlobals($_SERVER); + + $headers = Headers::createFromGlobals(); + $cookies = Cookies::parseHeader($headers->getHeader('Cookie', [])); + + // Cache the php://input stream as it cannot be re-read + $cacheResource = fopen('php://temp', 'wb+'); + $cache = $cacheResource ? new Stream($cacheResource) : null; + + $body = (new StreamFactory())->createStreamFromFile('php://input', 'r', $cache); + $uploadedFiles = UploadedFile::createFromGlobals($_SERVER); + + $request = new Request($method, $uri, $headers, $cookies, $_SERVER, $body, $uploadedFiles); + $contentTypes = $request->getHeader('Content-Type'); + + $parsedContentType = ''; + foreach ($contentTypes as $contentType) { + $fragments = explode(';', $contentType); + $parsedContentType = current($fragments); + } + + $contentTypesWithParsedBodies = ['application/x-www-form-urlencoded', 'multipart/form-data']; + if ($method === 'POST' && in_array($parsedContentType, $contentTypesWithParsedBodies)) { + return $request->withParsedBody($_POST); + } + + return $request; + } +} diff --git a/vendor/slim/psr7/src/Factory/StreamFactory.php b/vendor/slim/psr7/src/Factory/StreamFactory.php new file mode 100644 index 0000000..04d22a1 --- /dev/null +++ b/vendor/slim/psr7/src/Factory/StreamFactory.php @@ -0,0 +1,95 @@ +createStreamFromResource($resource); + } + + /** + * {@inheritdoc} + */ + public function createStreamFromFile( + string $filename, + string $mode = 'r', + ?StreamInterface $cache = null + ): StreamInterface { + set_error_handler( + static function (int $errno, string $errstr) use ($filename, $mode): void { + throw new RuntimeException( + "Unable to open $filename using mode $mode: $errstr", + $errno + ); + } + ); + + try { + $resource = fopen($filename, $mode); + } catch (ValueError $exception) { + throw new RuntimeException("Unable to open $filename using mode $mode: " . $exception->getMessage()); + } finally { + restore_error_handler(); + } + + if (!is_resource($resource)) { + throw new RuntimeException( + "StreamFactory::createStreamFromFile() could not create resource from file `$filename`" + ); + } + + return new Stream($resource, $cache); + } + + /** + * {@inheritdoc} + */ + public function createStreamFromResource($resource, ?StreamInterface $cache = null): StreamInterface + { + if (!is_resource($resource)) { + throw new InvalidArgumentException( + 'Parameter 1 of StreamFactory::createStreamFromResource() must be a resource.' + ); + } + + return new Stream($resource, $cache); + } +} diff --git a/vendor/slim/psr7/src/Factory/UploadedFileFactory.php b/vendor/slim/psr7/src/Factory/UploadedFileFactory.php new file mode 100644 index 0000000..5699e96 --- /dev/null +++ b/vendor/slim/psr7/src/Factory/UploadedFileFactory.php @@ -0,0 +1,47 @@ +getMetadata('uri'); + + if (!is_string($file) || !$stream->isReadable()) { + throw new InvalidArgumentException('File is not readable.'); + } + + if ($size === null) { + $size = $stream->getSize(); + } + + return new UploadedFile($stream, $clientFilename, $clientMediaType, $size, $error); + } +} diff --git a/vendor/slim/psr7/src/Factory/UriFactory.php b/vendor/slim/psr7/src/Factory/UriFactory.php new file mode 100644 index 0000000..74ab377 --- /dev/null +++ b/vendor/slim/psr7/src/Factory/UriFactory.php @@ -0,0 +1,113 @@ + 1) { + $queryString = parse_url('https://www.example.com' . $globals['REQUEST_URI'], PHP_URL_QUERY) ?? ''; + } + } + + // Build Uri and return + return new Uri($scheme, $host, $port, $requestUri, $queryString, '', $username, $password); + } +} diff --git a/vendor/slim/psr7/src/Header.php b/vendor/slim/psr7/src/Header.php new file mode 100644 index 0000000..ef9e196 --- /dev/null +++ b/vendor/slim/psr7/src/Header.php @@ -0,0 +1,63 @@ +originalName = $originalName; + $this->normalizedName = $normalizedName; + $this->values = $values; + } + + public function getOriginalName(): string + { + return $this->originalName; + } + + public function getNormalizedName(): string + { + return $this->normalizedName; + } + + public function addValue(string $value): self + { + $this->values[] = $value; + + return $this; + } + + public function addValues(array|string $values): self + { + if (is_string($values)) { + return $this->addValue($values); + } + + $this->values = array_merge($this->values, $values); + + return $this; + } + + public function getValues(): array + { + return $this->values; + } +} diff --git a/vendor/slim/psr7/src/Headers.php b/vendor/slim/psr7/src/Headers.php new file mode 100644 index 0000000..e413147 --- /dev/null +++ b/vendor/slim/psr7/src/Headers.php @@ -0,0 +1,318 @@ +globals = $globals ?? $_SERVER; + $this->setHeaders($headers); + } + + /** + * {@inheritdoc} + */ + public function addHeader($name, $value): HeadersInterface + { + [$values, $originalName, $normalizedName] = $this->prepareHeader($name, $value); + + if (isset($this->headers[$normalizedName])) { + $header = $this->headers[$normalizedName]; + $header->addValues($values); + } else { + $this->headers[$normalizedName] = new Header($originalName, $normalizedName, $values); + } + + return $this; + } + + /** + * {@inheritdoc} + */ + public function removeHeader(string $name): HeadersInterface + { + $name = $this->normalizeHeaderName($name); + unset($this->headers[$name]); + return $this; + } + + /** + * {@inheritdoc} + */ + public function getHeader(string $name, $default = []): array + { + $name = $this->normalizeHeaderName($name); + + if (isset($this->headers[$name])) { + $header = $this->headers[$name]; + return $header->getValues(); + } + + if (empty($default)) { + return $default; + } + + $this->validateHeader($name, $default); + return $this->trimHeaderValue($default); + } + + /** + * {@inheritdoc} + */ + public function setHeader($name, $value): HeadersInterface + { + [$values, $originalName, $normalizedName] = $this->prepareHeader($name, $value); + + // Ensure we preserve original case if the header already exists in the stack + if (isset($this->headers[$normalizedName])) { + $existingHeader = $this->headers[$normalizedName]; + $originalName = $existingHeader->getOriginalName(); + } + + $this->headers[$normalizedName] = new Header($originalName, $normalizedName, $values); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function setHeaders(array $headers): HeadersInterface + { + $this->headers = []; + + foreach ($this->parseAuthorizationHeader($headers) as $name => $value) { + $this->addHeader($name, $value); + } + + return $this; + } + + /** + * {@inheritdoc} + */ + public function hasHeader(string $name): bool + { + $name = $this->normalizeHeaderName($name); + return isset($this->headers[$name]); + } + + /** + * {@inheritdoc} + */ + public function getHeaders(bool $originalCase = false): array + { + $headers = []; + + foreach ($this->headers as $header) { + $name = $originalCase ? $header->getOriginalName() : $header->getNormalizedName(); + $headers[$name] = $header->getValues(); + } + + return $headers; + } + + /** + * @param string $name + * @param bool $preserveCase + * @return string + */ + protected function normalizeHeaderName(string $name, bool $preserveCase = false): string + { + $name = strtr($name, '_', '-'); + + if (!$preserveCase) { + $name = strtolower($name); + } + + if (strpos(strtolower($name), 'http-') === 0) { + $name = substr($name, 5); + } + + return $name; + } + + /** + * Parse incoming headers and determine Authorization header from original headers + * + * @param array $headers + * @return array + */ + protected function parseAuthorizationHeader(array $headers): array + { + $hasAuthorizationHeader = false; + foreach ($headers as $name => $value) { + if (strtolower((string) $name) === 'authorization') { + $hasAuthorizationHeader = true; + break; + } + } + + if (!$hasAuthorizationHeader) { + if (isset($this->globals['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['Authorization'] = $this->globals['REDIRECT_HTTP_AUTHORIZATION']; + } elseif (isset($this->globals['PHP_AUTH_USER'])) { + $pw = $this->globals['PHP_AUTH_PW'] ?? ''; + $headers['Authorization'] = 'Basic ' . base64_encode($this->globals['PHP_AUTH_USER'] . ':' . $pw); + } elseif (isset($this->globals['PHP_AUTH_DIGEST'])) { + $headers['Authorization'] = $this->globals['PHP_AUTH_DIGEST']; + } + } + + return $headers; + } + + /** + * @param array|string $value + * + * @return array + */ + protected function trimHeaderValue($value): array + { + $items = is_array($value) ? $value : [$value]; + $result = []; + foreach ($items as $item) { + $result[] = trim((string) $item, " \t"); + } + return $result; + } + + /** + * @param string $name + * @param array|string $value + * + * @throws InvalidArgumentException + * + * @return array + */ + protected function prepareHeader($name, $value): array + { + $this->validateHeader($name, $value); + $values = $this->trimHeaderValue($value); + $originalName = $this->normalizeHeaderName($name, true); + $normalizedName = $this->normalizeHeaderName($name); + return [$values, $originalName, $normalizedName]; + } + + /** + * Make sure the header complies with RFC 7230. + * + * Header names must be a non-empty string consisting of token characters. + * + * Header values must be strings consisting of visible characters with all optional + * leading and trailing whitespace stripped. This method will always strip such + * optional whitespace. Note that the method does not allow folding whitespace within + * the values as this was deprecated for almost all instances by the RFC. + * + * header-field = field-name ":" OWS field-value OWS + * field-name = 1*( "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^" + * / "_" / "`" / "|" / "~" / %x30-39 / ( %x41-5A / %x61-7A ) ) + * OWS = *( SP / HTAB ) + * field-value = *( ( %x21-7E / %x80-FF ) [ 1*( SP / HTAB ) ( %x21-7E / %x80-FF ) ] ) + * + * @see https://tools.ietf.org/html/rfc7230#section-3.2.4 + * + * @param string $name + * @param array|string $value + * + * @throws InvalidArgumentException; + */ + protected function validateHeader($name, $value): void + { + $this->validateHeaderName($name); + $this->validateHeaderValue($value); + } + + /** + * @param mixed $name + * + * @throws InvalidArgumentException + */ + protected function validateHeaderName($name): void + { + if (!is_string($name) || preg_match("@^[!#$%&'*+.^_`|~0-9A-Za-z-]+$@D", $name) !== 1) { + throw new InvalidArgumentException('Header name must be an RFC 7230 compatible string.'); + } + } + + /** + * @param mixed $value + * + * @throws InvalidArgumentException + */ + protected function validateHeaderValue($value): void + { + $items = is_array($value) ? $value : [$value]; + + if (empty($items)) { + throw new InvalidArgumentException( + 'Header values must be a string or an array of strings, empty array given.' + ); + } + + $pattern = "@^[ \t\x21-\x7E\x80-\xFF]*$@D"; + foreach ($items as $item) { + $hasInvalidType = !is_numeric($item) && !is_string($item); + $rejected = $hasInvalidType || preg_match($pattern, (string) $item) !== 1; + if ($rejected) { + throw new InvalidArgumentException( + 'Header values must be RFC 7230 compatible strings.' + ); + } + } + } + + /** + * @return static + */ + public static function createFromGlobals() + { + $headers = null; + + if (function_exists('getallheaders')) { + $headers = getallheaders(); + } + + if (!is_array($headers)) { + $headers = []; + } + + return new static($headers); + } +} diff --git a/vendor/slim/psr7/src/Interfaces/HeadersInterface.php b/vendor/slim/psr7/src/Interfaces/HeadersInterface.php new file mode 100644 index 0000000..3f486f1 --- /dev/null +++ b/vendor/slim/psr7/src/Interfaces/HeadersInterface.php @@ -0,0 +1,90 @@ + true, + '1.1' => true, + '2.0' => true, + '2' => true, + ]; + + /** + * @var HeadersInterface + */ + protected $headers; + + /** + * @var StreamInterface + */ + protected $body; + + /** + * Disable magic setter to ensure immutability + * + * @param string $name The property name + * @param mixed $value The property value + * + * @return void + */ + public function __set($name, $value): void + { + // Do nothing + } + + /** + * {@inheritdoc} + */ + public function getProtocolVersion(): string + { + return $this->protocolVersion; + } + + /** + * @return static + * {@inheritdoc} + */ + public function withProtocolVersion($version): MessageInterface + { + if (!isset(self::$validProtocolVersions[$version])) { + throw new InvalidArgumentException( + 'Invalid HTTP version. Must be one of: ' + . implode(', ', array_keys(self::$validProtocolVersions)) + ); + } + + $clone = clone $this; + $clone->protocolVersion = $version; + + return $clone; + } + + /** + * {@inheritdoc} + */ + public function getHeaders(): array + { + return $this->headers->getHeaders(true); + } + + /** + * {@inheritdoc} + */ + public function hasHeader($name): bool + { + return $this->headers->hasHeader($name); + } + + /** + * {@inheritdoc} + */ + public function getHeader($name): array + { + return $this->headers->getHeader($name); + } + + /** + * {@inheritdoc} + */ + public function getHeaderLine($name): string + { + $values = $this->headers->getHeader($name); + return implode(',', $values); + } + + /** + * @return static + * {@inheritdoc} + */ + public function withHeader($name, $value): MessageInterface + { + $clone = clone $this; + $clone->headers->setHeader($name, $value); + + if ($this instanceof Response && $this->body instanceof NonBufferedBody) { + header(sprintf('%s: %s', $name, $clone->getHeaderLine($name))); + } + + return $clone; + } + + /** + * @return static + * {@inheritdoc} + */ + public function withAddedHeader($name, $value): MessageInterface + { + $clone = clone $this; + $clone->headers->addHeader($name, $value); + + if ($this instanceof Response && $this->body instanceof NonBufferedBody) { + header(sprintf('%s: %s', $name, $clone->getHeaderLine($name))); + } + + return $clone; + } + + /** + * @return static + * {@inheritdoc} + */ + public function withoutHeader($name): MessageInterface + { + $clone = clone $this; + $clone->headers->removeHeader($name); + + if ($this instanceof Response && $this->body instanceof NonBufferedBody) { + header_remove($name); + } + + return $clone; + } + + /** + * {@inheritdoc} + */ + public function getBody(): StreamInterface + { + return $this->body; + } + + /** + * @return static + * {@inheritdoc} + */ + public function withBody(StreamInterface $body): MessageInterface + { + $clone = clone $this; + $clone->body = $body; + + return $clone; + } +} diff --git a/vendor/slim/psr7/src/NonBufferedBody.php b/vendor/slim/psr7/src/NonBufferedBody.php new file mode 100644 index 0000000..ad22c2d --- /dev/null +++ b/vendor/slim/psr7/src/NonBufferedBody.php @@ -0,0 +1,153 @@ +method = $this->filterMethod($method); + $this->uri = $uri; + $this->headers = $headers; + $this->cookies = $cookies; + $this->serverParams = $serverParams; + $this->attributes = []; + $this->body = $body; + $this->uploadedFiles = $uploadedFiles; + + if (isset($serverParams['SERVER_PROTOCOL'])) { + $this->protocolVersion = str_replace('HTTP/', '', $serverParams['SERVER_PROTOCOL']); + } + + if (!$this->headers->hasHeader('Host') || $this->uri->getHost() !== '') { + $this->headers->setHeader('Host', $this->uri->getHost()); + } + } + + /** + * This method is applied to the cloned object after PHP performs an initial shallow-copy. + * This method completes a deep-copy by creating new objects for the cloned object's internal reference pointers. + */ + public function __clone() + { + $this->headers = clone $this->headers; + $this->body = clone $this->body; + } + + /** + * {@inheritdoc} + */ + public function getMethod(): string + { + return $this->method; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withMethod($method): RequestInterface + { + $method = $this->filterMethod($method); + $clone = clone $this; + $clone->method = $method; + + return $clone; + } + + /** + * Validate the HTTP method + * + * @param string $method + * + * @return string + * + * @throws InvalidArgumentException on invalid HTTP method. + */ + protected function filterMethod($method): string + { + /** @var mixed $method */ + if (!is_string($method)) { + throw new InvalidArgumentException(sprintf( + 'Unsupported HTTP method; must be a string, received %s', + (is_object($method) ? get_class($method) : gettype($method)) + )); + } + + if (preg_match("/^[!#$%&'*+.^_`|~0-9a-z-]+$/i", $method) !== 1) { + throw new InvalidArgumentException(sprintf( + 'Unsupported HTTP method "%s" provided', + $method + )); + } + + return $method; + } + + /** + * {@inheritdoc} + */ + public function getRequestTarget(): string + { + if ($this->requestTarget) { + return $this->requestTarget; + } + + if ($this->uri === null) { + return '/'; + } + + $path = $this->uri->getPath(); + $path = '/' . ltrim($path, '/'); + + $query = $this->uri->getQuery(); + if ($query) { + $path .= '?' . $query; + } + + return $path; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withRequestTarget($requestTarget): RequestInterface + { + if (!is_string($requestTarget) || preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; must be a string and cannot contain whitespace' + ); + } + + $clone = clone $this; + $clone->requestTarget = $requestTarget; + + return $clone; + } + + /** + * {@inheritdoc} + */ + public function getUri(): UriInterface + { + return $this->uri; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withUri(UriInterface $uri, $preserveHost = false): RequestInterface + { + $clone = clone $this; + $clone->uri = $uri; + + if (!$preserveHost && $uri->getHost() !== '') { + $clone->headers->setHeader('Host', $uri->getHost()); + return $clone; + } + + if (($uri->getHost() !== '' && !$this->hasHeader('Host') || $this->getHeaderLine('Host') === '')) { + $clone->headers->setHeader('Host', $uri->getHost()); + return $clone; + } + + return $clone; + } + + /** + * {@inheritdoc} + */ + public function getCookieParams(): array + { + return $this->cookies; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withCookieParams(array $cookies): ServerRequestInterface + { + $clone = clone $this; + $clone->cookies = $cookies; + + return $clone; + } + + /** + * {@inheritdoc} + */ + public function getQueryParams(): array + { + if (is_array($this->queryParams)) { + return $this->queryParams; + } + + if ($this->uri === null) { + return []; + } + + // Decode URL data + parse_str($this->uri->getQuery(), $this->queryParams); + + return is_array($this->queryParams) ? $this->queryParams : []; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withQueryParams(array $query): ServerRequestInterface + { + $clone = clone $this; + $clone->queryParams = $query; + + return $clone; + } + + /** + * {@inheritdoc} + */ + public function getUploadedFiles(): array + { + return $this->uploadedFiles; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface + { + $clone = clone $this; + $clone->uploadedFiles = $uploadedFiles; + + return $clone; + } + + /** + * {@inheritdoc} + */ + public function getServerParams(): array + { + return $this->serverParams; + } + + /** + * {@inheritdoc} + */ + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * {@inheritdoc} + * @return mixed + */ + public function getAttribute($name, $default = null) + { + return $this->attributes[$name] ?? $default; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withAttribute($name, $value): ServerRequestInterface + { + $clone = clone $this; + $clone->attributes[$name] = $value; + + return $clone; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withoutAttribute($name): ServerRequestInterface + { + $clone = clone $this; + + unset($clone->attributes[$name]); + + return $clone; + } + + /** + * {@inheritdoc} + */ + public function getParsedBody() + { + return $this->parsedBody; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withParsedBody($data): ServerRequestInterface + { + /** @var mixed $data */ + if (!is_null($data) && !is_object($data) && !is_array($data)) { + throw new InvalidArgumentException('Parsed body value must be an array, an object, or null'); + } + + $clone = clone $this; + $clone->parsedBody = $data; + + return $clone; + } +} diff --git a/vendor/slim/psr7/src/Response.php b/vendor/slim/psr7/src/Response.php new file mode 100644 index 0000000..980e3b5 --- /dev/null +++ b/vendor/slim/psr7/src/Response.php @@ -0,0 +1,216 @@ + 'Continue', + StatusCodeInterface::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols', + StatusCodeInterface::STATUS_PROCESSING => 'Processing', + + // Successful 2xx + StatusCodeInterface::STATUS_OK => 'OK', + StatusCodeInterface::STATUS_CREATED => 'Created', + StatusCodeInterface::STATUS_ACCEPTED => 'Accepted', + StatusCodeInterface::STATUS_NON_AUTHORITATIVE_INFORMATION => 'Non-Authoritative Information', + StatusCodeInterface::STATUS_NO_CONTENT => 'No Content', + StatusCodeInterface::STATUS_RESET_CONTENT => 'Reset Content', + StatusCodeInterface::STATUS_PARTIAL_CONTENT => 'Partial Content', + StatusCodeInterface::STATUS_MULTI_STATUS => 'Multi-Status', + StatusCodeInterface::STATUS_ALREADY_REPORTED => 'Already Reported', + StatusCodeInterface::STATUS_IM_USED => 'IM Used', + + // Redirection 3xx + StatusCodeInterface::STATUS_MULTIPLE_CHOICES => 'Multiple Choices', + StatusCodeInterface::STATUS_MOVED_PERMANENTLY => 'Moved Permanently', + StatusCodeInterface::STATUS_FOUND => 'Found', + StatusCodeInterface::STATUS_SEE_OTHER => 'See Other', + StatusCodeInterface::STATUS_NOT_MODIFIED => 'Not Modified', + StatusCodeInterface::STATUS_USE_PROXY => 'Use Proxy', + StatusCodeInterface::STATUS_RESERVED => '(Unused)', + StatusCodeInterface::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect', + StatusCodeInterface::STATUS_PERMANENT_REDIRECT => 'Permanent Redirect', + + // Client Error 4xx + StatusCodeInterface::STATUS_BAD_REQUEST => 'Bad Request', + StatusCodeInterface::STATUS_UNAUTHORIZED => 'Unauthorized', + StatusCodeInterface::STATUS_PAYMENT_REQUIRED => 'Payment Required', + StatusCodeInterface::STATUS_FORBIDDEN => 'Forbidden', + StatusCodeInterface::STATUS_NOT_FOUND => 'Not Found', + StatusCodeInterface::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed', + StatusCodeInterface::STATUS_NOT_ACCEPTABLE => 'Not Acceptable', + StatusCodeInterface::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required', + StatusCodeInterface::STATUS_REQUEST_TIMEOUT => 'Request Timeout', + StatusCodeInterface::STATUS_CONFLICT => 'Conflict', + StatusCodeInterface::STATUS_GONE => 'Gone', + StatusCodeInterface::STATUS_LENGTH_REQUIRED => 'Length Required', + StatusCodeInterface::STATUS_PRECONDITION_FAILED => 'Precondition Failed', + StatusCodeInterface::STATUS_PAYLOAD_TOO_LARGE => 'Request Entity Too Large', + StatusCodeInterface::STATUS_URI_TOO_LONG => 'Request-URI Too Long', + StatusCodeInterface::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type', + StatusCodeInterface::STATUS_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable', + StatusCodeInterface::STATUS_EXPECTATION_FAILED => 'Expectation Failed', + StatusCodeInterface::STATUS_IM_A_TEAPOT => 'I\'m a teapot', + StatusCodeInterface::STATUS_MISDIRECTED_REQUEST => 'Misdirected Request', + StatusCodeInterface::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', + StatusCodeInterface::STATUS_LOCKED => 'Locked', + StatusCodeInterface::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', + StatusCodeInterface::STATUS_UPGRADE_REQUIRED => 'Upgrade Required', + StatusCodeInterface::STATUS_PRECONDITION_REQUIRED => 'Precondition Required', + StatusCodeInterface::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', + StatusCodeInterface::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', + 444 => 'Connection Closed Without Response', + StatusCodeInterface::STATUS_UNAVAILABLE_FOR_LEGAL_REASONS => 'Unavailable For Legal Reasons', + 499 => 'Client Closed Request', + + // Server Error 5xx + StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error', + StatusCodeInterface::STATUS_NOT_IMPLEMENTED => 'Not Implemented', + StatusCodeInterface::STATUS_BAD_GATEWAY => 'Bad Gateway', + StatusCodeInterface::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable', + StatusCodeInterface::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout', + StatusCodeInterface::STATUS_VERSION_NOT_SUPPORTED => 'HTTP Version Not Supported', + StatusCodeInterface::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates', + StatusCodeInterface::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', + StatusCodeInterface::STATUS_LOOP_DETECTED => 'Loop Detected', + StatusCodeInterface::STATUS_NOT_EXTENDED => 'Not Extended', + StatusCodeInterface::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', + 599 => 'Network Connect Timeout Error', + ]; + + /** + * @param int $status The response status code. + * @param HeadersInterface|null $headers The response headers. + * @param StreamInterface|null $body The response body. + */ + public function __construct( + int $status = StatusCodeInterface::STATUS_OK, + ?HeadersInterface $headers = null, + ?StreamInterface $body = null + ) { + $this->status = $this->filterStatus($status); + $this->headers = $headers ?: new Headers([], []); + $this->body = $body ?: (new StreamFactory())->createStream(); + } + + /** + * This method is applied to the cloned object after PHP performs an initial shallow-copy. + * This method completes a deep-copy by creating new objects for the cloned object's internal reference pointers. + */ + public function __clone() + { + $this->headers = clone $this->headers; + } + + /** + * {@inheritdoc} + */ + public function getStatusCode(): int + { + return $this->status; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withStatus($code, $reasonPhrase = ''): ResponseInterface + { + $code = $this->filterStatus($code); + $reasonPhrase = $this->filterReasonPhrase($reasonPhrase); + + $clone = clone $this; + $clone->status = $code; + $clone->reasonPhrase = $reasonPhrase; + + return $clone; + } + + /** + * {@inheritdoc} + */ + public function getReasonPhrase(): string + { + if ($this->reasonPhrase !== '') { + return $this->reasonPhrase; + } + + if (isset(static::$messages[$this->status])) { + return static::$messages[$this->status]; + } + + return ''; + } + + /** + * Filter HTTP status code. + * + * @param int $status HTTP status code. + * + * @return int + * + * @throws InvalidArgumentException If an invalid HTTP status code is provided. + */ + protected function filterStatus($status): int + { + if (!is_integer($status) || $status < StatusCodeInterface::STATUS_CONTINUE || $status > 599) { + throw new InvalidArgumentException('Invalid HTTP status code.'); + } + + return $status; + } + + /** + * Filter Reason Phrase + * + * @param mixed $reasonPhrase + * + * @return string + * + * @throws InvalidArgumentException + */ + protected function filterReasonPhrase($reasonPhrase = ''): string + { + if (is_object($reasonPhrase) && method_exists($reasonPhrase, '__toString')) { + $reasonPhrase = (string) $reasonPhrase; + } + + if (!is_string($reasonPhrase)) { + throw new InvalidArgumentException('Response reason phrase must be a string.'); + } + + if (strpos($reasonPhrase, "\r") !== false || strpos($reasonPhrase, "\n") !== false) { + throw new InvalidArgumentException( + 'Reason phrase contains one of the following prohibited characters: \r \n' + ); + } + + return $reasonPhrase; + } +} diff --git a/vendor/slim/psr7/src/Stream.php b/vendor/slim/psr7/src/Stream.php new file mode 100644 index 0000000..25a97f8 --- /dev/null +++ b/vendor/slim/psr7/src/Stream.php @@ -0,0 +1,396 @@ +attach($stream); + + if ($cache && (!$cache->isSeekable() || !$cache->isWritable())) { + throw new RuntimeException('Cache stream must be seekable and writable'); + } + $this->cache = $cache; + } + + /** + * {@inheritdoc} + * @return array|mixed + */ + public function getMetadata($key = null) + { + if (!$this->stream) { + return null; + } + + $this->meta = stream_get_meta_data($this->stream); + + if (!$key) { + return $this->meta; + } + + return $this->meta[$key] ?? null; + } + + /** + * Attach new resource to this object. + * + * @internal This method is not part of the PSR-7 standard. + * + * @param resource $stream A PHP resource handle. + * + * @throws InvalidArgumentException If argument is not a valid PHP resource. + * + * @return void + */ + protected function attach($stream): void + { + if (!is_resource($stream)) { + throw new InvalidArgumentException(__METHOD__ . ' argument must be a valid PHP resource'); + } + + if ($this->stream) { + $this->detach(); + } + + $this->stream = $stream; + } + + /** + * {@inheritdoc} + */ + public function detach() + { + $oldResource = $this->stream; + $this->stream = null; + $this->meta = null; + $this->readable = null; + $this->writable = null; + $this->seekable = null; + $this->size = null; + $this->isPipe = null; + + $this->cache = null; + $this->finished = false; + + return $oldResource; + } + + /** + * {@inheritdoc} + */ + public function __toString(): string + { + if (!$this->stream) { + return ''; + } + if ($this->cache && $this->finished) { + $this->cache->rewind(); + return $this->cache->getContents(); + } + if ($this->isSeekable()) { + $this->rewind(); + } + return $this->getContents(); + } + + /** + * {@inheritdoc} + */ + public function close(): void + { + if ($this->stream) { + if ($this->isPipe()) { + pclose($this->stream); + } else { + fclose($this->stream); + } + } + + $this->detach(); + } + + /** + * {@inheritdoc} + */ + public function getSize(): ?int + { + if ($this->stream && !$this->size) { + $stats = fstat($this->stream); + + if ($stats) { + $this->size = !$this->isPipe() ? $stats['size'] : null; + } + } + + return $this->size; + } + + /** + * {@inheritdoc} + */ + public function tell(): int + { + $position = false; + + if ($this->stream) { + $position = ftell($this->stream); + } + + if ($position === false || $this->isPipe()) { + throw new RuntimeException('Could not get the position of the pointer in stream.'); + } + + return $position; + } + + /** + * {@inheritdoc} + */ + public function eof(): bool + { + return !$this->stream || feof($this->stream); + } + + /** + * {@inheritdoc} + */ + public function isReadable(): bool + { + if ($this->readable !== null) { + return $this->readable; + } + + $this->readable = false; + + if ($this->stream) { + $mode = $this->getMetadata('mode'); + + if (is_string($mode) && (strstr($mode, 'r') !== false || strstr($mode, '+') !== false)) { + $this->readable = true; + } + } + + return $this->readable; + } + + /** + * {@inheritdoc} + */ + public function isWritable(): bool + { + if ($this->writable === null) { + $this->writable = false; + + if ($this->stream) { + $mode = $this->getMetadata('mode'); + + if (is_string($mode) && (strstr($mode, 'w') !== false || strstr($mode, '+') !== false)) { + $this->writable = true; + } + } + } + + return $this->writable; + } + + /** + * {@inheritdoc} + */ + public function isSeekable(): bool + { + if ($this->seekable === null) { + $this->seekable = false; + + if ($this->stream) { + $this->seekable = !$this->isPipe() && $this->getMetadata('seekable'); + } + } + + return $this->seekable; + } + + /** + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET): void + { + if (!$this->isSeekable() || $this->stream && fseek($this->stream, $offset, $whence) === -1) { + throw new RuntimeException('Could not seek in stream.'); + } + } + + /** + * {@inheritdoc} + */ + public function rewind(): void + { + if (!$this->isSeekable() || $this->stream && rewind($this->stream) === false) { + throw new RuntimeException('Could not rewind stream.'); + } + } + + /** + * {@inheritdoc} + */ + public function read($length): string + { + $data = false; + + if ($this->isReadable() && $this->stream && $length > 0) { + $data = fread($this->stream, $length); + } + + if (is_string($data)) { + if ($this->cache) { + $this->cache->write($data); + } + if ($this->eof()) { + $this->finished = true; + } + return $data; + } + + throw new RuntimeException('Could not read from stream.'); + } + + /** + * {@inheritdoc} + * @return int + */ + public function write($string): int + { + $written = false; + + if ($this->isWritable() && $this->stream) { + $written = fwrite($this->stream, $string); + } + + if ($written !== false) { + $this->size = null; + return $written; + } + + throw new RuntimeException('Could not write to stream.'); + } + + /** + * {@inheritdoc} + */ + public function getContents(): string + { + if ($this->cache && $this->finished) { + $this->cache->rewind(); + return $this->cache->getContents(); + } + + $contents = false; + + if ($this->stream) { + $contents = stream_get_contents($this->stream); + } + + if (is_string($contents)) { + if ($this->cache) { + $this->cache->write($contents); + } + if ($this->eof()) { + $this->finished = true; + } + return $contents; + } + + throw new RuntimeException('Could not get contents of stream.'); + } + + /** + * Returns whether or not the stream is a pipe. + * + * @internal This method is not part of the PSR-7 standard. + * + * @return bool + */ + public function isPipe(): bool + { + if ($this->isPipe === null) { + $this->isPipe = false; + + if ($this->stream) { + $stats = fstat($this->stream); + + if (is_array($stats)) { + $this->isPipe = ($stats['mode'] & self::FSTAT_MODE_S_IFIFO) !== 0; + } + } + } + + return $this->isPipe; + } +} diff --git a/vendor/slim/psr7/src/UploadedFile.php b/vendor/slim/psr7/src/UploadedFile.php new file mode 100644 index 0000000..d8d6ad6 --- /dev/null +++ b/vendor/slim/psr7/src/UploadedFile.php @@ -0,0 +1,279 @@ +getMetadata('uri'); + if (!is_string($file)) { + throw new InvalidArgumentException('No URI associated with the stream.'); + } + $this->file = $file; + $this->stream = $fileNameOrStream; + } elseif (is_string($fileNameOrStream)) { + $this->file = $fileNameOrStream; + } else { + throw new InvalidArgumentException( + 'Please provide a string (full path to the uploaded file) or an instance of StreamInterface.' + ); + } + $this->name = $name; + $this->type = $type; + $this->size = $size; + $this->error = $error; + $this->sapi = $sapi; + } + + /** + * {@inheritdoc} + * @return StreamInterface + */ + public function getStream(): StreamInterface + { + if ($this->moved) { + throw new RuntimeException(sprintf('Uploaded file %s has already been moved', $this->name)); + } + + if (!$this->stream) { + $this->stream = (new StreamFactory())->createStreamFromFile($this->file); + } + + return $this->stream; + } + + /** + * {@inheritdoc} + */ + public function moveTo($targetPath): void + { + if ($this->moved) { + throw new RuntimeException('Uploaded file already moved'); + } + + $targetIsStream = strpos($targetPath, '://') > 0; + if (!$targetIsStream && !is_writable(dirname($targetPath))) { + throw new InvalidArgumentException('Upload target path is not writable'); + } + + if ($targetIsStream) { + if (!copy($this->file, $targetPath)) { + throw new RuntimeException(sprintf('Error moving uploaded file %s to %s', $this->name, $targetPath)); + } + + if (!unlink($this->file)) { + throw new RuntimeException(sprintf('Error removing uploaded file %s', $this->name)); + } + } elseif ($this->sapi) { + if (!is_uploaded_file($this->file)) { + throw new RuntimeException(sprintf('%s is not a valid uploaded file', $this->file)); + } + + if (!move_uploaded_file($this->file, $targetPath)) { + throw new RuntimeException(sprintf('Error moving uploaded file %s to %s', $this->name, $targetPath)); + } + } else { + if (!rename($this->file, $targetPath)) { + throw new RuntimeException(sprintf('Error moving uploaded file %s to %s', $this->name, $targetPath)); + } + } + + $this->moved = true; + } + + /** + * {@inheritdoc} + */ + public function getError(): int + { + return $this->error; + } + + /** + * {@inheritdoc} + */ + public function getClientFilename(): ?string + { + return $this->name; + } + + /** + * {@inheritdoc} + */ + public function getClientMediaType(): ?string + { + return $this->type; + } + + /** + * {@inheritdoc} + */ + public function getSize(): ?int + { + return $this->size; + } + + /** + * Returns the client-provided full path to the file + * + * @internal This method is not part of the PSR-7 standard + * + * @return string + */ + public function getFilePath(): string + { + return $this->file; + } + + /** + * Create a normalized tree of UploadedFile instances from the Environment. + * + * @internal This method is not part of the PSR-7 standard. + * + * @param array $globals The global server variables. + * + * @return array A normalized tree of UploadedFile instances or null if none are provided. + */ + public static function createFromGlobals(array $globals): array + { + if (isset($globals['slim.files']) && is_array($globals['slim.files'])) { + return $globals['slim.files']; + } + + if (!empty($_FILES)) { + return self::parseUploadedFiles($_FILES); + } + + return []; + } + + /** + * Parse a non-normalized, i.e. $_FILES superglobal, tree of uploaded file data. + * + * @internal This method is not part of the PSR-7 standard. + * + * @param array $uploadedFiles The non-normalized tree of uploaded file data. + * + * @return array A normalized tree of UploadedFile instances. + */ + private static function parseUploadedFiles(array $uploadedFiles): array + { + $parsed = []; + foreach ($uploadedFiles as $field => $uploadedFile) { + if (!isset($uploadedFile['error'])) { + if (is_array($uploadedFile)) { + $parsed[$field] = self::parseUploadedFiles($uploadedFile); + } + continue; + } + + $parsed[$field] = []; + if (!is_array($uploadedFile['error'])) { + $parsed[$field] = new static( + $uploadedFile['tmp_name'], + $uploadedFile['name'] ?? null, + $uploadedFile['type'] ?? null, + $uploadedFile['size'] ?? null, + $uploadedFile['error'], + true + ); + } else { + $subArray = []; + foreach ($uploadedFile['error'] as $fileIdx => $error) { + // Normalize sub array and re-parse to move the input's key name up a level + $subArray[$fileIdx]['name'] = $uploadedFile['name'][$fileIdx]; + $subArray[$fileIdx]['type'] = $uploadedFile['type'][$fileIdx]; + $subArray[$fileIdx]['tmp_name'] = $uploadedFile['tmp_name'][$fileIdx]; + $subArray[$fileIdx]['error'] = $uploadedFile['error'][$fileIdx]; + $subArray[$fileIdx]['size'] = $uploadedFile['size'][$fileIdx]; + + $parsed[$field] = self::parseUploadedFiles($subArray); + } + } + } + + return $parsed; + } +} diff --git a/vendor/slim/psr7/src/Uri.php b/vendor/slim/psr7/src/Uri.php new file mode 100644 index 0000000..6f51d7f --- /dev/null +++ b/vendor/slim/psr7/src/Uri.php @@ -0,0 +1,504 @@ + null, + 'http' => 80, + 'https' => 443 + ]; + + /** + * Uri scheme (without "://" suffix) + */ + protected string $scheme = ''; + + protected string $user = ''; + + protected string $password = ''; + + protected string $host = ''; + + protected ?int $port; + + protected string $path = ''; + + /** + * Uri query string (without "?" prefix) + */ + protected string $query = ''; + + /** + * Uri fragment string (without "#" prefix) + */ + protected string $fragment = ''; + + /** + * @param string $scheme Uri scheme. + * @param string $host Uri host. + * @param int|null $port Uri port number. + * @param string $path Uri path. + * @param string $query Uri query string. + * @param string $fragment Uri fragment. + * @param string $user Uri user. + * @param string $password Uri password. + */ + public function __construct( + string $scheme, + string $host, + ?int $port = null, + string $path = '/', + string $query = '', + string $fragment = '', + string $user = '', + string $password = '' + ) { + $this->scheme = $this->filterScheme($scheme); + $this->host = $this->filterHost($host); + $this->port = $this->filterPort($port); + $this->path = $this->filterPath($path); + $this->query = $this->filterQuery($query); + $this->fragment = $this->filterFragment($fragment); + $this->user = $this->filterUserInfo($user); + $this->password = $this->filterUserInfo($password); + } + + /** + * {@inheritdoc} + */ + public function getScheme(): string + { + return $this->scheme; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withScheme($scheme): UriInterface + { + $scheme = $this->filterScheme($scheme); + $clone = clone $this; + $clone->scheme = $scheme; + + return $clone; + } + + /** + * Filter Uri scheme. + * + * @param mixed $scheme Raw Uri scheme. + * + * @return string + * + * @throws InvalidArgumentException If the Uri scheme is not a string. + * @throws InvalidArgumentException If Uri scheme is not exists in SUPPORTED_SCHEMES + */ + protected function filterScheme($scheme): string + { + if (!is_string($scheme)) { + throw new InvalidArgumentException('Uri scheme must be a string.'); + } + + $scheme = str_replace('://', '', strtolower($scheme)); + if (!key_exists($scheme, static::SUPPORTED_SCHEMES)) { + throw new InvalidArgumentException( + 'Uri scheme must be one of: "' . implode('", "', array_keys(static::SUPPORTED_SCHEMES)) . '"' + ); + } + + return $scheme; + } + + /** + * {@inheritdoc} + */ + public function getAuthority(): string + { + $userInfo = $this->getUserInfo(); + $host = $this->getHost(); + $port = $this->getPort(); + + return ($userInfo !== '' ? $userInfo . '@' : '') . $host . ($port !== null ? ':' . $port : ''); + } + + /** + * {@inheritdoc} + */ + public function getUserInfo(): string + { + $info = $this->user; + + if ($this->password !== '') { + $info .= ':' . $this->password; + } + + return $info; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withUserInfo($user, $password = null): UriInterface + { + $clone = clone $this; + $clone->user = $this->filterUserInfo($user); + + if ($clone->user !== '') { + $clone->password = $this->filterUserInfo($password); + } else { + $clone->password = ''; + } + + return $clone; + } + + /** + * Filters the user info string. + * + * Returns the percent-encoded query string. + * + * @param string|null $info The raw uri query string. + * + * @return string + */ + protected function filterUserInfo(?string $info = null): string + { + if (!is_string($info)) { + return ''; + } + + $match = preg_replace_callback( + '/(?:[^%a-zA-Z0-9_\-\.~\pL!\$&\'\(\)\*\+,;=]+|%(?![A-Fa-f0-9]{2}))/u', + function ($match) { + return rawurlencode($match[0]); + }, + $info + ); + + return is_string($match) ? $match : ''; + } + + /** + * {@inheritdoc} + */ + public function getHost(): string + { + return $this->host; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withHost($host): UriInterface + { + $clone = clone $this; + $clone->host = $this->filterHost($host); + + return $clone; + } + + /** + * Filter Uri host. + * + * If the supplied host is an IPv6 address, then it is converted to a reference + * as per RFC 2373. + * + * @param mixed $host The host to filter. + * + * @return string + * + * @throws InvalidArgumentException for invalid host names. + */ + protected function filterHost($host): string + { + if (is_object($host) && method_exists($host, '__toString')) { + $host = (string) $host; + } + + if (!is_string($host)) { + throw new InvalidArgumentException('Uri host must be a string'); + } + + if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + $host = '[' . $host . ']'; + } + + return strtolower($host); + } + + /** + * {@inheritdoc} + */ + public function getPort(): ?int + { + return $this->port && !$this->hasStandardPort() ? $this->port : null; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withPort($port): UriInterface + { + $port = $this->filterPort($port); + $clone = clone $this; + $clone->port = $port; + + return $clone; + } + + /** + * Does this Uri use a standard port? + * + * @return bool + */ + protected function hasStandardPort(): bool + { + return static::SUPPORTED_SCHEMES[$this->scheme] === $this->port; + } + + /** + * Filter Uri port. + * + * @param int|string|null $port The Uri port number. + * + * @return int|null + * + * @throws InvalidArgumentException If the port is invalid. + */ + protected function filterPort($port): ?int + { + if (is_null($port)) { + return null; + } + + $port = (int) $port; + + if ($port >= 1 && $port <= 65535) { + return $port; + } + + throw new InvalidArgumentException('Uri port must be null or an integer between 1 and 65535 (inclusive)'); + } + + /** + * {@inheritdoc} + */ + public function getPath(): string + { + if (str_starts_with($this->path, '/')) { + // Use only one leading slash to prevent XSS attempts. + return '/' . ltrim($this->path, '/'); + } + + return $this->path; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withPath($path): UriInterface + { + if (!is_string($path)) { + throw new InvalidArgumentException('Uri path must be a string'); + } + + $clone = clone $this; + $clone->path = $this->filterPath($path); + + return $clone; + } + + /** + * Filter Uri path. + * + * This method percent-encodes all reserved characters in the provided path string. + * This method will NOT double-encode characters that are already percent-encoded. + * + * @param string $path The raw uri path. + * + * @return string The RFC 3986 percent-encoded uri path. + * + * @link http://www.faqs.org/rfcs/rfc3986.html + */ + protected function filterPath($path): string + { + $match = preg_replace_callback( + '/(?:[^a-zA-Z0-9_\-\.~:@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/', + fn (array $match) => rawurlencode($match[0]), + $path + ); + + return is_string($match) ? $match : ''; + } + + /** + * {@inheritdoc} + */ + public function getQuery(): string + { + return $this->query; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withQuery($query): UriInterface + { + $query = ltrim($this->filterQuery($query), '?'); + $clone = clone $this; + $clone->query = $query; + + return $clone; + } + + /** + * Filters the query string of a URI. + * + * Returns the percent-encoded query string. + * + * @param mixed $query The raw uri query string. + * + * @return string + */ + protected function filterQuery($query): string + { + if (is_object($query) && method_exists($query, '__toString')) { + $query = (string) $query; + } + + if (!is_string($query)) { + throw new InvalidArgumentException('Uri query must be a string.'); + } + + $match = preg_replace_callback( + '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/', + function ($match) { + return rawurlencode($match[0]); + }, + $query + ); + + return is_string($match) ? $match : ''; + } + + /** + * {@inheritdoc} + */ + public function getFragment(): string + { + return $this->fragment; + } + + /** + * {@inheritdoc} + * @return static + */ + public function withFragment($fragment): UriInterface + { + $fragment = $this->filterFragment($fragment); + $clone = clone $this; + $clone->fragment = $fragment; + + return $clone; + } + + /** + * Filters fragment of a URI. + * + * Returns the percent-encoded fragment. + * + * @param mixed $fragment The raw uri query string. + * + * @return string + */ + protected function filterFragment($fragment): string + { + if (is_object($fragment) && method_exists($fragment, '__toString')) { + $fragment = (string) $fragment; + } + + if (!is_string($fragment)) { + throw new InvalidArgumentException('Uri fragment must be a string.'); + } + + $fragment = ltrim($fragment, '#'); + + $match = preg_replace_callback( + '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/', + function ($match) { + return rawurlencode($match[0]); + }, + $fragment + ); + + return is_string($match) ? $match : ''; + } + + /** + * {@inheritdoc} + */ + public function __toString(): string + { + $scheme = $this->getScheme(); + $authority = $this->getAuthority(); + $path = $this->path; + $query = $this->getQuery(); + $fragment = $this->getFragment(); + + if ($path !== '') { + if ($path[0] !== '/') { + if ($authority !== '') { + // If the path is rootless and an authority is present, the path MUST be prefixed by "/". + $path = '/' . $path; + } + } elseif (isset($path[1]) && $path[1] === '/') { + if ($authority === '') { + // If the path is starting with more than one "/" and no authority is present, + // the starting slashes MUST be reduced to one. + $path = '/' . ltrim($path, '/'); + } + } + } + + return ($scheme !== '' ? $scheme . ':' : '') + . ($authority !== '' ? '//' . $authority : '') + . $path + . ($query !== '' ? '?' . $query : '') + . ($fragment !== '' ? '#' . $fragment : ''); + } +} diff --git a/vendor/slim/psr7/tests/Assets/HeaderStack.php b/vendor/slim/psr7/tests/Assets/HeaderStack.php new file mode 100644 index 0000000..b07daea --- /dev/null +++ b/vendor/slim/psr7/tests/Assets/HeaderStack.php @@ -0,0 +1,95 @@ + $item) { + if (false !== strpos($item['header'], "$header:")) { + unset(self::$data[$key]); + } + } + } +} diff --git a/vendor/slim/psr7/tests/BodyTest.php b/vendor/slim/psr7/tests/BodyTest.php new file mode 100644 index 0000000..de1d8de --- /dev/null +++ b/vendor/slim/psr7/tests/BodyTest.php @@ -0,0 +1,422 @@ +stream) === true) { + fclose($this->stream); + } + } + + /** + * @param string $mode + * + * @return resource + */ + public function resourceFactory(string $mode = 'r+') + { + $stream = fopen('php://temp', $mode); + fwrite($stream, $this->text); + rewind($stream); + + return $stream; + } + + public function testConstructorAttachesStream() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $bodyStream = new ReflectionProperty($body, 'stream'); + $bodyStream->setAccessible(true); + + $this->assertSame($this->stream, $bodyStream->getValue($body)); + } + + public function testConstructorInvalidStream() + { + $this->expectException(InvalidArgumentException::class); + + $this->stream = 'foo'; + $body = new Stream($this->stream); + } + + public function testGetMetadata() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertTrue(is_array($body->getMetadata())); + } + + public function testGetMetadataKey() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertEquals('php://temp', $body->getMetadata('uri')); + } + + public function testGetMetadataKeyNotFound() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertNull($body->getMetadata('foo')); + } + + public function testDetach() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $bodyStream = new ReflectionProperty($body, 'stream'); + $bodyStream->setAccessible(true); + + $bodyMetadata = new ReflectionProperty($body, 'meta'); + $bodyMetadata->setAccessible(true); + + $bodyReadable = new ReflectionProperty($body, 'readable'); + $bodyReadable->setAccessible(true); + + $bodyWritable = new ReflectionProperty($body, 'writable'); + $bodyWritable->setAccessible(true); + + $bodySeekable = new ReflectionProperty($body, 'seekable'); + $bodySeekable->setAccessible(true); + + $result = $body->detach(); + + $this->assertSame($this->stream, $result); + $this->assertNull($bodyStream->getValue($body)); + $this->assertNull($bodyMetadata->getValue($body)); + $this->assertNull($bodyReadable->getValue($body)); + $this->assertNull($bodyWritable->getValue($body)); + $this->assertNull($bodySeekable->getValue($body)); + } + + public function testToStringAttached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertEquals($this->text, (string) $body); + } + + public function testToStringAttachedRewindsFirst() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertEquals($this->text, (string) $body); + $this->assertEquals($this->text, (string) $body); + $this->assertEquals($this->text, (string) $body); + } + + public function testToStringDetached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $bodyStream = new ReflectionProperty($body, 'stream'); + $bodyStream->setAccessible(true); + $bodyStream->setValue($body, null); + + $this->assertEquals('', (string) $body); + } + + public function testClose() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->close(); + + $bodyStream = new ReflectionProperty($body, 'stream'); + $bodyStream->setAccessible(true); + + $this->assertNull($bodyStream->getValue($body)); + } + + public function testGetSizeAttached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertEquals(mb_strlen($this->text), $body->getSize()); + } + + public function testGetSizeDetached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $bodyStream = new ReflectionProperty($body, 'stream'); + $bodyStream->setAccessible(true); + $bodyStream->setValue($body, null); + + $this->assertNull($body->getSize()); + } + + public function testTellAttached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + fseek($this->stream, 10); + + $this->assertEquals(10, $body->tell()); + } + + public function testTellDetachedThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $bodyStream = new ReflectionProperty($body, 'stream'); + $bodyStream->setAccessible(true); + $bodyStream->setValue($body, null); + + $body->tell(); + } + + public function testEofAttachedFalse() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + fseek($this->stream, 10); + + $this->assertFalse($body->eof()); + } + + public function testEofAttachedTrue() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + while (feof($this->stream) === false) { + fread($this->stream, 1024); + } + + $this->assertTrue($body->eof()); + } + + public function testEofDetached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $bodyStream = new ReflectionProperty($body, 'stream'); + $bodyStream->setAccessible(true); + $bodyStream->setValue($body, null); + + $this->assertTrue($body->eof()); + } + + public function isReadableAttachedTrue() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertTrue($body->isReadable()); + } + + public function isReadableAttachedFalse() + { + $stream = fopen('php://temp', 'w'); + $body = new Stream($this->stream); + + $this->assertFalse($body->isReadable()); + fclose($stream); + } + + public function testIsReadableDetached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->detach(); + + $this->assertFalse($body->isReadable()); + } + + public function isWritableAttachedTrue() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertTrue($body->isWritable()); + } + + public function isWritableAttachedFalse() + { + $stream = fopen('php://temp', 'r'); + $body = new Stream($this->stream); + + $this->assertFalse($body->isWritable()); + fclose($stream); + } + + public function testIsWritableDetached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->detach(); + + $this->assertFalse($body->isWritable()); + } + + public function isSeekableAttachedTrue() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertTrue($body->isSeekable()); + } + + // TODO: Is seekable is false when attached... how? + + public function testIsSeekableDetached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->detach(); + + $this->assertFalse($body->isSeekable()); + } + + public function testSeekAttached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->seek(10); + + $this->assertEquals(10, ftell($this->stream)); + } + + public function testSeekDetachedThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->detach(); + + $body->seek(10); + } + + public function testRewindAttached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + fseek($this->stream, 10); + $body->rewind(); + + $this->assertEquals(0, ftell($this->stream)); + } + + public function testRewindDetachedThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->detach(); + + $body->rewind(); + } + + public function testReadAttached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + + $this->assertEquals(substr($this->text, 0, 10), $body->read(10)); + } + + public function testReadDetachedThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->detach(); + + $body->read(10); + } + + public function testWriteAttached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + while (feof($this->stream) === false) { + fread($this->stream, 1024); + } + $body->write('foo'); + + $this->assertEquals($this->text . 'foo', (string) $body); + } + + public function testWriteDetachedThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->detach(); + + $body->write('foo'); + } + + public function testGetContentsAttached() + { + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + fseek($this->stream, 10); + + $this->assertEquals(substr($this->text, 10), $body->getContents()); + } + + public function testGetContentsDetachedThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + + $this->stream = $this->resourceFactory(); + $body = new Stream($this->stream); + $body->detach(); + + $body->getContents(); + } +} diff --git a/vendor/slim/psr7/tests/CookiesTest.php b/vendor/slim/psr7/tests/CookiesTest.php new file mode 100644 index 0000000..8a1cc86 --- /dev/null +++ b/vendor/slim/psr7/tests/CookiesTest.php @@ -0,0 +1,283 @@ + 'Works', + ]); + $prop = new ReflectionProperty($cookies, 'requestCookies'); + $prop->setAccessible(true); + $this->assertNotEmpty($prop->getValue($cookies)['test']); + $this->assertEquals('Works', $prop->getValue($cookies)['test']); + } + + public function testSetDefaults() + { + $defaults = [ + 'value' => 'toast', + 'domain' => null, + 'hostonly' => null, + 'path' => null, + 'expires' => null, + 'secure' => true, + 'httponly' => true, + 'samesite' => null + ]; + + $cookies = new Cookies(); + + $prop = new ReflectionProperty($cookies, 'defaults'); + $prop->setAccessible(true); + + $origDefaults = $prop->getValue($cookies); + + $cookies->setDefaults($defaults); + + $this->assertEquals($defaults, $prop->getValue($cookies)); + $this->assertNotEquals($origDefaults, $prop->getValue($cookies)); + } + + public function testSetCookieValues() + { + $cookies = new Cookies(); + $cookies->set('foo', 'bar'); + + $prop = new ReflectionProperty($cookies, 'responseCookies'); + $prop->setAccessible(true); + + $expectedValue = [ + 'foo' => [ + 'value' => 'bar', + 'domain' => null, + 'hostonly' => null, + 'path' => null, + 'expires' => null, + 'secure' => false, + 'httponly' => false, + 'samesite' => null + ] + ]; + + $this->assertEquals($expectedValue, $prop->getValue($cookies)); + } + + public function testSetCookieValuesContainDefaults() + { + $cookies = new Cookies(); + $defaults = [ + 'value' => 'toast', + 'domain' => null, + 'hostonly' => null, + 'path' => null, + 'expires' => null, + 'secure' => true, + 'httponly' => true, + 'samesite' => 'lax' + ]; + + $cookies->setDefaults($defaults); + $cookies->set('foo', 'bar'); + + $prop = new ReflectionProperty($cookies, 'responseCookies'); + $prop->setAccessible(true); + + $expectedValue = [ + 'foo' => [ + 'value' => 'bar', + 'domain' => null, + 'hostonly' => null, + 'path' => null, + 'expires' => null, + 'secure' => true, + 'httponly' => true, + 'samesite' => 'lax' + ] + ]; + + $this->assertEquals($expectedValue, $prop->getValue($cookies)); + } + + public function testSetCookieValuesCanOverrideDefaults() + { + $cookies = new Cookies(); + $defaults = [ + 'value' => 'toast', + 'domain' => null, + 'hostonly' => null, + 'path' => null, + 'expires' => null, + 'secure' => true, + 'httponly' => true, + 'samesite' => 'lax' + ]; + + $cookies->setDefaults($defaults); + $cookies->set('foo', ['value' => 'bar', 'secure' => false, 'samesite' => 'strict']); + + $prop = new ReflectionProperty($cookies, 'responseCookies'); + $prop->setAccessible(true); + + $expectedValue = [ + 'foo' => [ + 'value' => 'bar', + 'domain' => null, + 'hostonly' => null, + 'path' => null, + 'expires' => null, + 'secure' => false, + 'httponly' => true, + 'samesite' => 'strict' + ] + ]; + + $this->assertEquals($expectedValue, $prop->getValue($cookies)); + } + + public function testSetSameSiteCookieValuesAreCaseInsensitive() + { + $cookies = new Cookies(); + $defaults = [ + 'value' => 'bacon', + 'samesite' => 'lax' + ]; + + $cookies->setDefaults($defaults); + $cookies->set('breakfast', ['samesite' => 'StricT']); + + $prop = new ReflectionProperty($cookies, 'responseCookies'); + $prop->setAccessible(true); + + $expectedValue = [ + 'breakfast' => [ + 'value' => 'bacon', + 'domain' => null, + 'hostonly' => null, + 'path' => null, + 'expires' => null, + 'secure' => false, + 'httponly' => false, + 'samesite' => 'StricT', + ] + ]; + + $this->assertEquals($expectedValue, $prop->getValue($cookies)); + } + + public function testGet() + { + $cookies = new Cookies(['foo' => 'bar', 'baz' => null]); + $this->assertEquals('bar', $cookies->get('foo')); + $this->assertNull($cookies->get('baz', 'defaultValue')); + $this->assertNull($cookies->get('missing')); + $this->assertEquals('defaultValue', $cookies->get('missing', 'defaultValue')); + } + + public function testParseHeader() + { + $cookies = Cookies::parseHeader('foo=bar; name=Josh'); + $this->assertEquals('bar', $cookies['foo']); + $this->assertEquals('Josh', $cookies['name']); + } + + public function testParseHeaderWithJsonArray() + { + $cookies = Cookies::parseHeader('foo=bar; testarray=["someVar1","someVar2","someVar3"]'); + $this->assertEquals('bar', $cookies['foo']); + $this->assertContains('someVar3', json_decode($cookies['testarray'])); + } + + public function testToHeaders() + { + $cookies = new Cookies(); + $cookies->set('test', 'Works'); + $cookies->set('test_array', ['value' => 'bar', 'domain' => 'example.com']); + $this->assertEquals('test=Works', $cookies->toHeaders()[0]); + $this->assertEquals('test_array=bar; domain=example.com', $cookies->toHeaders()[1]); + } + + public function testToHeader() + { + $cookies = new Cookies(); + $class = new ReflectionClass($cookies); + $method = $class->getMethod('toHeader'); + $method->setAccessible(true); + $properties = [ + 'name' => 'test', + 'properties' => [ + 'value' => 'Works' + ] + ]; + $time = time(); + $formattedDate = gmdate('D, d-M-Y H:i:s e', $time); + $propertiesComplex = [ + 'name' => 'test_complex', + 'properties' => [ + 'value' => 'Works', + 'domain' => 'example.com', + 'expires' => $time, + 'path' => '/', + 'secure' => true, + 'hostonly' => true, + 'httponly' => true, + 'samesite' => 'lax' + ] + ]; + $stringDate = '2016-01-01 12:00:00'; + $formattedStringDate = gmdate('D, d-M-Y H:i:s e', strtotime($stringDate)); + $propertiesStringDate = [ + 'name' => 'test_date', + 'properties' => [ + 'value' => 'Works', + 'expires' => $stringDate, + ] + ]; + $cookie = $method->invokeArgs($cookies, $properties); + $cookieComplex = $method->invokeArgs($cookies, $propertiesComplex); + $cookieStringDate = $method->invokeArgs($cookies, $propertiesStringDate); + $this->assertEquals('test=Works', $cookie); + $this->assertEquals( + 'test_complex=Works; domain=example.com; path=/; expires=' + . $formattedDate . '; secure; HostOnly; HttpOnly; SameSite=lax', + $cookieComplex + ); + $this->assertEquals('test_date=Works; expires=' . $formattedStringDate, $cookieStringDate); + } + + public function testParseHeaderException() + { + $this->expectException(InvalidArgumentException::class); + + Cookies::parseHeader(new stdClass()); + } + + public function testSetSameSiteNoneToHeaders() + { + $cookies = new Cookies(); + $cookies->set('foo', ['value' => 'bar', 'samesite' => 'None']); + $this->assertEquals('foo=bar; SameSite=None', $cookies->toHeaders()[0]); + } +} diff --git a/vendor/slim/psr7/tests/EnvironmentTest.php b/vendor/slim/psr7/tests/EnvironmentTest.php new file mode 100644 index 0000000..ba32e18 --- /dev/null +++ b/vendor/slim/psr7/tests/EnvironmentTest.php @@ -0,0 +1,48 @@ + '/foo/bar/index.php', + 'REQUEST_URI' => '/foo/bar?abc=123', + ]); + + $this->assertEquals('/foo/bar/index.php', $env['SCRIPT_NAME']); + $this->assertEquals('/foo/bar?abc=123', $env['REQUEST_URI']); + } + + public function testMockHttps() + { + $env = Environment::mock([ + 'HTTPS' => 'on' + ]); + + $this->assertEquals('on', $env['HTTPS']); + $this->assertEquals(443, $env['SERVER_PORT']); + } + + public function testMockRequestScheme() + { + $env = Environment::mock([ + 'REQUEST_SCHEME' => 'https' + ]); + + $this->assertEquals('https', $env['REQUEST_SCHEME']); + $this->assertEquals(443, $env['SERVER_PORT']); + } +} diff --git a/vendor/slim/psr7/tests/Factory/RequestFactoryTest.php b/vendor/slim/psr7/tests/Factory/RequestFactoryTest.php new file mode 100644 index 0000000..02f16e5 --- /dev/null +++ b/vendor/slim/psr7/tests/Factory/RequestFactoryTest.php @@ -0,0 +1,42 @@ +createUri($uri); + } + + public function testCreateRequestThrowsExceptionWithInvalidUri() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Parameter 2 of RequestFactory::createRequest() must be a string' . + ' or a compatible UriInterface.'); + + $factory = $this->createRequestFactory(); + + $factory->createRequest('GET', new stdClass()); + } +} diff --git a/vendor/slim/psr7/tests/Factory/ResponseFactoryTest.php b/vendor/slim/psr7/tests/Factory/ResponseFactoryTest.php new file mode 100644 index 0000000..7dc557a --- /dev/null +++ b/vendor/slim/psr7/tests/Factory/ResponseFactoryTest.php @@ -0,0 +1,42 @@ +assertInstanceOf(ResponseInterface::class, $response); + $this->assertSame($code, $response->getStatusCode()); + $this->assertSame($reasonPhrase, $response->getReasonPhrase()); + } + + /** + * @dataProvider dataCodes + * + * @param int $code + */ + public function testCreateResponseWithReasonPhrase(int $code) + { + $response = $this->factory->createResponse($code, 'Reason'); + $this->assertResponse($response, $code); + $this->assertResponseCodeAndReasonPhrase($response, $code, 'Reason'); + } +} diff --git a/vendor/slim/psr7/tests/Factory/ServerRequestFactoryTest.php b/vendor/slim/psr7/tests/Factory/ServerRequestFactoryTest.php new file mode 100644 index 0000000..d46be55 --- /dev/null +++ b/vendor/slim/psr7/tests/Factory/ServerRequestFactoryTest.php @@ -0,0 +1,208 @@ +createUri($uri); + } + + public function testGetProtocolVersion() + { + $env = Environment::mock(['SERVER_PROTOCOL' => 'HTTP/1.0']); + $request = $this->createServerRequestFactory()->createServerRequest('GET', '', $env); + + $this->assertEquals('1.0', $request->getProtocolVersion()); + } + + public function testCreateFromGlobals() + { + $GLOBALS['getallheaders_return'] = [ + 'ACCEPT' => 'application/json', + 'ACCEPT-CHARSET' => 'utf-8', + 'ACCEPT-LANGUAGE' => 'en-US', + 'CONTENT-TYPE' => 'multipart/form-data', + 'HOST' => 'example.com', + 'USER-AGENT' => 'Slim Framework', + ]; + + $_SERVER = Environment::mock([ + 'HTTP_HOST' => 'example.com', + 'PHP_AUTH_PW' => 'sekrit', + 'PHP_AUTH_USER' => 'josh', + 'QUERY_STRING' => 'abc=123', + 'REMOTE_ADDR' => '127.0.0.1', + 'REQUEST_METHOD' => 'GET', + 'REQUEST_TIME' => time(), + 'REQUEST_TIME_FLOAT' => microtime(true), + 'REQUEST_URI' => '/foo/bar', + 'SCRIPT_NAME' => '/index.php', + 'SERVER_NAME' => 'localhost', + 'SERVER_PORT' => 8080, + 'SERVER_PROTOCOL' => 'HTTP/1.1', + ]); + + $request = ServerRequestFactory::createFromGlobals(); + + unset($GLOBALS['getallheaders_return']); + + $this->assertEquals('GET', $request->getMethod()); + $this->assertEquals('1.1', $request->getProtocolVersion()); + + $this->assertEquals('application/json', $request->getHeaderLine('Accept')); + $this->assertEquals('utf-8', $request->getHeaderLine('Accept-Charset')); + $this->assertEquals('en-US', $request->getHeaderLine('Accept-Language')); + $this->assertEquals('multipart/form-data', $request->getHeaderLine('Content-Type')); + + $uri = $request->getUri(); + $this->assertEquals('josh:sekrit', $uri->getUserInfo()); + $this->assertEquals('example.com', $uri->getHost()); + $this->assertEquals('8080', $uri->getPort()); + $this->assertEquals('/foo/bar', $uri->getPath()); + $this->assertEquals('abc=123', $uri->getQuery()); + $this->assertEquals('', $uri->getFragment()); + } + + public function testCreateFromGlobalsWithParsedBody() + { + $_SERVER = Environment::mock([ + 'HTTP_CONTENT_TYPE' => 'multipart/form-data', + 'REQUEST_METHOD' => 'POST', + ]); + + $_POST = [ + 'def' => '456', + ]; + + $request = ServerRequestFactory::createFromGlobals(); + + // $_POST should be placed into the parsed body + $this->assertEquals($_POST, $request->getParsedBody()); + } + + public function testCreateFromGlobalsBodyPointsToPhpInput() + { + $request = ServerRequestFactory::createFromGlobals(); + + $this->assertEquals('php://input', $request->getBody()->getMetadata('uri')); + } + + public function testCreateFromGlobalsSetsACache() + { + $request = ServerRequestFactory::createFromGlobals(); + + // ensure that the Stream's $cache property has been set for this php://input stream + $stream = $request->getBody(); + $class = new ReflectionClass($stream); + $property = $class->getProperty('cache'); + $property->setAccessible(true); + $cacheStreamValue = $property->getValue($stream); + $this->assertNotNull($cacheStreamValue); + } + + public function testCreateFromGlobalsWithUploadedFiles() + { + $_SERVER = Environment::mock([ + 'HTTP_CONTENT_TYPE' => 'multipart/form-data', + 'REQUEST_METHOD' => 'POST', + ]); + + $_FILES = [ + 'uploaded_file' => [ + 'name' => [ + 0 => 'foo.jpg', + 1 => 'bar.jpg', + ], + + 'type' => [ + 0 => 'image/jpeg', + 1 => 'image/jpeg', + ], + + 'tmp_name' => [ + 0 => '/tmp/phpUA3XUw', + 1 => '/tmp/phpXUFS0x', + ], + + 'error' => [ + 0 => 0, + 1 => 0, + ], + + 'size' => [ + 0 => 358708, + 1 => 236162, + ], + ] + ]; + + $request = ServerRequestFactory::createFromGlobals(); + + // $_FILES should be mapped to an array of UploadedFile objects + $uploadedFiles = $request->getUploadedFiles(); + $this->assertCount(1, $uploadedFiles); + $this->assertArrayHasKey('uploaded_file', $uploadedFiles); + $this->assertInstanceOf(UploadedFile::class, $uploadedFiles['uploaded_file'][0]); + $this->assertInstanceOf(UploadedFile::class, $uploadedFiles['uploaded_file'][1]); + } + + public function testCreateFromGlobalsParsesBodyWithFragmentedContentType() + { + $_SERVER = Environment::mock([ + 'HTTP_CONTENT_TYPE' => 'application/x-www-form-urlencoded;charset=utf-8', + 'REQUEST_METHOD' => 'POST', + ]); + + $_POST = [ + 'def' => '456', + ]; + + $request = ServerRequestFactory::createFromGlobals(); + + $this->assertEquals($_POST, $request->getParsedBody()); + } + + public function testCreateServerRequestWithNullAsUri() + { + $this->expectException(InvalidArgumentException::class); + + $env = Environment::mock(); + $this->createServerRequestFactory()->createServerRequest('GET', null, $env); + } + + public function testCreateServerRequestWithInvalidUriObject() + { + $this->expectException(InvalidArgumentException::class); + + $env = Environment::mock(); + $this->createServerRequestFactory()->createServerRequest('GET', new stdClass(), $env); + } +} diff --git a/vendor/slim/psr7/tests/Factory/StreamFactoryTest.php b/vendor/slim/psr7/tests/Factory/StreamFactoryTest.php new file mode 100644 index 0000000..e10d38d --- /dev/null +++ b/vendor/slim/psr7/tests/Factory/StreamFactoryTest.php @@ -0,0 +1,66 @@ +expectException(RuntimeException::class); + $this->expectExceptionMessage('StreamFactory::createStream() could not open temporary file stream.'); + + $GLOBALS['fopen_return'] = false; + + $factory = $this->createStreamFactory(); + + $factory->createStream(); + } + + public function testCreateStreamFromFileThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('StreamFactory::createStreamFromFile() could not create resource' + . ' from file `non-readable`'); + + $GLOBALS['fopen_return'] = false; + + $factory = $this->createStreamFactory(); + + $factory->createStreamFromFile('non-readable'); + } + + public function testCreateStreamFromResourceThrowsRuntimeException() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Parameter 1 of StreamFactory::createStreamFromResource() must be a resource.'); + + $factory = $this->createStreamFactory(); + + $factory->createStreamFromResource('not-resource'); + } +} diff --git a/vendor/slim/psr7/tests/Factory/UploadedFileFactoryTest.php b/vendor/slim/psr7/tests/Factory/UploadedFileFactoryTest.php new file mode 100644 index 0000000..1f46b79 --- /dev/null +++ b/vendor/slim/psr7/tests/Factory/UploadedFileFactoryTest.php @@ -0,0 +1,114 @@ +createStreamFromResource($resource); + } + + /** + * Prophesize a `\Psr\Http\Message\StreamInterface` with a `getMetadata` method prophecy. + * + * @param string $argKey Argument for the method prophecy. + * @param mixed $returnValue Return value of the `getMetadata` method. + * + * @return StreamInterface + */ + protected function prophesizeStreamInterfaceWithGetMetadataMethod(string $argKey, $returnValue): StreamInterface + { + $streamProphecy = $this->prophesize(StreamInterface::class); + + /** @noinspection PhpUndefinedMethodInspection */ + $streamProphecy + ->getMetadata($argKey) + ->willReturn($returnValue) + ->shouldBeCalled(); + + /** @var StreamInterface $stream */ + $stream = $streamProphecy->reveal(); + + return $stream; + } + + public function testCreateUploadedFileWithInvalidUri() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('File is not readable.'); + + // Prophesize a `\Psr\Http\Message\StreamInterface` with a `getMetadata` method prophecy. + $streamProphecy = $this->prophesize(StreamInterface::class); + + /** @noinspection PhpUndefinedMethodInspection */ + $streamProphecy + ->getMetadata('uri') + ->willReturn(null) + ->shouldBeCalled(); + + /** @var StreamInterface $stream */ + $stream = $streamProphecy->reveal(); + + $this->factory->createUploadedFile($stream); + } + + public function testCreateUploadedFileWithNonReadableFile() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('File is not readable.'); + + // Prophesize a `\Psr\Http\Message\StreamInterface` with a `getMetadata` and `isReadable` method prophecies. + $streamProphecy = $this->prophesize(StreamInterface::class); + + /** @noinspection PhpUndefinedMethodInspection */ + $streamProphecy + ->getMetadata('uri') + ->willReturn('non-readable') + ->shouldBeCalled(); + + /** @noinspection PhpUndefinedMethodInspection */ + $streamProphecy + ->isReadable() + ->willReturn(false) + ->shouldBeCalled(); + + /** @var StreamInterface $stream */ + $stream = $streamProphecy->reveal(); + + $this->factory->createUploadedFile($stream); + } +} diff --git a/vendor/slim/psr7/tests/Factory/UriFactoryTest.php b/vendor/slim/psr7/tests/Factory/UriFactoryTest.php new file mode 100644 index 0000000..1927569 --- /dev/null +++ b/vendor/slim/psr7/tests/Factory/UriFactoryTest.php @@ -0,0 +1,243 @@ +createUriFactory()->createUri('https://josh@example.com/foo/bar?abc=123#section3'); + + $this->assertEquals('josh@example.com', $uri->getAuthority()); + } + + public function testGetAuthority() + { + $uri = $this->createUriFactory()->createUri('https://example.com/foo/bar?abc=123#section3'); + + $this->assertEquals('example.com', $uri->getAuthority()); + } + + public function testGetAuthorityWithNonStandardPort() + { + $uri = $this->createUriFactory()->createUri('https://example.com:400/foo/bar?abc=123#section3'); + + $this->assertEquals('example.com:400', $uri->getAuthority()); + } + + public function testGetUserInfoWithUsernameAndPassword() + { + $uri = $this->createUriFactory()->createUri('https://josh:sekrit@example.com:443/foo/bar?abc=123#section3'); + + $this->assertEquals('josh:sekrit', $uri->getUserInfo()); + } + + public function testGetUserInfoWithUsernameAndPasswordEncodesCorrectly() + { + $uri = $this + ->createUriFactory() + ->createUri('https://bob@example.com:pass:word@example.com:443/foo/bar?abc=123#section3'); + + $this->assertEquals('bob%40example.com:pass%3Aword', $uri->getUserInfo()); + } + + public function testGetUserInfoWithUsername() + { + $uri = $this->createUriFactory()->createUri('http://josh@example.com/foo/bar?abc=123#section3'); + + $this->assertEquals('josh', $uri->getUserInfo()); + } + + public function testGetUserInfoNone() + { + $uri = $this->createUriFactory()->createUri('https://example.com/foo/bar?abc=123#section3'); + + $this->assertEquals('', $uri->getUserInfo()); + } + + public function testCreateFromString() + { + $uri = $this->createUriFactory()->createUri('https://example.com:8080/foo/bar?abc=123'); + + $this->assertEquals('https', $uri->getScheme()); + $this->assertEquals('example.com', $uri->getHost()); + $this->assertEquals('8080', $uri->getPort()); + $this->assertEquals('/foo/bar', $uri->getPath()); + $this->assertEquals('abc=123', $uri->getQuery()); + } + + public function testCreateFromGlobals() + { + $globals = Environment::mock([ + 'SCRIPT_NAME' => '/index.php', + 'REQUEST_URI' => '/foo/bar?baz=1', + 'PHP_AUTH_USER' => 'josh', + 'PHP_AUTH_PW' => 'sekrit', + 'QUERY_STRING' => 'abc=123', + 'HTTP_HOST' => 'example.com:8080', + 'SERVER_PORT' => 8080, + ]); + + $uri = $this->createUriFactory()->createFromGlobals($globals); + + $this->assertEquals('josh:sekrit', $uri->getUserInfo()); + $this->assertEquals('example.com', $uri->getHost()); + $this->assertEquals('8080', $uri->getPort()); + $this->assertEquals('/foo/bar', $uri->getPath()); + $this->assertEquals('abc=123', $uri->getQuery()); + $this->assertEquals('', $uri->getFragment()); + } + + public function testCreateFromGlobalsWithHttps() + { + $globals = Environment::mock( + [ + 'HTTPS' => 'on', + 'HTTP_HOST' => 'example.com' + ] + ); + + // Make the 'SERVER_PORT' empty as we want to test if the default server port gets set correctly. + $globals['SERVER_PORT'] = ''; + + $uri = $this->createUriFactory()->createFromGlobals($globals); + + $this->assertEquals('https', $uri->getScheme()); + $this->assertEquals('example.com', $uri->getHost()); + + // The port is expected to be NULL as the server port is the default standard (443 in case of https). + $this->assertNull($uri->getPort()); + } + + public function testCreateFromGlobalsUsesServerNameAsHostIfHostHeaderIsNotPresent() + { + $globals = Environment::mock([ + 'SERVER_NAME' => 'example.com', + ]); + + $uri = $this->createUriFactory()->createFromGlobals($globals); + + $this->assertEquals('example.com', $uri->getHost()); + } + + public function testCreateFromGlobalWithIPv6HostNoPort() + { + $environment = Environment::mock([ + 'SCRIPT_NAME' => '/index.php', + 'REQUEST_URI' => '/foo/bar', + 'PHP_AUTH_USER' => 'josh', + 'PHP_AUTH_PW' => 'sekrit', + 'QUERY_STRING' => 'abc=123', + 'HTTP_HOST' => '[2001:db8::1]', + 'REMOTE_ADDR' => '2001:db8::1', + 'SERVER_PORT' => 8080, + ]); + $uri = $this->createUriFactory()->createFromGlobals($environment); + + $this->assertEquals('josh:sekrit', $uri->getUserInfo()); + $this->assertEquals('[2001:db8::1]', $uri->getHost()); + $this->assertEquals('8080', $uri->getPort()); + $this->assertEquals('/foo/bar', $uri->getPath()); + $this->assertEquals('abc=123', $uri->getQuery()); + $this->assertEquals('', $uri->getFragment()); + } + + public function testCreateFromGlobalsWithIPv6HostWithPort() + { + $globals = Environment::mock([ + 'SCRIPT_NAME' => '/index.php', + 'REQUEST_URI' => '/foo/bar', + 'PHP_AUTH_USER' => 'josh', + 'PHP_AUTH_PW' => 'sekrit', + 'QUERY_STRING' => 'abc=123', + 'HTTP_HOST' => '[2001:db8::1]:8080', + 'REMOTE_ADDR' => '2001:db8::1', + 'SERVER_PORT' => 8080, + ]); + + $uri = $this->createUriFactory()->createFromGlobals($globals); + + $this->assertEquals('josh:sekrit', $uri->getUserInfo()); + $this->assertEquals('[2001:db8::1]', $uri->getHost()); + $this->assertEquals('8080', $uri->getPort()); + $this->assertEquals('/foo/bar', $uri->getPath()); + $this->assertEquals('abc=123', $uri->getQuery()); + $this->assertEquals('', $uri->getFragment()); + } + + public function testCreateFromGlobalsWithBasePathContainingSpace() + { + $globals = Environment::mock([ + 'SCRIPT_NAME' => "/f'oo bar/index.php", + 'REQUEST_URI' => "/f%27oo%20bar/baz", + ]); + $uri = $this->createUriFactory()->createFromGlobals($globals); + + $this->assertEquals('/f%27oo%20bar/baz', $uri->getPath()); + } + + public function testWithPathWhenBaseRootIsEmpty() + { + $globals = Environment::mock([ + 'SCRIPT_NAME' => '/index.php', + 'REQUEST_URI' => '/bar', + ]); + $uri = $this->createUriFactory()->createFromGlobals($globals); + + $this->assertEquals('http://localhost/test', (string) $uri->withPath('test')); + } + + /** + * When the URL is /foo/index.php/bar/baz, we need the baseURL to be + * /foo/index.php so that routing works correctly. + * + * @ticket 1639 as a fix to 1590 broke this. + */ + public function testRequestURIContainsIndexDotPhp() + { + $uri = $this->createUriFactory()->createFromGlobals( + Environment::mock( + [ + 'SCRIPT_NAME' => '/foo/index.php', + 'REQUEST_URI' => '/foo/index.php/bar/baz', + ] + ) + ); + $this->assertSame('/foo/index.php/bar/baz', $uri->getPath()); + } + + public function testRequestURICanContainParams() + { + $uri = $this->createUriFactory()->createFromGlobals( + Environment::mock( + [ + 'REQUEST_URI' => '/foo?abc=123', + ] + ) + ); + $this->assertEquals('abc=123', $uri->getQuery()); + } + + public function testUriDistinguishZeroFromEmptyString() + { + $expected = 'https://0:0@0:1/0?0#0'; + $this->assertSame($expected, (string) $this->createUriFactory()->createUri($expected)); + } +} diff --git a/vendor/slim/psr7/tests/HeaderTest.php b/vendor/slim/psr7/tests/HeaderTest.php new file mode 100644 index 0000000..d062768 --- /dev/null +++ b/vendor/slim/psr7/tests/HeaderTest.php @@ -0,0 +1,61 @@ +headerFactory(); + $this->assertEquals('ACCEPT', $header->getOriginalName()); + } + + public function testGetNormalizedName(): void + { + $header = $this->headerFactory(); + $this->assertEquals('accept', $header->getNormalizedName()); + } + + public function testAddValue(): void + { + $header = $this->headerFactory(); + $header2 = $header->addValue('text/html'); + + $this->assertEquals(['application/json', 'text/html'], $header->getValues()); + $this->assertSame($header2, $header); + } + + public function testAddValuesString(): void + { + $header = $this->headerFactory(); + $header2 = $header->addValues('text/html'); + + $this->assertEquals(['application/json', 'text/html'], $header->getValues()); + $this->assertSame($header2, $header); + } +} diff --git a/vendor/slim/psr7/tests/HeadersTest.php b/vendor/slim/psr7/tests/HeadersTest.php new file mode 100644 index 0000000..0642058 --- /dev/null +++ b/vendor/slim/psr7/tests/HeadersTest.php @@ -0,0 +1,288 @@ + 'application/json', + ]; + + $headers = Headers::createFromGlobals(); + + unset($GLOBALS['getallheaders_return']); + + $this->assertEquals(['accept' => ['application/json']], $headers->getHeaders()); + $this->assertEquals(['ACCEPT' => ['application/json']], $headers->getHeaders(true)); + } + + public function testCreateFromGlobalsUsesEmptyArrayIfGetAllHeadersReturnsFalse() + { + $GLOBALS['getallheaders_return'] = false; + + $headers = Headers::createFromGlobals(); + + unset($GLOBALS['getallheaders_return']); + + $this->assertEquals([], $headers->getHeaders()); + } + + public function testAddHeader() + { + $headers = new Headers([ + 'Accept' => 'application/json', + ]); + + $headers->addHeader('Accept', 'text/html'); + + $this->assertEquals(['application/json', 'text/html'], $headers->getHeader('Accept')); + $this->assertEquals(['accept' => ['application/json', 'text/html']], $headers->getHeaders()); + $this->assertEquals(['Accept' => ['application/json', 'text/html']], $headers->getHeaders(true)); + } + + public function testAddHeaderValueEmptyArray() + { + $this->expectException(InvalidArgumentException::class); + + $headers = new Headers(); + $headers->addHeader('Header', []); + } + + public function testRemoveHeader() + { + $headers = new Headers([ + 'Accept' => 'application/json', + ]); + + $headers->removeHeader('Accept'); + + $this->assertEquals([], $headers->getHeader('Accept')); + $this->assertEquals([], $headers->getHeaders()); + } + + /** + * @doesNotPerformAssertions + */ + public function testRemoveHeaderByIncompatibleStringWithRFC() + { + $headers = new Headers(); + $headers->removeHeader(''); + } + + public function testGetHeader() + { + $headers = new Headers([ + 'Accept' => ['application/json', 'text/html'], + ]); + + $this->assertEquals(['application/json', 'text/html'], $headers->getHeader('accept')); + $this->assertEquals(['application/json', 'text/html'], $headers->getHeader('Accept')); + $this->assertEquals(['application/json', 'text/html'], $headers->getHeader('HTTP_ACCEPT')); + } + + public function testGetHeaderReturnsValidatedAndTrimedHeaderDefaultValue() + { + $headers = new Headers([]); + + $this->assertEquals(['application/json'], $headers->getHeader('accept', ' application/json')); + } + + public function testGetHeaderThrowsExceptionWithInvalidDefaultArgument() + { + $this->expectException(InvalidArgumentException::class); + + $headers = new Headers([]); + + $headers->getHeader('accept', new stdClass()); + } + + public function testSetHeader() + { + $headers = new Headers([ + 'Content-Length' => 0, + ]); + + $headers->setHeader('Content-Length', 100); + + $this->assertSame(['100'], $headers->getHeader('Content-Length')); + $this->assertEquals(['content-length' => ['100']], $headers->getHeaders()); + $this->assertEquals(['Content-Length' => ['100']], $headers->getHeaders(true)); + } + + public function testSetHeaderPreservesOriginalCaseIfHeaderAlreadyExists() + { + $headers = new Headers([ + 'CONTENT-LENGTH' => 0, + ]); + + $headers->setHeader('Content-Length', 100); + + $this->assertEquals(['content-length' => ['100']], $headers->getHeaders()); + $this->assertEquals(['CONTENT-LENGTH' => ['100']], $headers->getHeaders(true)); + } + + public function testSetHeaders() + { + $headers = new Headers([ + 'Content-Length' => 0, + ]); + + $headers->setHeaders([ + 'Accept' => 'application/json', + ]); + + $this->assertEquals(['accept' => ['application/json']], $headers->getHeaders()); + $this->assertEquals(['Accept' => ['application/json']], $headers->getHeaders(true)); + } + + public function testHasHeader() + { + $headers = new Headers([ + 'Accept' => 'application/json', + ]); + + $this->assertTrue($headers->hasHeader('accept')); + $this->assertTrue($headers->hasHeader('Accept')); + $this->assertTrue($headers->hasHeader('HTTP_ACCEPT')); + } + + public function testGetHeaders() + { + $headers = new Headers([ + 'HTTP_ACCEPT' => 'text/html', + 'HTTP_CONTENT_TYPE' => 'application/json', + ]); + + $expectedNormalizedHeaders = [ + 'accept' => ['text/html'], + 'content-type' => ['application/json'], + ]; + + $this->assertEquals($expectedNormalizedHeaders, $headers->getHeaders()); + } + + public function testGetHeadersPreservesOriginalCase() + { + $headers = new Headers([ + 'HTTP_ACCEPT' => 'text/html', + 'HTTP_CONTENT_TYPE' => 'application/json', + ]); + + $expectedOriginalHeaders = [ + 'ACCEPT' => ['text/html'], + 'CONTENT-TYPE' => ['application/json'], + ]; + + $this->assertEquals($expectedOriginalHeaders, $headers->getHeaders(true)); + } + + public function testParseAuthorizationHeader() + { + $expectedValue = 'Basic ' . base64_encode('user:password'); + + $headers = new Headers(['Authorization' => $expectedValue]); + $this->assertEquals([$expectedValue], $headers->getHeader('Authorization')); + + $headers = new Headers([], ['REDIRECT_HTTP_AUTHORIZATION' => 'cookie']); + $this->assertEquals(['cookie'], $headers->getHeader('Authorization')); + + $headers = new Headers([], ['PHP_AUTH_USER' => 'user', 'PHP_AUTH_PW' => 'password']); + $this->assertEquals([$expectedValue], $headers->getHeader('Authorization')); + + $headers = new Headers([], ['PHP_AUTH_DIGEST' => 'digest']); + $this->assertEquals(['digest'], $headers->getHeader('Authorization')); + } + + /** + * @dataProvider provideInvalidHeaderNames + */ + public function testWithInvalidHeaderName($headerName): void + { + $headers = new Headers(); + + $this->expectException(\InvalidArgumentException::class); + + $headers->setHeader($headerName, 'foo'); + } + + public static function provideInvalidHeaderNames(): array + { + return [ + [[]], + [false], + [new \stdClass()], + ["Content-Type\r\n\r\n"], + ["Content-Type\r\n"], + ["Content-Type\n"], + ["\r\nContent-Type"], + ["\nContent-Type"], + ["\n"], + ["\r\n"], + ["\t"], + ]; + } + + /** + * @dataProvider provideInvalidHeaderValues + */ + public function testSetInvalidHeaderValue($headerValue) + { + $headers = new Headers(); + + $this->expectException(\InvalidArgumentException::class); + + $headers->setHeader('Content-Type', $headerValue); + } + + public static function provideInvalidHeaderValues(): array + { + // Explicit tests for newlines as the most common exploit vector. + $tests = [ + ["new\nline"], + ["new\r\nline"], + ["new\rline"], + ["new\r\n line"], + ["newline\n"], + ["\nnewline"], + ["newline\r\n"], + ["\n\rnewline"], + ]; + + for ($i = 0; $i <= 0xff; $i++) { + if (\chr($i) == "\t") { + continue; + } + if (\chr($i) == " ") { + continue; + } + if ($i >= 0x21 && $i <= 0x7e) { + continue; + } + if ($i >= 0x80) { + continue; + } + + $tests[] = ["foo" . \chr($i) . "bar"]; + $tests[] = ["foo" . \chr($i)]; + } + + return $tests; + } +} diff --git a/vendor/slim/psr7/tests/Integration/BaseTestFactories.php b/vendor/slim/psr7/tests/Integration/BaseTestFactories.php new file mode 100644 index 0000000..1aa31d8 --- /dev/null +++ b/vendor/slim/psr7/tests/Integration/BaseTestFactories.php @@ -0,0 +1,57 @@ +createUri($uri); + } + + /** + * @param $data + * @return Stream + */ + protected function buildStream($data): Stream + { + if (!is_resource($data)) { + $h = fopen('php://temp', 'w+'); + fwrite($h, $data); + + $data = $h; + } + + return new Stream($data); + } + + /** + * @param $data + * @return UploadedFile + */ + protected function buildUploadableFile($data): UploadedFile + { + return new UploadedFile($this->buildStream($data)); + } +} diff --git a/vendor/slim/psr7/tests/Integration/RequestTest.php b/vendor/slim/psr7/tests/Integration/RequestTest.php new file mode 100644 index 0000000..0ea00bc --- /dev/null +++ b/vendor/slim/psr7/tests/Integration/RequestTest.php @@ -0,0 +1,36 @@ +buildUri('/'), + new Headers(), + [], + [], + $this->buildStream('') + ); + } +} diff --git a/vendor/slim/psr7/tests/Integration/ResponseTest.php b/vendor/slim/psr7/tests/Integration/ResponseTest.php new file mode 100644 index 0000000..7bd45fe --- /dev/null +++ b/vendor/slim/psr7/tests/Integration/ResponseTest.php @@ -0,0 +1,27 @@ +buildUri('/'), + new Headers(), + $_COOKIE, + $_SERVER, + $this->buildStream('') + ); + } +} diff --git a/vendor/slim/psr7/tests/Integration/StreamTest.php b/vendor/slim/psr7/tests/Integration/StreamTest.php new file mode 100644 index 0000000..e70af71 --- /dev/null +++ b/vendor/slim/psr7/tests/Integration/StreamTest.php @@ -0,0 +1,46 @@ +tempFilename = tempnam(sys_get_temp_dir(), 'Slim_Http_UploadedFileTest_'); + if (!$this->tempFilename) { + throw new \RuntimeException("Unable to create temporary file"); + } + file_put_contents($this->tempFilename, '12345'); + + return new UploadedFile( + $this->tempFilename, + basename($this->tempFilename), + 'text/plain', + (int)filesize($this->tempFilename) + ); + } + + protected function tearDown(): void + { + if (is_file($this->tempFilename)) { + unlink($this->tempFilename); + } + } +} diff --git a/vendor/slim/psr7/tests/Integration/UriTest.php b/vendor/slim/psr7/tests/Integration/UriTest.php new file mode 100644 index 0000000..525052a --- /dev/null +++ b/vendor/slim/psr7/tests/Integration/UriTest.php @@ -0,0 +1,30 @@ +createUri($uri); + } +} diff --git a/vendor/slim/psr7/tests/MessageTest.php b/vendor/slim/psr7/tests/MessageTest.php new file mode 100644 index 0000000..eced34f --- /dev/null +++ b/vendor/slim/psr7/tests/MessageTest.php @@ -0,0 +1,186 @@ +protocolVersion = '1.0'; + + $this->assertEquals('1.0', $message->getProtocolVersion()); + } + + public function testWithProtocolVersion() + { + $message = new MessageStub(); + $clone = $message->withProtocolVersion('1.0'); + + $this->assertEquals('1.0', $clone->protocolVersion); + } + + public function testWithProtocolVersionInvalidThrowsException() + { + $this->expectException(InvalidArgumentException::class); + + $message = new MessageStub(); + $message->withProtocolVersion('3.0'); + } + + public function testGetHeaders() + { + $headers = new Headers(); + $headers->addHeader('X-Foo', 'one'); + $headers->addHeader('X-Foo', 'two'); + $headers->addHeader('X-Foo', 'three'); + + $message = new MessageStub(); + $message->headers = $headers; + + $shouldBe = [ + 'X-Foo' => [ + 'one', + 'two', + 'three', + ], + ]; + + $this->assertEquals($shouldBe, $message->getHeaders()); + } + + public function testHasHeader() + { + $headers = new Headers(); + $headers->addHeader('X-Foo', 'one'); + + $message = new MessageStub(); + $message->headers = $headers; + + $this->assertTrue($message->hasHeader('X-Foo')); + $this->assertFalse($message->hasHeader('X-Bar')); + } + + public function testGetHeaderLine() + { + $headers = new Headers(); + $headers->addHeader('X-Foo', 'one'); + $headers->addHeader('X-Foo', 'two'); + $headers->addHeader('X-Foo', 'three'); + + $message = new MessageStub(); + $message->headers = $headers; + + $this->assertEquals('one,two,three', $message->getHeaderLine('X-Foo')); + $this->assertEquals('', $message->getHeaderLine('X-Bar')); + } + + public function testGetHeader() + { + $headers = new Headers(); + $headers->addHeader('X-Foo', 'one'); + $headers->addHeader('X-Foo', 'two'); + $headers->addHeader('X-Foo', 'three'); + + $message = new MessageStub(); + $message->headers = $headers; + + $this->assertEquals(['one', 'two', 'three'], $message->getHeader('X-Foo')); + $this->assertEquals([], $message->getHeader('X-Bar')); + } + + public function testWithHeader() + { + $headers = new Headers(); + $headers->addHeader('X-Foo', 'one'); + $message = new MessageStub(); + $message->headers = $headers; + $clone = $message->withHeader('X-Foo', 'bar'); + + $this->assertEquals('bar', $clone->getHeaderLine('X-Foo')); + } + + public function testWithAddedHeader() + { + $headers = new Headers(); + $headers->addHeader('X-Foo', 'one'); + $message = new MessageStub(); + $message->headers = $headers; + $clone = $message->withAddedHeader('X-Foo', 'two'); + + $this->assertEquals('one,two', $clone->getHeaderLine('X-Foo')); + } + + public function testWithoutHeader() + { + $headers = new Headers(); + $headers->addHeader('X-Foo', 'one'); + $headers->addHeader('X-Bar', 'two'); + $response = new MessageStub(); + $response->headers = $headers; + $clone = $response->withoutHeader('X-Foo'); + $shouldBe = [ + 'X-Bar' => ['two'], + ]; + + $this->assertEquals($shouldBe, $clone->getHeaders()); + } + + /** + * @doesNotPerformAssertions + */ + public function testWithoutHeaderByIncompatibleStringWithRFC() + { + $headers = new Headers(); + $response = new MessageStub(); + $response->headers = $headers; + $response->withoutHeader('getBody(); + $message = new MessageStub(); + $message->body = $body; + + $this->assertSame($body, $message->getBody()); + } + + public function testWithBody() + { + $body = $this->getBody(); + $body2 = $this->getBody(); + $message = new MessageStub(); + $message->body = $body; + $clone = $message->withBody($body2); + + $this->assertSame($body, $message->body); + $this->assertSame($body2, $clone->body); + } + + /** + * @return MockObject|Stream + */ + protected function getBody() + { + return $this + ->getMockBuilder(Stream::class) + ->disableOriginalConstructor() + ->getMock(); + } +} diff --git a/vendor/slim/psr7/tests/Mocks/MessageStub.php b/vendor/slim/psr7/tests/Mocks/MessageStub.php new file mode 100644 index 0000000..3672d84 --- /dev/null +++ b/vendor/slim/psr7/tests/Mocks/MessageStub.php @@ -0,0 +1,37 @@ +detach(), 'Returns null since there is no such underlying stream'); + self::assertNull($body->getSize(), 'Current size is undefined'); + self::assertSame(0, $body->tell(), 'Pointer is considered to be at position 0 to conform'); + self::assertTrue($body->eof(), 'Always considered to be at EOF'); + self::assertFalse($body->isSeekable(), 'Cannot seek'); + self::assertTrue($body->isWritable(), 'Body is writable'); + self::assertFalse($body->isReadable(), 'Body is not readable'); + self::assertSame('', $body->getContents(), 'Data cannot be retrieved once written'); + self::assertNull($body->getMetadata(), 'Metadata mechanism is not implemented'); + } + + public function testWrite() + { + $ob_initial_level = ob_get_level(); + + // Start output buffering. + ob_start(); + + // Start output buffering again to test the while-loop in the `write()` + // method that calls `ob_get_clean()` as long as the ob level is bigger + // than 0. + ob_start(); + echo 'buffer content: '; + + // Set the ob level shift that should be applied in the `ob_get_level()` + // function override. That way, the `write()` method would only flush + // the second ob, not the first one. We will add the initial ob level + // because phpunit may have started ob too. + $GLOBALS['ob_get_level_shift'] = -($ob_initial_level + 1); + + $body = new NonBufferedBody(); + $length0 = $body->write('hello '); + $length1 = $body->write('world'); + + unset($GLOBALS['ob_get_level_shift']); + $contents = ob_get_clean(); + + $this->assertEquals(strlen('buffer content: ') + strlen('hello '), $length0); + $this->assertEquals(strlen('world'), $length1); + $this->assertEquals('buffer content: hello world', $contents); + } + + public function testWithHeader() + { + (new Response()) + ->withBody(new NonBufferedBody()) + ->withHeader('Foo', 'Bar'); + + self::assertSame([ + [ + 'header' => 'Foo: Bar', + 'replace' => true, + 'status_code' => null + ] + ], HeaderStack::stack()); + } + + public function testWithAddedHeader() + { + (new Response()) + ->withBody(new NonBufferedBody()) + ->withHeader('Foo', 'Bar') + ->withAddedHeader('Foo', 'Baz'); + + self::assertSame([ + [ + 'header' => 'Foo: Bar', + 'replace' => true, + 'status_code' => null + ], + [ + 'header' => 'Foo: Bar,Baz', + 'replace' => true, + 'status_code' => null + ] + ], HeaderStack::stack()); + } + + public function testWithoutHeader() + { + (new Response()) + ->withBody(new NonBufferedBody()) + ->withHeader('Foo', 'Bar') + ->withoutHeader('Foo'); + + self::assertSame([], HeaderStack::stack()); + } + + public function testCloseThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('A NonBufferedBody is not closable.'); + + (new NonBufferedBody())->close(); + } + + public function testSeekThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('A NonBufferedBody is not seekable.'); + + (new NonBufferedBody())->seek(10); + } + + public function testRewindThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('A NonBufferedBody is not rewindable.'); + + (new NonBufferedBody())->rewind(); + } + + public function testReadThrowsRuntimeException() + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('A NonBufferedBody is not readable.'); + + (new NonBufferedBody())->read(10); + } +} diff --git a/vendor/slim/psr7/tests/RequestTest.php b/vendor/slim/psr7/tests/RequestTest.php new file mode 100644 index 0000000..da54f98 --- /dev/null +++ b/vendor/slim/psr7/tests/RequestTest.php @@ -0,0 +1,458 @@ +createUri('https://example.com:443/foo/bar?abc=123'); + $headers = Headers::createFromGlobals($env); + $cookies = [ + 'user' => 'john', + 'id' => '123', + ]; + $serverParams = $env; + $body = (new StreamFactory())->createStream(); + $uploadedFiles = UploadedFile::createFromGlobals($env); + $request = new Request('GET', $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles); + + return $request; + } + + public function testDisableSetter() + { + $request = $this->requestFactory(); + $request->foo = 'bar'; + + $this->assertFalse(property_exists($request, 'foo')); + } + + public function testAddsHostHeaderFromUri() + { + $request = $this->requestFactory(); + $this->assertEquals('example.com', $request->getHeaderLine('Host')); + } + + public function testGetMethod() + { + $this->assertEquals('GET', $this->requestFactory()->getMethod()); + } + + public function testWithMethod() + { + $request = $this->requestFactory()->withMethod('PUT'); + + $this->assertEquals('PUT', $request->getMethod()); + } + + public function testWithMethodCaseSensitive() + { + $request = $this->requestFactory()->withMethod('pOsT'); + + $this->assertEquals('pOsT', $request->getMethod()); + } + + public function testWithAllAllowedCharactersMethod() + { + $request = $this->requestFactory()->withMethod("!#$%&'*+.^_`|~09AZ-"); + + $this->assertEquals("!#$%&'*+.^_`|~09AZ-", $request->getMethod()); + } + + public function testWithMethodInvalid() + { + $this->expectException(InvalidArgumentException::class); + + $this->requestFactory()->withMethod('B@R'); + } + + public function testCreateRequestWithInvalidMethodString() + { + $this->expectException(InvalidArgumentException::class); + + $uri = (new UriFactory())->createUri('https://example.com:443/foo/bar?abc=123'); + $headers = new Headers(); + $cookies = []; + $serverParams = []; + $body = (new StreamFactory())->createStream(); + + new Request('B@R', $uri, $headers, $cookies, $serverParams, $body); + } + + public function testCreateRequestWithInvalidMethodOther() + { + $this->expectException(InvalidArgumentException::class); + + $uri = (new UriFactory())->createUri('https://example.com:443/foo/bar?abc=123'); + $headers = new Headers(); + $cookies = []; + $serverParams = []; + $body = (new StreamFactory())->createStream(); + + new Request(10, $uri, $headers, $cookies, $serverParams, $body); + } + + public function testGetRequestTarget() + { + $this->assertEquals('/foo/bar?abc=123', $this->requestFactory()->getRequestTarget()); + } + + public function testGetRequestTargetAlreadySet() + { + $request = $this->requestFactory(); + $prop = new ReflectionProperty($request, 'requestTarget'); + $prop->setAccessible(true); + $prop->setValue($request, '/foo/bar?abc=123'); + + $this->assertEquals('/foo/bar?abc=123', $request->getRequestTarget()); + } + + public function testGetRequestTargetIfNoUri() + { + $request = $this->requestFactory(); + $prop = new ReflectionProperty($request, 'uri'); + $prop->setAccessible(true); + $prop->setValue($request, null); + + $this->assertEquals('/', $request->getRequestTarget()); + } + + public function testWithRequestTarget() + { + $clone = $this->requestFactory()->withRequestTarget('/test?user=1'); + + $this->assertEquals('/test?user=1', $clone->getRequestTarget()); + } + + public function testWithRequestTargetThatHasSpaces() + { + $this->expectException(InvalidArgumentException::class); + + $this->requestFactory()->withRequestTarget('/test/m ore/stuff?user=1'); + } + + public function testGetUri() + { + $uri = (new UriFactory())->createUri('https://example.com:443/foo/bar?abc=123'); + $headers = new Headers(); + $cookies = []; + $serverParams = []; + $body = (new StreamFactory())->createStream(); + $request = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); + + $this->assertSame($uri, $request->getUri()); + } + + public function testWithUri() + { + // Uris + $uri1 = (new UriFactory())->createUri('https://example.com:443/foo/bar?abc=123'); + $uri2 = (new UriFactory())->createUri('https://example2.com:443/test?xyz=123'); + + // Request + $headers = new Headers(); + $cookies = []; + $serverParams = []; + $body = (new StreamFactory())->createStream(); + $request = new Request('GET', $uri1, $headers, $cookies, $serverParams, $body); + $clone = $request->withUri($uri2); + + $this->assertSame($uri2, $clone->getUri()); + } + + public function testWithUriPreservesHost() + { + // When `$preserveHost` is set to `true`, this method interacts with + // the Host header in the following ways: + + // - If the Host header is missing or empty, and the new URI contains + // a host component, this method MUST update the Host header in the returned + // request. + $uri1 = (new UriFactory())->createUri(''); + $uri2 = (new UriFactory())->createUri('http://example2.com/test'); + + // Request + $headers = new Headers(); + $cookies = []; + $serverParams = []; + $body = (new StreamFactory())->createStream(); + $request = new Request('GET', $uri1, $headers, $cookies, $serverParams, $body); + + $clone = $request->withUri($uri2, true); + $this->assertSame('example2.com', $clone->getHeaderLine('Host')); + + // - If the Host header is missing or empty, and the new URI does not contain a + // host component, this method MUST NOT update the Host header in the returned + // request. + $uri3 = (new UriFactory())->createUri(''); + + $clone = $request->withUri($uri3, true); + $this->assertSame('', $clone->getHeaderLine('Host')); + + // - If a Host header is present and non-empty, this method MUST NOT update + // the Host header in the returned request. + $request = $request->withHeader('Host', 'example.com'); + $clone = $request->withUri($uri2, true); + $this->assertSame('example.com', $clone->getHeaderLine('Host')); + } + + public function testGetCookieParams() + { + $shouldBe = [ + 'user' => 'john', + 'id' => '123', + ]; + + $this->assertEquals($shouldBe, $this->requestFactory()->getCookieParams()); + } + + public function testWithCookieParams() + { + $request = $this->requestFactory(); + $clone = $request->withCookieParams(['type' => 'framework']); + + $this->assertEquals(['type' => 'framework'], $clone->getCookieParams()); + } + + public function testGetQueryParams() + { + $this->assertEquals(['abc' => '123'], $this->requestFactory()->getQueryParams()); + } + + public function testGetQueryParamsAlreadySet() + { + $request = $this->requestFactory(); + $prop = new ReflectionProperty($request, 'queryParams'); + $prop->setAccessible(true); + $prop->setValue($request, ['foo' => 'bar']); + + $this->assertEquals(['foo' => 'bar'], $request->getQueryParams()); + } + + public function testWithQueryParams() + { + $request = $this->requestFactory(); + $clone = $request->withQueryParams(['foo' => 'bar']); + $cloneUri = $clone->getUri(); + + $this->assertEquals('abc=123', $cloneUri->getQuery()); // <-- Unchanged + $this->assertEquals(['foo' => 'bar'], $clone->getQueryParams()); // <-- Changed + } + + public function testWithQueryParamsEmptyArray() + { + $request = $this->requestFactory(); + $clone = $request->withQueryParams([]); + $cloneUri = $clone->getUri(); + + $this->assertEquals('abc=123', $cloneUri->getQuery()); // <-- Unchanged + $this->assertEquals([], $clone->getQueryParams()); // <-- Changed + } + + public function testGetQueryParamsWithoutUri() + { + $request = $this->requestFactory(); + $prop = new ReflectionProperty($request, 'uri'); + $prop->setAccessible(true); + $prop->setValue($request, null); + + $this->assertEquals([], $request->getQueryParams()); + } + + public function testWithUploadedFiles() + { + $files = [new UploadedFile('foo.txt'), new UploadedFile('bar.txt')]; + + $request = $this->requestFactory(); + $prevUploaded = $request->getUploadedFiles(); + $clone = $request->withUploadedFiles($files); + + $this->assertEquals($prevUploaded, $request->getUploadedFiles()); + $this->assertEquals($files, $clone->getUploadedFiles()); + } + + public function testGetServerParams() + { + $mockEnv = Environment::mock(["HTTP_AUTHORIZATION" => "test"]); + $request = $this->requestFactory(["HTTP_AUTHORIZATION" => "test"]); + + $serverParams = $request->getServerParams(); + foreach ($serverParams as $key => $value) { + if ($key == 'REQUEST_TIME' || $key == 'REQUEST_TIME_FLOAT') { + $this->assertGreaterThanOrEqual( + $mockEnv[$key], + $value, + sprintf("%s value of %s was less than expected value of %s", $key, $value, $mockEnv[$key]) + ); + } else { + $this->assertEquals( + $mockEnv[$key], + $value, + sprintf("%s value of %s did not equal expected value of %s", $key, $value, $mockEnv[$key]) + ); + } + } + } + + public function testGetAttributes() + { + $request = $this->requestFactory(); + $attrProp = new ReflectionProperty($request, 'attributes'); + $attrProp->setAccessible(true); + $attrProp->setValue($request, ['foo' => 'bar']); + + $this->assertEquals(['foo' => 'bar'], $request->getAttributes()); + } + + public function testGetAttribute() + { + $request = $this->requestFactory(); + $attrProp = new ReflectionProperty($request, 'attributes'); + $attrProp->setAccessible(true); + $attrProp->setValue($request, ['foo' => 'bar']); + + $this->assertEquals('bar', $request->getAttribute('foo')); + $this->assertNull($request->getAttribute('bar')); + $this->assertEquals(2, $request->getAttribute('bar', 2)); + } + + public function testWithAttribute() + { + $request = $this->requestFactory(); + $attrProp = new ReflectionProperty($request, 'attributes'); + $attrProp->setAccessible(true); + $attrProp->setValue($request, ['foo' => 'bar']); + $clone = $request->withAttribute('test', '123'); + + $this->assertEquals('123', $clone->getAttribute('test')); + } + + public function testWithoutAttribute() + { + $request = $this->requestFactory(); + $attrProp = new ReflectionProperty($request, 'attributes'); + $attrProp->setAccessible(true); + $attrProp->setValue($request, ['foo' => 'bar']); + $clone = $request->withoutAttribute('foo'); + + $this->assertNull($clone->getAttribute('foo')); + } + + public function testGetParsedBodyWhenAlreadyParsed() + { + $request = $this->requestFactory(); + $prop = new ReflectionProperty($request, 'parsedBody'); + $prop->setAccessible(true); + $prop->setValue($request, ['foo' => 'bar']); + + $this->assertEquals(['foo' => 'bar'], $request->getParsedBody()); + } + + public function testGetParsedBodyWhenBodyDoesNotExist() + { + $request = $this->requestFactory(); + $prop = new ReflectionProperty($request, 'body'); + $prop->setAccessible(true); + $prop->setValue($request, null); + + $this->assertNull($request->getParsedBody()); + } + + public function testWithParsedBody() + { + $clone = $this->requestFactory()->withParsedBody(['xyz' => '123']); + + $this->assertEquals(['xyz' => '123'], $clone->getParsedBody()); + } + + public function testWithParsedBodyEmptyArray() + { + $method = 'GET'; + $uri = new Uri('https', 'example.com', 443, '/foo/bar', 'abc=123', '', ''); + $headers = new Headers(); + $headers->setHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf8'); + $cookies = []; + $serverParams = []; + $body = (new StreamFactory())->createStream(); + $body->write('foo=bar'); + $request = new Request($method, $uri, $headers, $cookies, $serverParams, $body); + + $clone = $request->withParsedBody([]); + + $this->assertEquals([], $clone->getParsedBody()); + } + + public function testWithParsedBodyNull() + { + $method = 'GET'; + $uri = new Uri('https', 'example.com', 443, '/foo/bar', 'abc=123', '', ''); + $headers = new Headers(); + $headers->setHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf8'); + $cookies = []; + $serverParams = []; + $body = (new StreamFactory())->createStream(); + $body->write('foo=bar'); + $request = new Request($method, $uri, $headers, $cookies, $serverParams, $body); + + $clone = $request->withParsedBody(null); + + $this->assertNull($clone->getParsedBody()); + } + + public function testGetParsedBodyReturnsNullWhenThereIsNoBodyData() + { + $request = $this->requestFactory(['REQUEST_METHOD' => 'POST']); + + $this->assertNull($request->getParsedBody()); + } + + public function testGetParsedBodyReturnsNullWhenThereIsNoMediaTypeParserRegistered() + { + $request = $this->requestFactory([ + 'REQUEST_METHOD' => 'POST', + 'CONTENT_TYPE' => 'text/csv', + ]); + $request->getBody()->write('foo,bar,baz'); + + $this->assertNull($request->getParsedBody()); + } + + public function testWithParsedBodyInvalid() + { + $this->expectException(InvalidArgumentException::class); + + $this->requestFactory()->withParsedBody(2); + } + + public function testWithParsedBodyInvalidFalseValue() + { + $this->expectException(InvalidArgumentException::class); + + $this->requestFactory()->withParsedBody(false); + } +} diff --git a/vendor/slim/psr7/tests/ResponseTest.php b/vendor/slim/psr7/tests/ResponseTest.php new file mode 100644 index 0000000..7bd3206 --- /dev/null +++ b/vendor/slim/psr7/tests/ResponseTest.php @@ -0,0 +1,196 @@ +setAccessible(true); + + $bodyReflection = new ReflectionProperty($response, 'body'); + $bodyReflection->setAccessible(true); + + $this->assertEquals(200, $response->getStatusCode()); + $this->assertInstanceOf(Headers::class, $headersReflection->getValue($response)); + $this->assertInstanceOf(Stream::class, $bodyReflection->getValue($response)); + } + + public function testConstructorWithCustomArgs() + { + $headers = new Headers(); + $body = new Stream(fopen('php://temp', 'r+')); + $response = new Response(404, $headers, $body); + + $headersReflection = new ReflectionProperty($response, 'headers'); + $headersReflection->setAccessible(true); + + $bodyReflection = new ReflectionProperty($response, 'body'); + $bodyReflection->setAccessible(true); + + $this->assertEquals(404, $response->getStatusCode()); + $this->assertSame($headers, $headersReflection->getValue($response)); + $this->assertSame($body, $bodyReflection->getValue($response)); + } + + public function testDeepCopyClone() + { + $headers = new Headers(); + $body = new Stream(fopen('php://temp', 'r+')); + $response = new Response(404, $headers, $body); + $clone = clone $response; + + $headersReflection = new ReflectionProperty($response, 'headers'); + $headersReflection->setAccessible(true); + + $this->assertEquals(404, $clone->getStatusCode()); + $this->assertEquals('1.1', $clone->getProtocolVersion()); + $this->assertNotSame($headers, $headersReflection->getValue($clone)); + } + + public function testDisableSetter() + { + $response = new Response(); + $response->foo = 'bar'; + + $this->assertFalse(property_exists($response, 'foo')); + } + + public function testGetStatusCode() + { + $response = new Response(); + $responseStatus = new ReflectionProperty($response, 'status'); + $responseStatus->setAccessible(true); + $responseStatus->setValue($response, 404); + + $this->assertEquals(404, $response->getStatusCode()); + } + + public function testWithStatus() + { + $response = new Response(); + $clone = $response->withStatus(302); + + $this->assertEquals(302, $clone->getStatusCode()); + } + + public function testWithStatusInvalidStatusCodeThrowsException() + { + $this->expectException(InvalidArgumentException::class); + + $response = new Response(); + $response->withStatus(800); + } + + public function testWithStatusInvalidReasonPhraseThrowsException() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Response reason phrase must be a string'); + + $response = new Response(); + $response->withStatus(200, null); + } + + public function testWithStatusEmptyReasonPhrase() + { + $responseWithNoMessage = new Response(310); + + $this->assertEquals('', $responseWithNoMessage->getReasonPhrase()); + } + + public function testReasonPhraseContainsCarriageReturn() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Reason phrase contains one of the following prohibited characters: \r \n'); + + $response = new Response(); + $response = $response->withStatus(404, "Not Found\r"); + } + + public function testReasonPhraseContainsLineFeed() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Reason phrase contains one of the following prohibited characters: \r \n'); + + $response = new Response(); + $response = $response->withStatus(404, "Not Found\n"); + } + + public function testWithStatusValidReasonPhraseObject() + { + $mock = $this->getMockBuilder(stdClass::class)->addMethods(['__toString'])->getMock(); + $mock->expects($this->once()) + ->method('__toString') + ->will($this->returnValue('Slim OK')); + + $response = new Response(); + $response = $response->withStatus(200, $mock); + $this->assertEquals('Slim OK', $response->getReasonPhrase()); + } + + public function testGetReasonPhrase() + { + $response = new Response(404); + + $this->assertEquals('Not Found', $response->getReasonPhrase()); + } + + public function testEmptyReasonPhraseForUnrecognisedCode() + { + $response = new Response(); + $response = $response->withStatus(199); + + $this->assertSame('', $response->getReasonPhrase()); + } + + public function testSetReasonPhraseForUnrecognisedCode() + { + $response = new Response(); + $response = $response->withStatus(199, 'Random Message'); + + $this->assertEquals('Random Message', $response->getReasonPhrase()); + } + + public function testGetCustomReasonPhrase() + { + $response = new Response(); + $clone = $response->withStatus(200, 'Custom Phrase'); + + $this->assertEquals('Custom Phrase', $clone->getReasonPhrase()); + } + + public function testResponseHeadersDoNotContainAuthorizationHeader() + { + $_SERVER = Environment::mock( + [ + 'PHP_AUTH_USER' => 'foo' + ] + ); + + $response = new Response(); + $this->assertEmpty($response->getHeaders()); + } +} diff --git a/vendor/slim/psr7/tests/StreamTest.php b/vendor/slim/psr7/tests/StreamTest.php new file mode 100644 index 0000000..0a97197 --- /dev/null +++ b/vendor/slim/psr7/tests/StreamTest.php @@ -0,0 +1,284 @@ +pipeFh != null) { + // prevent broken pipe error message + stream_get_contents($this->pipeFh); + } + } + + public function testIsPipe() + { + $this->openPipeStream(); + + $this->assertTrue($this->pipeStream->isPipe()); + + $this->pipeStream->detach(); + $this->assertFalse($this->pipeStream->isPipe()); + + $fhFile = fopen(__FILE__, 'r'); + $fileStream = new Stream($fhFile); + $this->assertFalse($fileStream->isPipe()); + } + + public function testIsPipeReadable() + { + $this->openPipeStream(); + + $this->assertTrue($this->pipeStream->isReadable()); + } + + public function testPipeIsNotSeekable() + { + $this->openPipeStream(); + + $this->assertFalse($this->pipeStream->isSeekable()); + } + + public function testCannotSeekPipe() + { + $this->expectException(RuntimeException::class); + + $this->openPipeStream(); + + $this->pipeStream->seek(0); + } + + public function testCannotTellPipe() + { + $this->expectException(RuntimeException::class); + + $this->openPipeStream(); + + $this->pipeStream->tell(); + } + + public function testCannotRewindPipe() + { + $this->expectException(RuntimeException::class); + + $this->openPipeStream(); + + $this->pipeStream->rewind(); + } + + public function testPipeGetSizeYieldsNull() + { + $this->openPipeStream(); + + $this->assertNull($this->pipeStream->getSize()); + } + + public function testClosePipe() + { + $this->openPipeStream(); + + // prevent broken pipe error message + stream_get_contents($this->pipeFh); + + $this->pipeStream->close(); + $this->pipeFh = null; + + $this->assertFalse($this->pipeStream->isPipe()); + } + + public function testPipeToString() + { + $this->openPipeStream(); + $content = trim((string) $this->pipeStream); + + $this->assertSame('12', $content); + } + + public function testConvertsToStringPartiallyReadNonSeekableStream() + { + $this->openPipeStream(); + $head = $this->pipeStream->read(1); + $tail = trim((string) $this->pipeStream); + + $this->assertSame('1', $head); + $this->assertSame('2', $tail); + } + + public function testPipeGetContents() + { + $this->openPipeStream(); + + $contents = trim($this->pipeStream->getContents()); + $this->assertSame('12', $contents); + } + + public function testIsWriteable() + { + $resource = fopen('php://temp', 'w'); + $stream = new Stream($resource); + + $this->assertEquals(13, $stream->write('Hello, world!')); + + $this->assertTrue($stream->isWritable()); + } + + public function testIsReadable() + { + $resource = fopen('php://temp', 'r'); + $stream = new Stream($resource); + + $this->assertTrue($stream->isReadable()); + $this->assertFalse($stream->isWritable()); + } + + public function testIsWritableAndReadable() + { + $resource = fopen('php://temp', 'w+'); + $stream = new Stream($resource); + + $stream->write('Hello, world!'); + + $this->assertEquals('Hello, world!', $stream); + + $this->assertTrue($stream->isWritable()); + $this->assertTrue($stream->isReadable()); + } + + /** + * Test that a call to the protected method `attach` would invoke `detach`. + * + * @throws ReflectionException + */ + public function testAttachAgain() + { + $this->openPipeStream(); + + $streamProphecy = $this->prophesize(Stream::class); + + /** @noinspection PhpUndefinedMethodInspection */ + $streamProphecy->detach()->shouldBeCalled(); + + /** @var Stream $stream */ + $stream = $streamProphecy->reveal(); + + $streamProperty = new ReflectionProperty(Stream::class, 'stream'); + $streamProperty->setAccessible(true); + $streamProperty->setValue($stream, $this->pipeFh); + + $attachMethod = new ReflectionMethod(Stream::class, 'attach'); + $attachMethod->setAccessible(true); + $attachMethod->invoke($stream, $this->pipeFh); + } + + public function testGetMetaDataReturnsNullIfStreamIsDetached() + { + $resource = fopen('php://temp', 'rw+'); + $stream = new Stream($resource); + $stream->detach(); + + $this->assertNull($stream->getMetadata()); + } + + private function openPipeStream() + { + $this->pipeFh = popen('echo 12', 'r'); + $this->pipeStream = new Stream($this->pipeFh); + } + + public function testReadOnlyCachedStreamsAreDisallowed() + { + $resource = fopen('php://temp', 'w+'); + $cache = new Stream(fopen('php://temp', 'r')); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Cache stream must be seekable and writable'); + new Stream($resource, $cache); + } + + public function testNonSeekableCachedStreamsAreDisallowed() + { + $resource = fopen('php://temp', 'w+'); + $cache = new Stream(fopen('php://output', 'w')); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Cache stream must be seekable and writable'); + + new Stream($resource, $cache); + } + + public function testCachedStreamsGetsContentFromTheCache() + { + $resource = popen('echo HelloWorld', 'r'); + $stream = new Stream($resource, new Stream(fopen('php://temp', 'w+'))); + + $this->assertEquals("HelloWorld\n", $stream->getContents()); + $this->assertEquals("HelloWorld\n", $stream->getContents()); + } + + public function testCachedStreamsFillsCacheOnRead() + { + $resource = fopen('data://,0', 'r'); + $stream = new Stream($resource, new Stream(fopen('php://temp', 'w+'))); + + $this->assertEquals("0", $stream->read(100)); + $this->assertEquals("0", $stream->__toString()); + } + + public function testDetachingStreamDropsCache() + { + $cache = new Stream(fopen('php://temp', 'w+')); + $resource = fopen('data://,foo', 'r'); + $stream = new Stream($resource, $cache); + + $stream->detach(); + + $cacheProperty = new ReflectionProperty(Stream::class, 'cache'); + $cacheProperty->setAccessible(true); + $finishedProperty = new ReflectionProperty(Stream::class, 'finished'); + $finishedProperty->setAccessible(true); + + $this->assertNull($cacheProperty->getValue($stream)); + $this->assertFalse($finishedProperty->getValue($stream)); + } + + public function testCachedStreamsRewindIfFinishedOnToString() + { + $resource = fopen('data://,foo', 'r'); + + $stream = new Stream($resource, new Stream(fopen('php://temp', 'w+'))); + + $this->assertEquals('foo', (string)$stream); + $this->assertEquals('foo', (string)$stream); + } +} diff --git a/vendor/slim/psr7/tests/UploadedFileTest.php b/vendor/slim/psr7/tests/UploadedFileTest.php new file mode 100644 index 0000000..ec90abc --- /dev/null +++ b/vendor/slim/psr7/tests/UploadedFileTest.php @@ -0,0 +1,676 @@ +assertEquals($expected, $uploadedFile); + } + + /** + * @param array $input The input array to parse. + * + * @dataProvider providerCreateFromGlobals + */ + public function testCreateFromGlobalsFromUserData(array $input) + { + //If slim.files provided - it will return what was provided + $userData['slim.files'] = $input; + + $uploadedFile = UploadedFile::createFromGlobals(Environment::mock($userData)); + $this->assertEquals($input, $uploadedFile); + } + + public function testCreateFromGlobalsWithoutFile() + { + unset($_FILES); + + $uploadedFile = UploadedFile::createFromGlobals(Environment::mock()); + $this->assertEquals([], $uploadedFile); + } + + public function testConstructor(): UploadedFile + { + $attr = [ + 'tmp_name' => self::$filename, + 'name' => 'my-avatar.txt', + 'size' => 8, + 'type' => 'text/plain', + 'error' => 0, + ]; + + $uploadedFile = new UploadedFile( + $attr['tmp_name'], + $attr['name'], + $attr['type'], + $attr['size'], + $attr['error'], + false + ); + + $this->assertEquals($attr['name'], $uploadedFile->getClientFilename()); + $this->assertEquals($attr['type'], $uploadedFile->getClientMediaType()); + $this->assertEquals($attr['size'], $uploadedFile->getSize()); + $this->assertEquals($attr['error'], $uploadedFile->getError()); + $this->assertEquals($attr['tmp_name'], $uploadedFile->getFilePath()); + + return $uploadedFile; + } + + public function testConstructorSapi(): UploadedFile + { + $attr = [ + 'tmp_name' => self::$filename, + 'name' => 'my-avatar.txt', + 'size' => 8, + 'type' => 'text/plain', + 'error' => 0, + ]; + + $uploadedFile = new UploadedFile( + $attr['tmp_name'], + $attr['name'], + $attr['type'], + $attr['size'], + $attr['error'], + true + ); + + $this->assertEquals($attr['name'], $uploadedFile->getClientFilename()); + $this->assertEquals($attr['type'], $uploadedFile->getClientMediaType()); + $this->assertEquals($attr['size'], $uploadedFile->getSize()); + $this->assertEquals($attr['error'], $uploadedFile->getError()); + $this->assertEquals($attr['tmp_name'], $uploadedFile->getFilePath()); + + return $uploadedFile; + } + + /** + * @depends testConstructor + * + * @param UploadedFile $uploadedFile + * + * @return UploadedFile + */ + public function testGetStream(UploadedFile $uploadedFile): UploadedFile + { + $stream = $uploadedFile->getStream(); + $this->assertEquals(true, $uploadedFile->getStream() instanceof Stream); + $stream->close(); + + return $uploadedFile; + } + + /** + * @depends testConstructor + * + * @param UploadedFile $uploadedFile + * + */ + public function testMoveToNotWritable(UploadedFile $uploadedFile) + { + $this->expectException(InvalidArgumentException::class); + + $tempName = uniqid('file-'); + $path = 'some_random_dir' . DIRECTORY_SEPARATOR . $tempName; + $uploadedFile->moveTo($path); + } + + /** + * @depends testConstructor + * + * @param UploadedFile $uploadedFile + * + * @return UploadedFile + */ + public function testMoveTo(UploadedFile $uploadedFile): UploadedFile + { + $tempName = uniqid('file-'); + $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempName; + $uploadedFile->moveTo($path); + + $this->assertFileExists($path); + + unlink($path); + + return $uploadedFile; + } + + public function testMoveToRenameFailure() + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessageMatches('/^Error moving uploaded file .* to .*$/'); + + $uploadedFile = $this->generateNewTmpFile(); + + $tempName = uniqid('file-'); + $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempName; + + $GLOBALS['rename_return'] = false; + $uploadedFile->moveTo($path); + } + + /** + * @depends testConstructorSapi + * + * @param UploadedFile $uploadedFile + * + */ + public function testMoveToSapiNonUploadedFile(UploadedFile $uploadedFile) + { + $this->expectException(RuntimeException::class); + + $tempName = uniqid('file-'); + $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempName; + $uploadedFile->moveTo($path); + } + + /** + * @depends testConstructorSapi + * + * @param UploadedFile $uploadedFile + * + */ + public function testMoveToSapiMoveUploadedFileFails(UploadedFile $uploadedFile) + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessageMatches('~Error moving uploaded file.*~'); + + $GLOBALS['is_uploaded_file_return'] = true; + + $tempName = uniqid('file-'); + $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempName; + $uploadedFile->moveTo($path); + } + + /** + * @depends testMoveTo + * + * @param UploadedFile $uploadedFile + * + */ + public function testMoveToCannotBeDoneTwice(UploadedFile $uploadedFile) + { + $this->expectException(RuntimeException::class); + + $tempName = uniqid('file-'); + $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempName; + $uploadedFile->moveTo($path); + $this->assertFileExists($path); + unlink($path); + + $uploadedFile->moveTo($path); + } + + /** + * This test must run after testMoveTo + * + * @depends testConstructor + * + * @param UploadedFile $uploadedFile + * + */ + public function testMoveToAgain(UploadedFile $uploadedFile) + { + $this->expectException(RuntimeException::class); + + $tempName = uniqid('file-'); + $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempName; + $uploadedFile->moveTo($path); + } + + /** + * This test must run after testMoveTo + * + * @depends testConstructor + * + * @param UploadedFile $uploadedFile + * + */ + public function testMovedStream(UploadedFile $uploadedFile) + { + $this->expectException(RuntimeException::class); + + $uploadedFile->getStream(); + } + + public function testMoveToStream() + { + $uploadedFile = $this->generateNewTmpFile(); + + $fileProperty = new ReflectionProperty($uploadedFile, 'file'); + $fileProperty->setAccessible(true); + $fileName = $fileProperty->getValue($uploadedFile); + + $contents = file_get_contents($fileName); + + ob_start(); + $uploadedFile->moveTo('php://output'); + $movedFileContents = ob_get_clean(); + + $this->assertEquals($contents, $movedFileContents); + $this->assertFileDoesNotExist($fileName); + } + + public function testMoveToStreamCopyFailure() + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Error moving uploaded file to php://output'); + + $uploadedFile = $this->generateNewTmpFile(); + + $GLOBALS['copy_return'] = false; + $uploadedFile->moveTo('php://output'); + } + + public function testFileUploadWithTempStream() + { + $streamFactory = function (...$args) { + return (new StreamFactory())->createStream(...$args); + }; + $uploadedFileFactory = function (...$args) { + return (new UploadedFileFactory())->createUploadedFile(...$args); + }; + $this->runFileUploadWithTempStreamTest($streamFactory, $uploadedFileFactory); + } + + /** + * This test sequence has been inspired by UploadedFileFactoryTestCase from http-interop/http-factory-tests package. + * + * @param callable $streamFactory + * @param callable $uploadedFileFactory + */ + private function runFileUploadWithTempStreamTest(callable $streamFactory, callable $uploadedFileFactory) + { + $content = 'this is your capitan speaking'; + $error = UPLOAD_ERR_OK; + $clientFilename = 'test.txt'; + $clientMediaType = 'text/plain'; + + $stream = call_user_func($streamFactory, $content); + $file = call_user_func( + $uploadedFileFactory, + $stream, + strlen($content), + $error, + $clientFilename, + $clientMediaType + ); + + $this->assertInstanceOf(UploadedFileInterface::class, $file); + $this->assertSame($content, (string)$file->getStream()); + $this->assertSame(strlen($content), $file->getSize()); + $this->assertSame($error, $file->getError()); + $this->assertSame($clientFilename, $file->getClientFilename()); + $this->assertSame($clientMediaType, $file->getClientMediaType()); + $this->assertSame($stream->getMetadata('uri'), $file->getFilePath()); + } + + public function testCreateUploadedFileWithInvalidArguments() + { + $this->expectException(InvalidArgumentException::class); + + new UploadedFile(42); // a random value that is neither a string nor an instance of StreamInterface + } + + public function testCreateUploadedFileWithInvalidUri() + { + $this->expectException(InvalidArgumentException::class); + + $streamProphecy = $this->prophesize(StreamInterface::class); + + /** @noinspection PhpUndefinedMethodInspection */ + $streamProphecy + ->getMetadata('uri') + ->willReturn(null) + ->shouldBeCalled(); + $stream = $streamProphecy->reveal(); + + // Test with a StreamInterface that returns `null` + // when `$stream->getMetadata('uri')` is called (which is an invalid case). + new UploadedFile($stream); + } + + public function providerCreateFromGlobals(): array + { + return [ + // no nest: + [ + // $_FILES array + [ + 'avatar' => [ + 'tmp_name' => 'phpUxcOty', + 'name' => 'my-avatar.png', + 'size' => 90996, + 'type' => 'image/png', + 'error' => 0, + ], + ], + // expected format of array + [ + 'avatar' => new UploadedFile('phpUxcOty', 'my-avatar.png', 'image/png', 90996, UPLOAD_ERR_OK, true) + ] + ], + // no nest, with error: + [ + // $_FILES array + [ + 'avatar' => [ + 'tmp_name' => 'phpUxcOty', + 'name' => 'my-avatar.png', + 'size' => 90996, + 'type' => 'image/png', + 'error' => 7, + ], + ], + // expected format of array + [ + 'avatar' => new UploadedFile( + 'phpUxcOty', + 'my-avatar.png', + 'image/png', + 90996, + UPLOAD_ERR_CANT_WRITE, + true + ) + ] + ], + + // array of files: + [ + // $_FILES array + [ + 'avatars' => [ + 'tmp_name' => [ + 0 => __DIR__ . DIRECTORY_SEPARATOR . 'file0.txt', + 1 => __DIR__ . DIRECTORY_SEPARATOR . 'file1.html', + ], + 'name' => [ + 0 => 'file0.txt', + 1 => 'file1.html', + ], + 'type' => [ + 0 => 'text/plain', + 1 => 'text/html', + ], + 'error' => [ + 0 => 0, + 1 => 0 + ], + 'size' => [ + 0 => 0, + 1 => 0 + ] + ], + ], + // expected format of array + [ + 'avatars' => [ + 0 => new UploadedFile( + __DIR__ . DIRECTORY_SEPARATOR . 'file0.txt', + 'file0.txt', + 'text/plain', + null, + UPLOAD_ERR_OK, + true + ), + 1 => new UploadedFile( + __DIR__ . DIRECTORY_SEPARATOR . 'file1.html', + 'file1.html', + 'text/html', + null, + UPLOAD_ERR_OK, + true + ), + ], + ] + ], + // array of files as multidimensional array: + [ + // $_FILES array + [ + [ + 'avatars' => [ + 'tmp_name' => [ + 0 => __DIR__ . DIRECTORY_SEPARATOR . 'file0.txt', + 1 => __DIR__ . DIRECTORY_SEPARATOR . 'file1.html', + ], + 'name' => [ + 0 => 'file0.txt', + 1 => 'file1.html', + ], + 'type' => [ + 0 => 'text/plain', + 1 => 'text/html', + ], + 'size' => [ + 0 => 0, + 1 => 0, + ], + ], + ], + ], + // expected format of array + [ + 0 => + [ + 'avatars' => + [ + 'tmp_name' => [], + 'name' => [], + 'type' => [], + 'size' => [], + ], + ], + ], + ], + // single nested file: + [ + // $_FILES array + [ + 'details' => [ + 'tmp_name' => [ + 'avatar' => __DIR__ . DIRECTORY_SEPARATOR . 'file0.txt', + ], + 'name' => [ + 'avatar' => 'file0.txt', + ], + 'type' => [ + 'avatar' => 'text/plain', + ], + 'error' => [ + 'avatar' => 0, + ], + 'size' => [ + 'avatar' => 0, + ], + ], + ], + // expected format of array + [ + 'details' => [ + 'avatar' => new UploadedFile( + __DIR__ . DIRECTORY_SEPARATOR . 'file0.txt', + 'file0.txt', + 'text/plain', + null, + UPLOAD_ERR_OK, + true + ), + ], + ] + ], + // nested array of files: + [ + [ + 'files' => [ + 'tmp_name' => [ + 'details' => [ + 'avatar' => [ + 0 => __DIR__ . DIRECTORY_SEPARATOR . 'file0.txt', + 1 => __DIR__ . DIRECTORY_SEPARATOR . 'file1.html', + ], + ], + ], + 'name' => [ + 'details' => [ + 'avatar' => [ + 0 => 'file0.txt', + 1 => 'file1.html', + ], + ], + ], + 'type' => [ + 'details' => [ + 'avatar' => [ + 0 => 'text/plain', + 1 => 'text/html', + ], + ], + ], + 'error' => [ + 'details' => [ + 'avatar' => [ + 0 => 0, + 1 => 0 + ], + ], + ], + 'size' => [ + 'details' => [ + 'avatar' => [ + 0 => 0, + 1 => 0 + ], + ], + ], + ], + ], + // expected format of array + [ + 'files' => [ + 'details' => [ + 'avatar' => [ + 0 => new UploadedFile( + __DIR__ . DIRECTORY_SEPARATOR . 'file0.txt', + 'file0.txt', + 'text/plain', + null, + UPLOAD_ERR_OK, + true + ), + 1 => new UploadedFile( + __DIR__ . DIRECTORY_SEPARATOR . 'file1.html', + 'file1.html', + 'text/html', + null, + UPLOAD_ERR_OK, + true + ), + ], + ], + ], + ] + ], + ]; + } +} diff --git a/vendor/slim/psr7/tests/UriTest.php b/vendor/slim/psr7/tests/UriTest.php new file mode 100644 index 0000000..92077ec --- /dev/null +++ b/vendor/slim/psr7/tests/UriTest.php @@ -0,0 +1,392 @@ + 80, + 'wss' => 443, + ]; + }; + + $this->assertEquals('ws', $wsUri->getScheme()); + } + + public function testGetScheme() + { + $this->assertEquals('https', $this->uriFactory()->getScheme()); + } + + public function testWithScheme() + { + $uri = $this->uriFactory()->withScheme('http'); + + $this->assertEquals('http', $uri->getScheme()); + } + + public function testWithSchemeRemovesSuffix() + { + $uri = $this->uriFactory()->withScheme('http://'); + + $this->assertEquals('http', $uri->getScheme()); + } + + public function testWithSchemeEmpty() + { + $uri = $this->uriFactory()->withScheme(''); + + $this->assertEquals('', $uri->getScheme()); + } + + public function testWithSchemeInvalid() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageMatches('/^Uri scheme must be one of:.*$/'); + + $this->uriFactory()->withScheme('ftp'); + } + + public function testWithSchemeInvalidType() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Uri scheme must be a string'); + + $this->uriFactory()->withScheme([]); + } + + public function testGetAuthorityWithUsernameAndPassword() + { + $this->assertEquals('josh:sekrit@example.com', $this->uriFactory()->getAuthority()); + } + + public function testWithUserInfo() + { + $uri = $this->uriFactory()->withUserInfo('bob', 'pass'); + + $this->assertEquals('bob:pass', $uri->getUserInfo()); + } + + public function testWithUserInfoEncodesCorrectly() + { + $uri = $this->uriFactory()->withUserInfo('bob@example.com', 'pass:word'); + + $this->assertEquals('bob%40example.com:pass%3Aword', $uri->getUserInfo()); + } + + public function testWithUserInfoRemovesPassword() + { + $uri = $this->uriFactory()->withUserInfo('bob'); + + $this->assertEquals('bob', $uri->getUserInfo()); + } + + public function testWithUserInfoRemovesInfo() + { + $uri = $this->uriFactory()->withUserInfo('bob', 'password'); + $uri = $uri->withUserInfo(''); + + $this->assertEquals('', $uri->getUserInfo()); + } + + public function testGetHost() + { + $this->assertEquals('example.com', $this->uriFactory()->getHost()); + } + + public function testWithHost() + { + $uri = $this->uriFactory()->withHost('slimframework.com'); + + $this->assertEquals('slimframework.com', $uri->getHost()); + } + + public function testWithHostValidObject() + { + $mock = $this->getMockBuilder(stdClass::class)->addMethods(['__toString'])->getMock(); + $mock->expects($this->once()) + ->method('__toString') + ->will($this->returnValue('host.test')); + + $uri = $this->uriFactory()->withHost($mock); + $this->assertEquals('host.test', $uri->getHost()); + } + + public function testWithHostInvalidObject() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Uri host must be a string'); + + $this->uriFactory()->withHost(new stdClass()); + } + + public function testFilterHost() + { + $uri = new Uri('http', '2001:db8::1'); + + $this->assertEquals('[2001:db8::1]', $uri->getHost()); + } + + public function testGetPortWithSchemeAndNonDefaultPort() + { + $uri = new Uri('https', 'www.example.com', 4000); + + $this->assertEquals(4000, $uri->getPort()); + } + + public function testGetPortWithSchemeAndDefaultPort() + { + $uriHttp = new Uri('http', 'www.example.com', 80); + $uriHttps = new Uri('https', 'www.example.com', 443); + + $this->assertNull($uriHttp->getPort()); + $this->assertNull($uriHttps->getPort()); + } + + public function testGetPortWithoutSchemeAndPort() + { + $uri = new Uri('', 'www.example.com'); + + $this->assertNull($uri->getPort()); + } + + public function testGetPortWithSchemeWithoutPort() + { + $uri = new Uri('http', 'www.example.com'); + + $this->assertNull($uri->getPort()); + } + + public function testWithPort() + { + $uri = $this->uriFactory()->withPort(8000); + + $this->assertEquals(8000, $uri->getPort()); + } + + public function testWithPortNull() + { + $uri = $this->uriFactory()->withPort(null); + + $this->assertEquals(null, $uri->getPort()); + } + + public function testWithPortInvalidInt() + { + $this->expectException(InvalidArgumentException::class); + + $this->uriFactory()->withPort(70000); + } + + public function testWithPortInvalidString() + { + $this->expectException(InvalidArgumentException::class); + + $this->uriFactory()->withPort('Foo'); + } + + public function testWithPortIntegerAsString() + { + $uri = $this->uriFactory()->withPort("199"); + + $this->assertEquals(199, $uri->getPort()); + } + + public function testGetPath() + { + $this->assertEquals('/foo/bar', $this->uriFactory()->getPath()); + } + + public function testWithPath() + { + $uri = $this->uriFactory()->withPath('/new'); + + $this->assertEquals('/new', $uri->getPath()); + } + + public function testWithPathWithoutPrefix() + { + $uri = $this->uriFactory()->withPath('new'); + + $this->assertEquals('new', $uri->getPath()); + } + + public function testWithPathEmptyValue() + { + $uri = $this->uriFactory()->withPath(''); + + $this->assertEquals('', $uri->getPath()); + } + + public function testWithPathUrlEncodesInput() + { + $uri = $this->uriFactory()->withPath('/includes?/new'); + + $this->assertEquals('/includes%3F/new', $uri->getPath()); + } + + public function testWithPathDoesNotDoubleEncodeInput() + { + $uri = $this->uriFactory()->withPath('/include%25s/new'); + + $this->assertEquals('/include%25s/new', $uri->getPath()); + } + + public function testWithPathInvalidType() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Uri path must be a string'); + + $this->uriFactory()->withPath(['foo']); + } + + public function testGetQuery() + { + $this->assertEquals('abc=123', $this->uriFactory()->getQuery()); + } + + public function testWithQuery() + { + $uri = $this->uriFactory()->withQuery('xyz=123'); + + $this->assertEquals('xyz=123', $uri->getQuery()); + } + + public function testWithQueryRemovesPrefix() + { + $uri = $this->uriFactory()->withQuery('?xyz=123'); + + $this->assertEquals('xyz=123', $uri->getQuery()); + } + + public function testWithQueryEmpty() + { + $uri = $this->uriFactory()->withQuery(''); + + $this->assertEquals('', $uri->getQuery()); + } + + public function testWithQueryValidObject() + { + $mock = $this->getMockBuilder(stdClass::class)->addMethods(['__toString'])->getMock(); + $mock->expects($this->once()) + ->method('__toString') + ->will($this->returnValue('xyz=123')); + + $uri = $this->uriFactory()->withQuery($mock); + $this->assertEquals('xyz=123', $uri->getQuery()); + } + + public function testFilterQuery() + { + $uri = $this->uriFactory()->withQuery('?foobar=%match'); + + $this->assertEquals('foobar=%25match', $uri->getQuery()); + } + + public function testWithQueryInvalidType() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Uri query must be a string'); + + $this->uriFactory()->withQuery(['foo']); + } + + public function testGetFragment() + { + $this->assertEquals('section3', $this->uriFactory()->getFragment()); + } + + public function testWithFragment() + { + $uri = $this->uriFactory()->withFragment('other-fragment'); + + $this->assertEquals('other-fragment', $uri->getFragment()); + } + + public function testWithFragmentRemovesPrefix() + { + $uri = $this->uriFactory()->withFragment('#other-fragment'); + + $this->assertEquals('other-fragment', $uri->getFragment()); + } + + public function testWithFragmentEmpty() + { + $uri = $this->uriFactory()->withFragment(''); + + $this->assertEquals('', $uri->getFragment()); + } + + public function testWithFragmentValidObject() + { + $mock = $this->getMockBuilder(stdClass::class)->addMethods(['__toString'])->getMock(); + $mock->expects($this->once()) + ->method('__toString') + ->will($this->returnValue('other-fragment')); + + $uri = $this->uriFactory()->withFragment($mock); + $this->assertEquals('other-fragment', $uri->getFragment()); + } + + public function testWithFragmentUrlEncode() + { + $uri = $this->uriFactory()->withFragment('^a'); + + $this->assertEquals('%5Ea', $uri->getFragment()); + } + + public function testWithFragmentInvalidType() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Uri fragment must be a string'); + + $this->uriFactory()->withFragment(['foo']); + } + + public function testToString() + { + $uri = $this->uriFactory(); + + $this->assertEquals('https://josh:sekrit@example.com/foo/bar?abc=123#section3', (string) $uri); + + $uri = $uri->withPath('bar'); + $this->assertEquals('https://josh:sekrit@example.com/bar?abc=123#section3', (string) $uri); + + $uri = $uri->withPath('/bar'); + $this->assertEquals('https://josh:sekrit@example.com/bar?abc=123#section3', (string) $uri); + + $uri = $uri->withScheme('')->withHost('')->withPort(null)->withUserInfo('')->withPath('//bar'); + $this->assertEquals('/bar?abc=123#section3', (string) $uri); + } +} diff --git a/vendor/slim/psr7/tests/bootstrap.php b/vendor/slim/psr7/tests/bootstrap.php new file mode 100644 index 0000000..eee5637 --- /dev/null +++ b/vendor/slim/psr7/tests/bootstrap.php @@ -0,0 +1,99 @@ + [ + 'getallheaders' => function () { + if (array_key_exists('getallheaders_return', $GLOBALS)) { + return $GLOBALS['getallheaders_return']; + } + + return getallheaders(); + } + ], + Message::class => [ + 'header' => function (string $string, bool $replace = true, ?int $statusCode = null): void { + HeaderStack::push( + [ + 'header' => $string, + 'replace' => $replace, + 'status_code' => $statusCode, + ] + ); + }, + 'header_remove' => function ($name = null): void { + HeaderStack::remove($name); + } + ], + NonBufferedBody::class => [ + 'ob_get_level' => function (): int { + if (isset($GLOBALS['ob_get_level_shift'])) { + return ob_get_level() + $GLOBALS['ob_get_level_shift']; + } + + return ob_get_level(); + } + ], + UploadedFile::class => [ + 'copy' => function (string $source, string $destination, $context = null): bool { + if (isset($GLOBALS['copy_return'])) { + return $GLOBALS['copy_return']; + } + + if ($context === null) { + return copy($source, $destination); + } + return copy($source, $destination, $context); + }, + 'is_uploaded_file' => function (string $filename): bool { + if (isset($GLOBALS['is_uploaded_file_return'])) { + return $GLOBALS['is_uploaded_file_return']; + } + + return is_uploaded_file($filename); + }, + 'rename' => function (string $oldName, string $newName, $context = null): bool { + if (isset($GLOBALS['rename_return'])) { + return $GLOBALS['rename_return']; + } + + if ($context === null) { + return rename($oldName, $newName); + } + return rename($oldName, $newName, $context = null); + } + ], + Factory\StreamFactory::class => [ + 'fopen' => function (string $filename, string $mode) { + if (isset($GLOBALS['fopen_return'])) { + return isset($GLOBALS['fopen_return']); + } + + return fopen($filename, $mode); + }, + 'is_readable' => function (string $filename) { + if ($filename === 'non-readable') { + return false; + } + + return is_readable($filename); + } + ] +]); diff --git a/vendor/slim/slim/CHANGELOG.md b/vendor/slim/slim/CHANGELOG.md new file mode 100644 index 0000000..6bcb127 --- /dev/null +++ b/vendor/slim/slim/CHANGELOG.md @@ -0,0 +1,237 @@ +# Changelog + +# 4.11.0 - 2022-11-06 +- [3180: Declare types](https://github.com/slimphp/Slim/pull/3180) thanks to @nbayramberdiyev +- [3181: Update laminas/laminas-diactoros requirement from ^2.8 to ^2.9](https://github.com/slimphp/Slim/pull/3181) thanks to @dependabot[bot] +- [3182: Update guzzlehttp/psr7 requirement from ^2.1 to ^2.2](https://github.com/slimphp/Slim/pull/3182) thanks to @dependabot[bot] +- [3183: Update phpstan/phpstan requirement from ^1.4 to ^1.5](https://github.com/slimphp/Slim/pull/3183) thanks to @dependabot[bot] +- [3184: Update adriansuter/php-autoload-override requirement from ^1.2 to ^1.3](https://github.com/slimphp/Slim/pull/3184) thanks to @dependabot[bot] +- [3189: Update phpstan/phpstan requirement from ^1.5 to ^1.6](https://github.com/slimphp/Slim/pull/3189) thanks to @dependabot[bot] +- [3191: Adding property types to Middleware classes](https://github.com/slimphp/Slim/pull/3191) thanks to @ashleycoles +- [3193: Handlers types](https://github.com/slimphp/Slim/pull/3193) thanks to @ashleycoles +- [3194: Adding types to AbstractErrorRenderer](https://github.com/slimphp/Slim/pull/3194) thanks to @ashleycoles +- [3195: Adding prop types for Exception classes](https://github.com/slimphp/Slim/pull/3195) thanks to @ashleycoles +- [3196: Adding property type declarations for Factory classes](https://github.com/slimphp/Slim/pull/3196) thanks to @ashleycoles +- [3197: Remove redundant docblock types](https://github.com/slimphp/Slim/pull/3197) thanks to @theodorejb +- [3199: Update laminas/laminas-diactoros requirement from ^2.9 to ^2.11](https://github.com/slimphp/Slim/pull/3199) thanks to @dependabot[bot] +- [3200: Update phpstan/phpstan requirement from ^1.6 to ^1.7](https://github.com/slimphp/Slim/pull/3200) thanks to @dependabot[bot] +- [3205: Update guzzlehttp/psr7 requirement from ^2.2 to ^2.4](https://github.com/slimphp/Slim/pull/3205) thanks to @dependabot[bot] +- [3206: Update squizlabs/php_codesniffer requirement from ^3.6 to ^3.7](https://github.com/slimphp/Slim/pull/3206) thanks to @dependabot[bot] +- [3207: Update phpstan/phpstan requirement from ^1.7 to ^1.8](https://github.com/slimphp/Slim/pull/3207) thanks to @dependabot[bot] +- [3211: Assign null coalescing to coalesce equal](https://github.com/slimphp/Slim/pull/3211) thanks to @MathiasReker +- [3213: Void return](https://github.com/slimphp/Slim/pull/3213) thanks to @MathiasReker +- [3214: Is null](https://github.com/slimphp/Slim/pull/3214) thanks to @MathiasReker +- [3216: Refactor](https://github.com/slimphp/Slim/pull/3216) thanks to @mehdihasanpour +- [3218: Refactor some code](https://github.com/slimphp/Slim/pull/3218) thanks to @mehdihasanpour +- [3221: Cleanup](https://github.com/slimphp/Slim/pull/3221) thanks to @mehdihasanpour +- [3225: Update laminas/laminas-diactoros requirement from ^2.11 to ^2.14](https://github.com/slimphp/Slim/pull/3225) thanks to @dependabot[bot] +- [3228: Using assertSame to let assert equal be restricted](https://github.com/slimphp/Slim/pull/3228) thanks to @peter279k +- [3229: Update laminas/laminas-diactoros requirement from ^2.14 to ^2.17](https://github.com/slimphp/Slim/pull/3229) thanks to @dependabot[bot] +- [3235: Persist routes indexed by name in RouteCollector for improved performance.](https://github.com/slimphp/Slim/pull/3235) thanks to @BusterNeece + +# 4.10.0 - 2022-03-14 +- [3120: Add a new PSR-17 factory to Psr17FactoryProvider](https://github.com/slimphp/Slim/pull/3120) thanks to @solventt +- [3123: Replace deprecated setMethods() in tests](https://github.com/slimphp/Slim/pull/3123) thanks to @solventt +- [3126: Update guzzlehttp/psr7 requirement from ^2.0 to ^2.1](https://github.com/slimphp/Slim/pull/3126) thanks to @dependabot[bot] +- [3127: PHPStan v1.0](https://github.com/slimphp/Slim/pull/3127) thanks to @t0mmy742 +- [3128: Update phpstan/phpstan requirement from ^1.0 to ^1.2](https://github.com/slimphp/Slim/pull/3128) thanks to @dependabot[bot] +- [3129: Deprecate PHP 7.3](https://github.com/slimphp/Slim/pull/3129) thanks to @l0gicgate +- [3130: Removed double defined PHP 7.4](https://github.com/slimphp/Slim/pull/3130) thanks to @flangofas +- [3132: Add new `RequestResponseNamedArgs` route strategy](https://github.com/slimphp/Slim/pull/3132) thanks to @adoy +- [3133: Improve typehinting for `RouteParserInterface`](https://github.com/slimphp/Slim/pull/3133) thanks to @jerowork +- [3135: Update phpstan/phpstan requirement from ^1.2 to ^1.3](https://github.com/slimphp/Slim/pull/3135) thanks to @dependabot[bot] +- [3137: Update phpspec/prophecy requirement from ^1.14 to ^1.15](https://github.com/slimphp/Slim/pull/3137) thanks to @dependabot[bot] +- [3138: Update license year](https://github.com/slimphp/Slim/pull/3138) thanks to @Awilum +- [3139: Fixed #1730 (reintroduced in 4.x)](https://github.com/slimphp/Slim/pull/3139) thanks to @adoy +- [3145: Update phpstan/phpstan requirement from ^1.3 to ^1.4](https://github.com/slimphp/Slim/pull/3145) thanks to @dependabot[bot] +- [3146: Inherit HttpException from RuntimeException](https://github.com/slimphp/Slim/pull/3146) thanks to @nbayramberdiyev +- [3148: Upgrade to HTML5](https://github.com/slimphp/Slim/pull/3148) thanks to @nbayramberdiyev +- [3172: Update nyholm/psr7 requirement from ^1.4 to ^1.5](https://github.com/slimphp/Slim/pull/3172) thanks to @dependabot[bot] + +# 4.9.0 - 2021-10-05 +- [3058: Implement exception class for Gone Http error](https://github.com/slimphp/Slim/pull/3058) thanks to @TheKernelPanic +- [3086: Update slim/psr7 requirement from ^1.3 to ^1.4](https://github.com/slimphp/Slim/pull/3086) thanks to @dependabot[bot] +- [3087: Update nyholm/psr7-server requirement from ^1.0.1 to ^1.0.2](https://github.com/slimphp/Slim/pull/3087) thanks to @dependabot[bot] +- [3093: Update phpstan/phpstan requirement from ^0.12.85 to ^0.12.90](https://github.com/slimphp/Slim/pull/3093) thanks to @dependabot[bot] +- [3099: Allow updated psr log](https://github.com/slimphp/Slim/pull/3099) thanks to @t0mmy742 +- [3104: Drop php7.2](https://github.com/slimphp/Slim/pull/3104) thanks to @t0mmy742 +- [3106: Use PSR-17 factory from Guzzle/psr7 2.0](https://github.com/slimphp/Slim/pull/3106) thanks to @t0mmy742 +- [3108: Update README file](https://github.com/slimphp/Slim/pull/3108) thanks to @t0mmy742 +- [3112: Update laminas/laminas-diactoros requirement from ^2.6 to ^2.8](https://github.com/slimphp/Slim/pull/3112) thanks to @dependabot[bot] +- [3114: Update slim/psr7 requirement from ^1.4 to ^1.5](https://github.com/slimphp/Slim/pull/3114) thanks to @dependabot[bot] +- [3115: Update phpstan/phpstan requirement from ^0.12.96 to ^0.12.99](https://github.com/slimphp/Slim/pull/3115) thanks to @dependabot[bot] +- [3116: Remove Zend Diactoros references](https://github.com/slimphp/Slim/pull/3116) thanks to @l0gicgate + +# 4.8.0 - 2021-05-19 +- [3034: Fix phpunit dependency version](https://github.com/slimphp/Slim/pull/3034) thanks to @l0gicgate +- [3037: Replace Travis by GitHub Actions](https://github.com/slimphp/Slim/pull/3037) thanks to @t0mmy742 +- [3043: Cover App creation from AppFactory with empty Container](https://github.com/slimphp/Slim/pull/3043) thanks to @t0mmy742 +- [3045: Update phpstan/phpstan requirement from ^0.12.58 to ^0.12.64](https://github.com/slimphp/Slim/pull/3045) thanks to @dependabot-preview[bot] +- [3047: documentation: min php 7.2 required](https://github.com/slimphp/Slim/pull/3047) thanks to @Rotzbua +- [3054: Update phpstan/phpstan requirement from ^0.12.64 to ^0.12.70](https://github.com/slimphp/Slim/pull/3054) thanks to @dependabot-preview[bot] +- [3056: Fix docblock in ErrorMiddleware](https://github.com/slimphp/Slim/pull/3056) thanks to @piotr-cz +- [3060: Update phpstan/phpstan requirement from ^0.12.70 to ^0.12.80](https://github.com/slimphp/Slim/pull/3060) thanks to @dependabot-preview[bot] +- [3061: Update nyholm/psr7 requirement from ^1.3 to ^1.4](https://github.com/slimphp/Slim/pull/3061) thanks to @dependabot-preview[bot] +- [3063: Allow ^1.0 || ^2.0 in psr/container](https://github.com/slimphp/Slim/pull/3063) thanks to @Ayesh +- [3069: Classname/Method Callable Arrays](https://github.com/slimphp/Slim/pull/3069) thanks to @ddrv +- [3078: Update squizlabs/php_codesniffer requirement from ^3.5 to ^3.6](https://github.com/slimphp/Slim/pull/3078) thanks to @dependabot[bot] +- [3079: Update phpspec/prophecy requirement from ^1.12 to ^1.13](https://github.com/slimphp/Slim/pull/3079) thanks to @dependabot[bot] +- [3080: Update guzzlehttp/psr7 requirement from ^1.7 to ^1.8](https://github.com/slimphp/Slim/pull/3080) thanks to @dependabot[bot] +- [3082: Update phpstan/phpstan requirement from ^0.12.80 to ^0.12.85](https://github.com/slimphp/Slim/pull/3082) thanks to @dependabot[bot] + +# 4.7.0 - 2020-11-30 + +### Fixed +- [3027: Fix: FastRoute dispatcher and data generator should match](https://github.com/slimphp/Slim/pull/3027) thanks to @edudobay + +### Added +- [3015: PHP 8 support](https://github.com/slimphp/Slim/pull/3015) thanks to @edudobay + +### Optimizations +- [3024: Randomize tests](https://github.com/slimphp/Slim/pull/3024) thanks to @pawel-slowik + +## 4.6.0 - 2020-11-15 + +### Fixed +- [2942: Fix PHPdoc for error handlers in ErrorMiddleware ](https://github.com/slimphp/Slim/pull/2942) thanks to @TiMESPLiNTER +- [2944: Remove unused function in ErrorHandler](https://github.com/slimphp/Slim/pull/2944) thanks to @l0gicgate +- [2960: Fix phpstan 0.12 errors](https://github.com/slimphp/Slim/pull/2960) thanks to @adriansuter +- [2982: Removing cloning statements in tests](https://github.com/slimphp/Slim/pull/2982) thanks to @l0gicgate +- [3017: Fix request creator factory test](https://github.com/slimphp/Slim/pull/3017) thanks to @pawel-slowik +- [3022: Ensure RouteParser Always Present After Routing](https://github.com/slimphp/Slim/pull/3022) thanks to @l0gicgate + +### Added +- [2949: Add the support in composer.json](https://github.com/slimphp/Slim/pull/2949) thanks to @ddrv +- [2958: Strict empty string content type checking in BodyParsingMiddleware::getMediaType](https://github.com/slimphp/Slim/pull/2958) thanks to @Ayesh +- [2997: Add hints to methods](https://github.com/slimphp/Slim/pull/2997) thanks to @evgsavosin - [3000: Fix route controller test](https://github.com/slimphp/Slim/pull/3000) thanks to @pawel-slowik +- [3001: Add missing `$strategy` parameter in a Route test](https://github.com/slimphp/Slim/pull/3001) thanks to @pawel-slowik + +### Optimizations +- [2951: Minor optimizations in if() blocks](https://github.com/slimphp/Slim/pull/2951) thanks to @Ayesh +- [2959: Micro optimization: Declare closures in BodyParsingMiddleware as static](https://github.com/slimphp/Slim/pull/2959) thanks to @Ayesh +- [2978: Split the routing results to its own function.](https://github.com/slimphp/Slim/pull/2978) thanks to @dlundgren + +### Dependencies Updated +- [2953: Update nyholm/psr7-server requirement from ^0.4.1](https://github.com/slimphp/Slim/pull/2953) thanks to @dependabot-preview[bot] +- [2954: Update laminas/laminas-diactoros requirement from ^2.1 to ^2.3](https://github.com/slimphp/Slim/pull/2954) thanks to @dependabot-preview[bot] +- [2955: Update guzzlehttp/psr7 requirement from ^1.5 to ^1.6](https://github.com/slimphp/Slim/pull/2955) thanks to @dependabot-preview[bot] +- [2956: Update slim/psr7 requirement from ^1.0 to ^1.1](https://github.com/slimphp/Slim/pull/2956) thanks to @dependabot-preview[bot] +- [2957: Update nyholm/psr7 requirement from ^1.1 to ^1.2](https://github.com/slimphp/Slim/pull/2957) thanks to @dependabot-preview[bot] +- [2963: Update phpstan/phpstan requirement from ^0.12.23 to ^0.12.25](https://github.com/slimphp/Slim/pull/2963) thanks to @dependabot-preview[bot] +- [2965: Update adriansuter/php-autoload-override requirement from ^1.0 to ^1.1](https://github.com/slimphp/Slim/pull/2965) thanks to @dependabot-preview[bot] +- [2967: Update nyholm/psr7 requirement from ^1.2 to ^1.3](https://github.com/slimphp/Slim/pull/2967) thanks to @dependabot-preview[bot] +- [2969: Update nyholm/psr7-server requirement from ^0.4.1 to ^1.0.0](https://github.com/slimphp/Slim/pull/2969) thanks to @dependabot-preview[bot] +- [2970: Update phpstan/phpstan requirement from ^0.12.25 to ^0.12.26](https://github.com/slimphp/Slim/pull/2970) thanks to @dependabot-preview[bot] +- [2971: Update phpstan/phpstan requirement from ^0.12.26 to ^0.12.27](https://github.com/slimphp/Slim/pull/2971) thanks to @dependabot-preview[bot] +- [2972: Update phpstan/phpstan requirement from ^0.12.27 to ^0.12.28](https://github.com/slimphp/Slim/pull/2972) thanks to @dependabot-preview[bot] +- [2973: Update phpstan/phpstan requirement from ^0.12.28 to ^0.12.29](https://github.com/slimphp/Slim/pull/2973) thanks to @dependabot-preview[bot] +- [2975: Update phpstan/phpstan requirement from ^0.12.29 to ^0.12.30](https://github.com/slimphp/Slim/pull/2975) thanks to @dependabot-preview[bot] +- [2976: Update phpstan/phpstan requirement from ^0.12.30 to ^0.12.31](https://github.com/slimphp/Slim/pull/2976) thanks to @dependabot-preview[bot] +- [2980: Update phpstan/phpstan requirement from ^0.12.31 to ^0.12.32](https://github.com/slimphp/Slim/pull/2980) thanks to @dependabot-preview[bot] +- [2981: Update phpspec/prophecy requirement from ^1.10 to ^1.11](https://github.com/slimphp/Slim/pull/2981) thanks to @dependabot-preview[bot] +- [2986: Update phpstan/phpstan requirement from ^0.12.32 to ^0.12.33](https://github.com/slimphp/Slim/pull/2986) thanks to @dependabot-preview[bot] +- [2990: Update phpstan/phpstan requirement from ^0.12.33 to ^0.12.34](https://github.com/slimphp/Slim/pull/2990) thanks to @dependabot-preview[bot] +- [2991: Update phpstan/phpstan requirement from ^0.12.34 to ^0.12.35](https://github.com/slimphp/Slim/pull/2991) thanks to @dependabot-preview[bot] +- [2993: Update phpstan/phpstan requirement from ^0.12.35 to ^0.12.36](https://github.com/slimphp/Slim/pull/2993) thanks to @dependabot-preview[bot] +- [2995: Update phpstan/phpstan requirement from ^0.12.36 to ^0.12.37](https://github.com/slimphp/Slim/pull/2995) thanks to @dependabot-preview[bot] +- [3010: Update guzzlehttp/psr7 requirement from ^1.6 to ^1.7](https://github.com/slimphp/Slim/pull/3010) thanks to @dependabot-preview[bot] +- [3011: Update phpspec/prophecy requirement from ^1.11 to ^1.12](https://github.com/slimphp/Slim/pull/3011) thanks to @dependabot-preview[bot] +- [3012: Update slim/http requirement from ^1.0 to ^1.1](https://github.com/slimphp/Slim/pull/3012) thanks to @dependabot-preview[bot] +- [3013: Update slim/psr7 requirement from ^1.1 to ^1.2](https://github.com/slimphp/Slim/pull/3013) thanks to @dependabot-preview[bot] +- [3014: Update laminas/laminas-diactoros requirement from ^2.3 to ^2.4](https://github.com/slimphp/Slim/pull/3014) thanks to @dependabot-preview[bot] +- [3018: Update phpstan/phpstan requirement from ^0.12.37 to ^0.12.54](https://github.com/slimphp/Slim/pull/3018) thanks to @dependabot-preview[bot] + +## 4.5.0 - 2020-04-14 + +### Added +- [2928](https://github.com/slimphp/Slim/pull/2928) Test against PHP 7.4 +- [2937](https://github.com/slimphp/Slim/pull/2937) Add support for PSR-3 + +### Fixed +- [2916](https://github.com/slimphp/Slim/pull/2916) Rename phpcs.xml to phpcs.xml.dist +- [2917](https://github.com/slimphp/Slim/pull/2917) Update .editorconfig +- [2925](https://github.com/slimphp/Slim/pull/2925) ResponseEmitter: Don't remove Content-Type and Content-Length when body is empt +- [2932](https://github.com/slimphp/Slim/pull/2932) Update the Tidelift enterprise language +- [2938](https://github.com/slimphp/Slim/pull/2938) Modify usage of deprecated expectExceptionMessageRegExp() method + +## 4.4.0 - 2020-01-04 + +### Added +- [2862](https://github.com/slimphp/Slim/pull/2862) Optionally handle subclasses of exceptions in custom error handler +- [2869](https://github.com/slimphp/Slim/pull/2869) php-di/php-di added in composer suggestion +- [2874](https://github.com/slimphp/Slim/pull/2874) Add `null` to param type-hints +- [2889](https://github.com/slimphp/Slim/pull/2889) Make `RouteContext` attributes customizable and change default to use private names +- [2907](https://github.com/slimphp/Slim/pull/2907) Migrate to PSR-12 convention +- [2910](https://github.com/slimphp/Slim/pull/2910) Migrate Zend to Laminas +- [2912](https://github.com/slimphp/Slim/pull/2912) Add Laminas PSR17 Factory +- [2913](https://github.com/slimphp/Slim/pull/2913) Update php-autoload-override version +- [2914](https://github.com/slimphp/Slim/pull/2914) Added ability to add handled exceptions as an array + +### Fixed +- [2864](https://github.com/slimphp/Slim/pull/2864) Optimize error message in error handling if displayErrorDetails was not set +- [2876](https://github.com/slimphp/Slim/pull/2876) Update links from http to https +- [2877](https://github.com/slimphp/Slim/pull/2877) Fix docblock for `Slim\Routing\RouteCollector::cacheFile` +- [2878](https://github.com/slimphp/Slim/pull/2878) check body is writable only on ouput buffering append +- [2896](https://github.com/slimphp/Slim/pull/2896) Render errors uniformly +- [2902](https://github.com/slimphp/Slim/pull/2902) Fix prophecies +- [2908](https://github.com/slimphp/Slim/pull/2908) Use autoload-dev for `Slim\Tests` namespace + +### Removed +- [2871](https://github.com/slimphp/Slim/pull/2871) Remove explicit type-hint +- [2872](https://github.com/slimphp/Slim/pull/2872) Remove type-hint + +## 4.3.0 - 2019-10-05 + +### Added +- [2819](https://github.com/slimphp/Slim/pull/2819) Added description to addRoutingMiddleware() +- [2820](https://github.com/slimphp/Slim/pull/2820) Update link to homepage in composer.json +- [2828](https://github.com/slimphp/Slim/pull/2828) Allow URIs with leading multi-slashes +- [2832](https://github.com/slimphp/Slim/pull/2832) Refactor `FastRouteDispatcher` +- [2835](https://github.com/slimphp/Slim/pull/2835) Rename `pathFor` to `urlFor` in docblock +- [2846](https://github.com/slimphp/Slim/pull/2846) Correcting the branch name as per issue-2843 +- [2849](https://github.com/slimphp/Slim/pull/2849) Create class alias for FastRoute\RouteCollector +- [2855](https://github.com/slimphp/Slim/pull/2855) Add list of allowed methods to HttpMethodNotAllowedException +- [2860](https://github.com/slimphp/Slim/pull/2860) Add base path to `$request` and use `RouteContext` to read + +### Fixed +- [2839](https://github.com/slimphp/Slim/pull/2839) Fix description for handler signature in phpdocs +- [2844](https://github.com/slimphp/Slim/pull/2844) Handle base path by routeCollector instead of RouteCollectorProxy +- [2845](https://github.com/slimphp/Slim/pull/2845) Fix composer scripts +- [2851](https://github.com/slimphp/Slim/pull/2851) Fix example of 'Hello World' app +- [2854](https://github.com/slimphp/Slim/pull/2854) Fix undefined property in tests + +### Removed +- [2853](https://github.com/slimphp/Slim/pull/2853) Remove unused classes + +## 4.2.0 - 2019-08-20 + +### Added +- [2787](https://github.com/slimphp/Slim/pull/2787) Add an advanced callable resolver +- [2791](https://github.com/slimphp/Slim/pull/2791) Add `inferPrivatePropertyTypeFromConstructor` to phpstan +- [2793](https://github.com/slimphp/Slim/pull/2793) Add ability to configure application via a container in `AppFactory` +- [2798](https://github.com/slimphp/Slim/pull/2798) Add PSR-7 Agnostic Body Parsing Middleware +- [2801](https://github.com/slimphp/Slim/pull/2801) Add `setLogErrorRenderer()` method to `ErrorHandler` +- [2807](https://github.com/slimphp/Slim/pull/2807) Add check for Slim callable notation if no resolver given +- [2803](https://github.com/slimphp/Slim/pull/2803) Add ability to emit non seekable streams in `ResponseEmitter` +- [2817](https://github.com/slimphp/Slim/pull/2817) Add the ability to pass in a custom `MiddlewareDispatcherInterface` to the `App` + +### Fixed +- [2789](https://github.com/slimphp/Slim/pull/2789) Fix Cookie header detection in `ResponseEmitter` +- [2796](https://github.com/slimphp/Slim/pull/2796) Fix http message format +- [2800](https://github.com/slimphp/Slim/pull/2800) Fix null comparisons more clear in `ErrorHandler` +- [2802](https://github.com/slimphp/Slim/pull/2802) Fix incorrect search of a header in stack +- [2806](https://github.com/slimphp/Slim/pull/2806) Simplify `Route::prepare()` method argument preparation +- [2809](https://github.com/slimphp/Slim/pull/2809) Eliminate a duplicate code via HOF in `MiddlewareDispatcher` +- [2816](https://github.com/slimphp/Slim/pull/2816) Fix RouteCollectorProxy::redirect() bug + +### Removed +- [2811](https://github.com/slimphp/Slim/pull/2811) Remove `DeferredCallable` + +## 4.1.0 - 2019-08-06 + +### Added +- [#2779](https://github.com/slimphp/Slim/pull/2774) Add support for Slim callables `Class:method` resolution & Container Closure auto-binding in `MiddlewareDispatcher` +- [#2774](https://github.com/slimphp/Slim/pull/2774) Add possibility for custom `RequestHandler` invocation strategies + +### Fixed +- [#2776](https://github.com/slimphp/Slim/pull/2774) Fix group middleware on multiple nested groups diff --git a/vendor/slim/slim/LICENSE.md b/vendor/slim/slim/LICENSE.md new file mode 100644 index 0000000..d6fd559 --- /dev/null +++ b/vendor/slim/slim/LICENSE.md @@ -0,0 +1,19 @@ +Copyright (c) 2011-2022 Josh Lockhart + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/slim/slim/MAINTAINERS.md b/vendor/slim/slim/MAINTAINERS.md new file mode 100644 index 0000000..2b8ad04 --- /dev/null +++ b/vendor/slim/slim/MAINTAINERS.md @@ -0,0 +1,17 @@ +# Maintainers + +There aren't many rules for maintainers of Slim to remember; what we have is listed here. + +## We don't merge our own PRs + +Our code is better if more than one set of eyes looks at it. Therefore we do not merge our own pull requests unless there is an exceptional circumstance. This helps to spot errors in the patch and also enables us to share information about the project around the maintainer team. + +## PRs tagged `WIP` are not ready to be merged + +Sometimes it's helpful to collaborate on a patch before it's ready to be merged. We use the text `WIP` (for _Work in Progress_) in the title to mark these PRs. + +If a PR has `WIP` in its title, then it is not to be merged. The person who raised the PR will remove the `WIP` text when they are ready for a full review and merge. + +## Assign a merged PR to a milestone + +By ensuring that all merged PRs are assigned to a milestone, we can easily find which PRs were in which release. diff --git a/vendor/slim/slim/SECURITY.md b/vendor/slim/slim/SECURITY.md new file mode 100644 index 0000000..a5b6df0 --- /dev/null +++ b/vendor/slim/slim/SECURITY.md @@ -0,0 +1,14 @@ +# Security Policy + +### Supported Versions + + +| Version | Supported | +| ------- | ------------------ | +| 3.x.x | :white_check_mark: | +| 4.x.x | :white_check_mark: | + + +### Reporting a Vulnerability + +To report a vulnerability please send an email to security@slimframework.com diff --git a/vendor/slim/slim/Slim/App.php b/vendor/slim/slim/Slim/App.php new file mode 100644 index 0000000..68b9000 --- /dev/null +++ b/vendor/slim/slim/Slim/App.php @@ -0,0 +1,226 @@ + + */ +class App extends RouteCollectorProxy implements RequestHandlerInterface +{ + /** + * Current version + * + * @var string + */ + public const VERSION = '4.12.0'; + + protected RouteResolverInterface $routeResolver; + + protected MiddlewareDispatcherInterface $middlewareDispatcher; + + /** + * @param TContainerInterface $container + */ + public function __construct( + ResponseFactoryInterface $responseFactory, + ?ContainerInterface $container = null, + ?CallableResolverInterface $callableResolver = null, + ?RouteCollectorInterface $routeCollector = null, + ?RouteResolverInterface $routeResolver = null, + ?MiddlewareDispatcherInterface $middlewareDispatcher = null + ) { + parent::__construct( + $responseFactory, + $callableResolver ?? new CallableResolver($container), + $container, + $routeCollector + ); + + $this->routeResolver = $routeResolver ?? new RouteResolver($this->routeCollector); + $routeRunner = new RouteRunner($this->routeResolver, $this->routeCollector->getRouteParser(), $this); + + if (!$middlewareDispatcher) { + $middlewareDispatcher = new MiddlewareDispatcher($routeRunner, $this->callableResolver, $container); + } else { + $middlewareDispatcher->seedMiddlewareStack($routeRunner); + } + + $this->middlewareDispatcher = $middlewareDispatcher; + } + + /** + * @return RouteResolverInterface + */ + public function getRouteResolver(): RouteResolverInterface + { + return $this->routeResolver; + } + + /** + * @return MiddlewareDispatcherInterface + */ + public function getMiddlewareDispatcher(): MiddlewareDispatcherInterface + { + return $this->middlewareDispatcher; + } + + /** + * @param MiddlewareInterface|string|callable $middleware + * @return App + */ + public function add($middleware): self + { + $this->middlewareDispatcher->add($middleware); + return $this; + } + + /** + * @param MiddlewareInterface $middleware + * @return App + */ + public function addMiddleware(MiddlewareInterface $middleware): self + { + $this->middlewareDispatcher->addMiddleware($middleware); + return $this; + } + + /** + * Add the Slim built-in routing middleware to the app middleware stack + * + * This method can be used to control middleware order and is not required for default routing operation. + * + * @return RoutingMiddleware + */ + public function addRoutingMiddleware(): RoutingMiddleware + { + $routingMiddleware = new RoutingMiddleware( + $this->getRouteResolver(), + $this->getRouteCollector()->getRouteParser() + ); + $this->add($routingMiddleware); + return $routingMiddleware; + } + + /** + * Add the Slim built-in error middleware to the app middleware stack + * + * @param bool $displayErrorDetails + * @param bool $logErrors + * @param bool $logErrorDetails + * @param LoggerInterface|null $logger + * + * @return ErrorMiddleware + */ + public function addErrorMiddleware( + bool $displayErrorDetails, + bool $logErrors, + bool $logErrorDetails, + ?LoggerInterface $logger = null + ): ErrorMiddleware { + $errorMiddleware = new ErrorMiddleware( + $this->getCallableResolver(), + $this->getResponseFactory(), + $displayErrorDetails, + $logErrors, + $logErrorDetails, + $logger + ); + $this->add($errorMiddleware); + return $errorMiddleware; + } + + /** + * Add the Slim body parsing middleware to the app middleware stack + * + * @param callable[] $bodyParsers + * + * @return BodyParsingMiddleware + */ + public function addBodyParsingMiddleware(array $bodyParsers = []): BodyParsingMiddleware + { + $bodyParsingMiddleware = new BodyParsingMiddleware($bodyParsers); + $this->add($bodyParsingMiddleware); + return $bodyParsingMiddleware; + } + + /** + * Run application + * + * This method traverses the application middleware stack and then sends the + * resultant Response object to the HTTP client. + * + * @param ServerRequestInterface|null $request + * @return void + */ + public function run(?ServerRequestInterface $request = null): void + { + if (!$request) { + $serverRequestCreator = ServerRequestCreatorFactory::create(); + $request = $serverRequestCreator->createServerRequestFromGlobals(); + } + + $response = $this->handle($request); + $responseEmitter = new ResponseEmitter(); + $responseEmitter->emit($response); + } + + /** + * Handle a request + * + * This method traverses the application middleware stack and then returns the + * resultant Response object. + * + * @param ServerRequestInterface $request + * @return ResponseInterface + */ + public function handle(ServerRequestInterface $request): ResponseInterface + { + $response = $this->middlewareDispatcher->handle($request); + + /** + * This is to be in compliance with RFC 2616, Section 9. + * If the incoming request method is HEAD, we need to ensure that the response body + * is empty as the request may fall back on a GET route handler due to FastRoute's + * routing logic which could potentially append content to the response body + * https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4 + */ + $method = strtoupper($request->getMethod()); + if ($method === 'HEAD') { + $emptyBody = $this->responseFactory->createResponse()->getBody(); + return $response->withBody($emptyBody); + } + + return $response; + } +} diff --git a/vendor/slim/slim/Slim/CallableResolver.php b/vendor/slim/slim/Slim/CallableResolver.php new file mode 100644 index 0000000..dab46c4 --- /dev/null +++ b/vendor/slim/slim/Slim/CallableResolver.php @@ -0,0 +1,199 @@ +container = $container; + } + + /** + * {@inheritdoc} + */ + public function resolve($toResolve): callable + { + $toResolve = $this->prepareToResolve($toResolve); + if (is_callable($toResolve)) { + return $this->bindToContainer($toResolve); + } + $resolved = $toResolve; + if (is_string($toResolve)) { + $resolved = $this->resolveSlimNotation($toResolve); + $resolved[1] ??= '__invoke'; + } + $callable = $this->assertCallable($resolved, $toResolve); + return $this->bindToContainer($callable); + } + + /** + * {@inheritdoc} + */ + public function resolveRoute($toResolve): callable + { + return $this->resolveByPredicate($toResolve, [$this, 'isRoute'], 'handle'); + } + + /** + * {@inheritdoc} + */ + public function resolveMiddleware($toResolve): callable + { + return $this->resolveByPredicate($toResolve, [$this, 'isMiddleware'], 'process'); + } + + /** + * @param string|callable $toResolve + * + * @throws RuntimeException + */ + private function resolveByPredicate($toResolve, callable $predicate, string $defaultMethod): callable + { + $toResolve = $this->prepareToResolve($toResolve); + if (is_callable($toResolve)) { + return $this->bindToContainer($toResolve); + } + $resolved = $toResolve; + if ($predicate($toResolve)) { + $resolved = [$toResolve, $defaultMethod]; + } + if (is_string($toResolve)) { + [$instance, $method] = $this->resolveSlimNotation($toResolve); + if ($method === null && $predicate($instance)) { + $method = $defaultMethod; + } + $resolved = [$instance, $method ?? '__invoke']; + } + $callable = $this->assertCallable($resolved, $toResolve); + return $this->bindToContainer($callable); + } + + /** + * @param mixed $toResolve + */ + private function isRoute($toResolve): bool + { + return $toResolve instanceof RequestHandlerInterface; + } + + /** + * @param mixed $toResolve + */ + private function isMiddleware($toResolve): bool + { + return $toResolve instanceof MiddlewareInterface; + } + + /** + * @throws RuntimeException + * + * @return array{object, string|null} [Instance, Method Name] + */ + private function resolveSlimNotation(string $toResolve): array + { + /** @psalm-suppress ArgumentTypeCoercion */ + preg_match(CallableResolver::$callablePattern, $toResolve, $matches); + [$class, $method] = $matches ? [$matches[1], $matches[2]] : [$toResolve, null]; + + if ($this->container && $this->container->has($class)) { + $instance = $this->container->get($class); + if (!is_object($instance)) { + throw new RuntimeException(sprintf('%s container entry is not an object', $class)); + } + } else { + if (!class_exists($class)) { + if ($method) { + $class .= '::' . $method . '()'; + } + throw new RuntimeException(sprintf('Callable %s does not exist', $class)); + } + $instance = new $class($this->container); + } + return [$instance, $method]; + } + + /** + * @param mixed $resolved + * @param mixed $toResolve + * + * @throws RuntimeException + */ + private function assertCallable($resolved, $toResolve): callable + { + if (!is_callable($resolved)) { + if (is_callable($toResolve) || is_object($toResolve) || is_array($toResolve)) { + $formatedToResolve = ($toResolveJson = json_encode($toResolve)) !== false ? $toResolveJson : ''; + } else { + $formatedToResolve = is_string($toResolve) ? $toResolve : ''; + } + throw new RuntimeException(sprintf('%s is not resolvable', $formatedToResolve)); + } + return $resolved; + } + + private function bindToContainer(callable $callable): callable + { + if (is_array($callable) && $callable[0] instanceof Closure) { + $callable = $callable[0]; + } + if ($this->container && $callable instanceof Closure) { + /** @var Closure $callable */ + $callable = $callable->bindTo($this->container); + } + return $callable; + } + + /** + * @param string|callable $toResolve + * @return string|callable + */ + private function prepareToResolve($toResolve) + { + if (!is_array($toResolve)) { + return $toResolve; + } + $candidate = $toResolve; + $class = array_shift($candidate); + $method = array_shift($candidate); + if (is_string($class) && is_string($method)) { + return $class . ':' . $method; + } + return $toResolve; + } +} diff --git a/vendor/slim/slim/Slim/Error/AbstractErrorRenderer.php b/vendor/slim/slim/Slim/Error/AbstractErrorRenderer.php new file mode 100644 index 0000000..90b290d --- /dev/null +++ b/vendor/slim/slim/Slim/Error/AbstractErrorRenderer.php @@ -0,0 +1,46 @@ +getTitle(); + } + + return $this->defaultErrorTitle; + } + + protected function getErrorDescription(Throwable $exception): string + { + if ($exception instanceof HttpException) { + return $exception->getDescription(); + } + + return $this->defaultErrorDescription; + } +} diff --git a/vendor/slim/slim/Slim/Error/Renderers/HtmlErrorRenderer.php b/vendor/slim/slim/Slim/Error/Renderers/HtmlErrorRenderer.php new file mode 100644 index 0000000..8fd838b --- /dev/null +++ b/vendor/slim/slim/Slim/Error/Renderers/HtmlErrorRenderer.php @@ -0,0 +1,83 @@ +The application could not run because of the following error:

'; + $html .= '

Details

'; + $html .= $this->renderExceptionFragment($exception); + } else { + $html = "

{$this->getErrorDescription($exception)}

"; + } + + return $this->renderHtmlBody($this->getErrorTitle($exception), $html); + } + + private function renderExceptionFragment(Throwable $exception): string + { + $html = sprintf('
Type: %s
', get_class($exception)); + + $code = $exception->getCode(); + $html .= sprintf('
Code: %s
', $code); + + $html .= sprintf('
Message: %s
', htmlentities($exception->getMessage())); + + $html .= sprintf('
File: %s
', $exception->getFile()); + + $html .= sprintf('
Line: %s
', $exception->getLine()); + + $html .= '

Trace

'; + $html .= sprintf('
%s
', htmlentities($exception->getTraceAsString())); + + return $html; + } + + public function renderHtmlBody(string $title = '', string $html = ''): string + { + return sprintf( + '' . + '' . + ' ' . + ' ' . + ' ' . + ' %s' . + ' ' . + ' ' . + ' ' . + '

%s

' . + '
%s
' . + ' Go Back' . + ' ' . + '', + $title, + $title, + $html + ); + } +} diff --git a/vendor/slim/slim/Slim/Error/Renderers/JsonErrorRenderer.php b/vendor/slim/slim/Slim/Error/Renderers/JsonErrorRenderer.php new file mode 100644 index 0000000..06085d2 --- /dev/null +++ b/vendor/slim/slim/Slim/Error/Renderers/JsonErrorRenderer.php @@ -0,0 +1,55 @@ + $this->getErrorTitle($exception)]; + + if ($displayErrorDetails) { + $error['exception'] = []; + do { + $error['exception'][] = $this->formatExceptionFragment($exception); + } while ($exception = $exception->getPrevious()); + } + + return (string) json_encode($error, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + } + + /** + * @return array + */ + private function formatExceptionFragment(Throwable $exception): array + { + $code = $exception->getCode(); + return [ + 'type' => get_class($exception), + 'code' => $code, + 'message' => $exception->getMessage(), + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + ]; + } +} diff --git a/vendor/slim/slim/Slim/Error/Renderers/PlainTextErrorRenderer.php b/vendor/slim/slim/Slim/Error/Renderers/PlainTextErrorRenderer.php new file mode 100644 index 0000000..fcb6e8a --- /dev/null +++ b/vendor/slim/slim/Slim/Error/Renderers/PlainTextErrorRenderer.php @@ -0,0 +1,59 @@ +getErrorTitle($exception)}\n"; + + if ($displayErrorDetails) { + $text .= $this->formatExceptionFragment($exception); + + while ($exception = $exception->getPrevious()) { + $text .= "\nPrevious Error:\n"; + $text .= $this->formatExceptionFragment($exception); + } + } + + return $text; + } + + private function formatExceptionFragment(Throwable $exception): string + { + $text = sprintf("Type: %s\n", get_class($exception)); + + $code = $exception->getCode(); + + $text .= sprintf("Code: %s\n", $code); + + $text .= sprintf("Message: %s\n", $exception->getMessage()); + + $text .= sprintf("File: %s\n", $exception->getFile()); + + $text .= sprintf("Line: %s\n", $exception->getLine()); + + $text .= sprintf('Trace: %s', $exception->getTraceAsString()); + + return $text; + } +} diff --git a/vendor/slim/slim/Slim/Error/Renderers/XmlErrorRenderer.php b/vendor/slim/slim/Slim/Error/Renderers/XmlErrorRenderer.php new file mode 100644 index 0000000..1171b79 --- /dev/null +++ b/vendor/slim/slim/Slim/Error/Renderers/XmlErrorRenderer.php @@ -0,0 +1,54 @@ +\n"; + $xml .= "\n " . $this->createCdataSection($this->getErrorTitle($exception)) . "\n"; + + if ($displayErrorDetails) { + do { + $xml .= " \n"; + $xml .= ' ' . get_class($exception) . "\n"; + $xml .= ' ' . $exception->getCode() . "\n"; + $xml .= ' ' . $this->createCdataSection($exception->getMessage()) . "\n"; + $xml .= ' ' . $exception->getFile() . "\n"; + $xml .= ' ' . $exception->getLine() . "\n"; + $xml .= " \n"; + } while ($exception = $exception->getPrevious()); + } + + $xml .= ''; + + return $xml; + } + + /** + * Returns a CDATA section with the given content. + */ + private function createCdataSection(string $content): string + { + return sprintf('', str_replace(']]>', ']]]]>', $content)); + } +} diff --git a/vendor/slim/slim/Slim/Exception/HttpBadRequestException.php b/vendor/slim/slim/Slim/Exception/HttpBadRequestException.php new file mode 100644 index 0000000..000c248 --- /dev/null +++ b/vendor/slim/slim/Slim/Exception/HttpBadRequestException.php @@ -0,0 +1,29 @@ +request = $request; + } + + public function getRequest(): ServerRequestInterface + { + return $this->request; + } + + public function getTitle(): string + { + return $this->title; + } + + public function setTitle(string $title): self + { + $this->title = $title; + return $this; + } + + public function getDescription(): string + { + return $this->description; + } + + public function setDescription(string $description): self + { + $this->description = $description; + return $this; + } +} diff --git a/vendor/slim/slim/Slim/Exception/HttpForbiddenException.php b/vendor/slim/slim/Slim/Exception/HttpForbiddenException.php new file mode 100644 index 0000000..d262a63 --- /dev/null +++ b/vendor/slim/slim/Slim/Exception/HttpForbiddenException.php @@ -0,0 +1,28 @@ +allowedMethods; + } + + /** + * @param string[] $methods + */ + public function setAllowedMethods(array $methods): self + { + $this->allowedMethods = $methods; + $this->message = 'Method not allowed. Must be one of: ' . implode(', ', $methods); + return $this; + } +} diff --git a/vendor/slim/slim/Slim/Exception/HttpNotFoundException.php b/vendor/slim/slim/Slim/Exception/HttpNotFoundException.php new file mode 100644 index 0000000..865146d --- /dev/null +++ b/vendor/slim/slim/Slim/Exception/HttpNotFoundException.php @@ -0,0 +1,27 @@ +message = $message; + } + + parent::__construct($request, $this->message, $this->code, $previous); + } +} diff --git a/vendor/slim/slim/Slim/Exception/HttpTooManyRequestsException.php b/vendor/slim/slim/Slim/Exception/HttpTooManyRequestsException.php new file mode 100644 index 0000000..af438ba --- /dev/null +++ b/vendor/slim/slim/Slim/Exception/HttpTooManyRequestsException.php @@ -0,0 +1,29 @@ + : App) + */ + public static function create( + ?ResponseFactoryInterface $responseFactory = null, + ?ContainerInterface $container = null, + ?CallableResolverInterface $callableResolver = null, + ?RouteCollectorInterface $routeCollector = null, + ?RouteResolverInterface $routeResolver = null, + ?MiddlewareDispatcherInterface $middlewareDispatcher = null + ): App { + static::$responseFactory = $responseFactory ?? static::$responseFactory; + return new App( + self::determineResponseFactory(), + $container ?? static::$container, + $callableResolver ?? static::$callableResolver, + $routeCollector ?? static::$routeCollector, + $routeResolver ?? static::$routeResolver, + $middlewareDispatcher ?? static::$middlewareDispatcher + ); + } + + /** + * @template TContainerInterface of (ContainerInterface) + * @param TContainerInterface $container + * @return App + */ + public static function createFromContainer(ContainerInterface $container): App + { + $responseFactory = $container->has(ResponseFactoryInterface::class) + && ( + $responseFactoryFromContainer = $container->get(ResponseFactoryInterface::class) + ) instanceof ResponseFactoryInterface + ? $responseFactoryFromContainer + : self::determineResponseFactory(); + + $callableResolver = $container->has(CallableResolverInterface::class) + && ( + $callableResolverFromContainer = $container->get(CallableResolverInterface::class) + ) instanceof CallableResolverInterface + ? $callableResolverFromContainer + : null; + + $routeCollector = $container->has(RouteCollectorInterface::class) + && ( + $routeCollectorFromContainer = $container->get(RouteCollectorInterface::class) + ) instanceof RouteCollectorInterface + ? $routeCollectorFromContainer + : null; + + $routeResolver = $container->has(RouteResolverInterface::class) + && ( + $routeResolverFromContainer = $container->get(RouteResolverInterface::class) + ) instanceof RouteResolverInterface + ? $routeResolverFromContainer + : null; + + $middlewareDispatcher = $container->has(MiddlewareDispatcherInterface::class) + && ( + $middlewareDispatcherFromContainer = $container->get(MiddlewareDispatcherInterface::class) + ) instanceof MiddlewareDispatcherInterface + ? $middlewareDispatcherFromContainer + : null; + + return new App( + $responseFactory, + $container, + $callableResolver, + $routeCollector, + $routeResolver, + $middlewareDispatcher + ); + } + + /** + * @throws RuntimeException + */ + public static function determineResponseFactory(): ResponseFactoryInterface + { + if (static::$responseFactory) { + if (static::$streamFactory) { + return static::attemptResponseFactoryDecoration(static::$responseFactory, static::$streamFactory); + } + return static::$responseFactory; + } + + $psr17FactoryProvider = static::$psr17FactoryProvider ?? new Psr17FactoryProvider(); + + /** @var Psr17Factory $psr17factory */ + foreach ($psr17FactoryProvider->getFactories() as $psr17factory) { + if ($psr17factory::isResponseFactoryAvailable()) { + $responseFactory = $psr17factory::getResponseFactory(); + + if (static::$streamFactory || $psr17factory::isStreamFactoryAvailable()) { + $streamFactory = static::$streamFactory ?? $psr17factory::getStreamFactory(); + return static::attemptResponseFactoryDecoration($responseFactory, $streamFactory); + } + + return $responseFactory; + } + } + + throw new RuntimeException( + "Could not detect any PSR-17 ResponseFactory implementations. " . + "Please install a supported implementation in order to use `AppFactory::create()`. " . + "See https://github.com/slimphp/Slim/blob/4.x/README.md for a list of supported implementations." + ); + } + + protected static function attemptResponseFactoryDecoration( + ResponseFactoryInterface $responseFactory, + StreamFactoryInterface $streamFactory + ): ResponseFactoryInterface { + if ( + static::$slimHttpDecoratorsAutomaticDetectionEnabled + && SlimHttpPsr17Factory::isResponseFactoryAvailable() + ) { + return SlimHttpPsr17Factory::createDecoratedResponseFactory($responseFactory, $streamFactory); + } + + return $responseFactory; + } + + public static function setPsr17FactoryProvider(Psr17FactoryProviderInterface $psr17FactoryProvider): void + { + static::$psr17FactoryProvider = $psr17FactoryProvider; + } + + public static function setResponseFactory(ResponseFactoryInterface $responseFactory): void + { + static::$responseFactory = $responseFactory; + } + + public static function setStreamFactory(StreamFactoryInterface $streamFactory): void + { + static::$streamFactory = $streamFactory; + } + + public static function setContainer(ContainerInterface $container): void + { + static::$container = $container; + } + + public static function setCallableResolver(CallableResolverInterface $callableResolver): void + { + static::$callableResolver = $callableResolver; + } + + public static function setRouteCollector(RouteCollectorInterface $routeCollector): void + { + static::$routeCollector = $routeCollector; + } + + public static function setRouteResolver(RouteResolverInterface $routeResolver): void + { + static::$routeResolver = $routeResolver; + } + + public static function setMiddlewareDispatcher(MiddlewareDispatcherInterface $middlewareDispatcher): void + { + static::$middlewareDispatcher = $middlewareDispatcher; + } + + public static function setSlimHttpDecoratorsAutomaticDetection(bool $enabled): void + { + static::$slimHttpDecoratorsAutomaticDetectionEnabled = $enabled; + } +} diff --git a/vendor/slim/slim/Slim/Factory/Psr17/GuzzlePsr17Factory.php b/vendor/slim/slim/Slim/Factory/Psr17/GuzzlePsr17Factory.php new file mode 100644 index 0000000..32a548a --- /dev/null +++ b/vendor/slim/slim/Slim/Factory/Psr17/GuzzlePsr17Factory.php @@ -0,0 +1,19 @@ +serverRequestCreator = $serverRequestCreator; + $this->serverRequestCreatorMethod = $serverRequestCreatorMethod; + } + + /** + * {@inheritdoc} + */ + public function createServerRequestFromGlobals(): ServerRequestInterface + { + /** @var callable $callable */ + $callable = [$this->serverRequestCreator, $this->serverRequestCreatorMethod]; + return (Closure::fromCallable($callable))(); + } +} diff --git a/vendor/slim/slim/Slim/Factory/Psr17/SlimHttpPsr17Factory.php b/vendor/slim/slim/Slim/Factory/Psr17/SlimHttpPsr17Factory.php new file mode 100644 index 0000000..5d63631 --- /dev/null +++ b/vendor/slim/slim/Slim/Factory/Psr17/SlimHttpPsr17Factory.php @@ -0,0 +1,39 @@ +serverRequestCreator = $serverRequestCreator; + } + + /** + * {@inheritdoc} + */ + public function createServerRequestFromGlobals(): ServerRequestInterface + { + if (!static::isServerRequestDecoratorAvailable()) { + throw new RuntimeException('The Slim-Http ServerRequest decorator is not available.'); + } + + $request = $this->serverRequestCreator->createServerRequestFromGlobals(); + + if ( + !(( + $decoratedServerRequest = new static::$serverRequestDecoratorClass($request) + ) instanceof ServerRequestInterface) + ) { + throw new RuntimeException(get_called_class() . ' could not instantiate a decorated server request.'); + } + + return $decoratedServerRequest; + } + + public static function isServerRequestDecoratorAvailable(): bool + { + return class_exists(static::$serverRequestDecoratorClass); + } +} diff --git a/vendor/slim/slim/Slim/Factory/Psr17/SlimPsr17Factory.php b/vendor/slim/slim/Slim/Factory/Psr17/SlimPsr17Factory.php new file mode 100644 index 0000000..46c46f9 --- /dev/null +++ b/vendor/slim/slim/Slim/Factory/Psr17/SlimPsr17Factory.php @@ -0,0 +1,19 @@ +getFactories() as $psr17Factory) { + if ($psr17Factory::isServerRequestCreatorAvailable()) { + $serverRequestCreator = $psr17Factory::getServerRequestCreator(); + return static::attemptServerRequestCreatorDecoration($serverRequestCreator); + } + } + + throw new RuntimeException( + "Could not detect any ServerRequest creator implementations. " . + "Please install a supported implementation in order to use `App::run()` " . + "without having to pass in a `ServerRequest` object. " . + "See https://github.com/slimphp/Slim/blob/4.x/README.md for a list of supported implementations." + ); + } + + protected static function attemptServerRequestCreatorDecoration( + ServerRequestCreatorInterface $serverRequestCreator + ): ServerRequestCreatorInterface { + if ( + static::$slimHttpDecoratorsAutomaticDetectionEnabled + && SlimHttpServerRequestCreator::isServerRequestDecoratorAvailable() + ) { + return new SlimHttpServerRequestCreator($serverRequestCreator); + } + + return $serverRequestCreator; + } + + public static function setPsr17FactoryProvider(Psr17FactoryProviderInterface $psr17FactoryProvider): void + { + static::$psr17FactoryProvider = $psr17FactoryProvider; + } + + public static function setServerRequestCreator(ServerRequestCreatorInterface $serverRequestCreator): void + { + self::$serverRequestCreator = $serverRequestCreator; + } + + public static function setSlimHttpDecoratorsAutomaticDetection(bool $enabled): void + { + static::$slimHttpDecoratorsAutomaticDetectionEnabled = $enabled; + } +} diff --git a/vendor/slim/slim/Slim/Handlers/ErrorHandler.php b/vendor/slim/slim/Slim/Handlers/ErrorHandler.php new file mode 100644 index 0000000..689b463 --- /dev/null +++ b/vendor/slim/slim/Slim/Handlers/ErrorHandler.php @@ -0,0 +1,309 @@ + + */ + protected array $errorRenderers = [ + 'application/json' => JsonErrorRenderer::class, + 'application/xml' => XmlErrorRenderer::class, + 'text/xml' => XmlErrorRenderer::class, + 'text/html' => HtmlErrorRenderer::class, + 'text/plain' => PlainTextErrorRenderer::class, + ]; + + protected bool $displayErrorDetails = false; + + protected bool $logErrors; + + protected bool $logErrorDetails = false; + + protected ?string $contentType = null; + + protected ?string $method = null; + + protected ServerRequestInterface $request; + + protected Throwable $exception; + + protected int $statusCode; + + protected CallableResolverInterface $callableResolver; + + protected ResponseFactoryInterface $responseFactory; + + protected LoggerInterface $logger; + + public function __construct( + CallableResolverInterface $callableResolver, + ResponseFactoryInterface $responseFactory, + ?LoggerInterface $logger = null + ) { + $this->callableResolver = $callableResolver; + $this->responseFactory = $responseFactory; + $this->logger = $logger ?: $this->getDefaultLogger(); + } + + /** + * Invoke error handler + * + * @param ServerRequestInterface $request The most recent Request object + * @param Throwable $exception The caught Exception object + * @param bool $displayErrorDetails Whether or not to display the error details + * @param bool $logErrors Whether or not to log errors + * @param bool $logErrorDetails Whether or not to log error details + */ + public function __invoke( + ServerRequestInterface $request, + Throwable $exception, + bool $displayErrorDetails, + bool $logErrors, + bool $logErrorDetails + ): ResponseInterface { + $this->displayErrorDetails = $displayErrorDetails; + $this->logErrors = $logErrors; + $this->logErrorDetails = $logErrorDetails; + $this->request = $request; + $this->exception = $exception; + $this->method = $request->getMethod(); + $this->statusCode = $this->determineStatusCode(); + if ($this->contentType === null) { + $this->contentType = $this->determineContentType($request); + } + + if ($logErrors) { + $this->writeToErrorLog(); + } + + return $this->respond(); + } + + /** + * Force the content type for all error handler responses. + * + * @param string|null $contentType The content type + */ + public function forceContentType(?string $contentType): void + { + $this->contentType = $contentType; + } + + protected function determineStatusCode(): int + { + if ($this->method === 'OPTIONS') { + return 200; + } + + if ($this->exception instanceof HttpException) { + return $this->exception->getCode(); + } + + return 500; + } + + /** + * Determine which content type we know about is wanted using Accept header + * + * Note: This method is a bare-bones implementation designed specifically for + * Slim's error handling requirements. Consider a fully-feature solution such + * as willdurand/negotiation for any other situation. + */ + protected function determineContentType(ServerRequestInterface $request): ?string + { + $acceptHeader = $request->getHeaderLine('Accept'); + $selectedContentTypes = array_intersect( + explode(',', $acceptHeader), + array_keys($this->errorRenderers) + ); + $count = count($selectedContentTypes); + + if ($count) { + $current = current($selectedContentTypes); + + /** + * Ensure other supported content types take precedence over text/plain + * when multiple content types are provided via Accept header. + */ + if ($current === 'text/plain' && $count > 1) { + $next = next($selectedContentTypes); + if (is_string($next)) { + return $next; + } + } + + if (is_string($current)) { + return $current; + } + } + + if (preg_match('/\+(json|xml)/', $acceptHeader, $matches)) { + $mediaType = 'application/' . $matches[1]; + if (array_key_exists($mediaType, $this->errorRenderers)) { + return $mediaType; + } + } + + return null; + } + + /** + * Determine which renderer to use based on content type + * + * @throws RuntimeException + */ + protected function determineRenderer(): callable + { + if ($this->contentType !== null && array_key_exists($this->contentType, $this->errorRenderers)) { + $renderer = $this->errorRenderers[$this->contentType]; + } else { + $renderer = $this->defaultErrorRenderer; + } + + return $this->callableResolver->resolve($renderer); + } + + /** + * Register an error renderer for a specific content-type + * + * @param string $contentType The content-type this renderer should be registered to + * @param ErrorRendererInterface|string|callable $errorRenderer The error renderer + */ + public function registerErrorRenderer(string $contentType, $errorRenderer): void + { + $this->errorRenderers[$contentType] = $errorRenderer; + } + + /** + * Set the default error renderer + * + * @param string $contentType The content type of the default error renderer + * @param ErrorRendererInterface|string|callable $errorRenderer The default error renderer + */ + public function setDefaultErrorRenderer(string $contentType, $errorRenderer): void + { + $this->defaultErrorRendererContentType = $contentType; + $this->defaultErrorRenderer = $errorRenderer; + } + + /** + * Set the renderer for the error logger + * + * @param ErrorRendererInterface|string|callable $logErrorRenderer + */ + public function setLogErrorRenderer($logErrorRenderer): void + { + $this->logErrorRenderer = $logErrorRenderer; + } + + /** + * Write to the error log if $logErrors has been set to true + */ + protected function writeToErrorLog(): void + { + $renderer = $this->callableResolver->resolve($this->logErrorRenderer); + $error = $renderer($this->exception, $this->logErrorDetails); + if ($this->logErrorRenderer === PlainTextErrorRenderer::class && !$this->displayErrorDetails) { + $error .= "\nTips: To display error details in HTTP response "; + $error .= 'set "displayErrorDetails" to true in the ErrorHandler constructor.'; + } + $this->logError($error); + } + + /** + * Wraps the error_log function so that this can be easily tested + */ + protected function logError(string $error): void + { + $this->logger->error($error); + } + + /** + * Returns a default logger implementation. + */ + protected function getDefaultLogger(): LoggerInterface + { + return new Logger(); + } + + protected function respond(): ResponseInterface + { + $response = $this->responseFactory->createResponse($this->statusCode); + if ($this->contentType !== null && array_key_exists($this->contentType, $this->errorRenderers)) { + $response = $response->withHeader('Content-type', $this->contentType); + } else { + $response = $response->withHeader('Content-type', $this->defaultErrorRendererContentType); + } + + if ($this->exception instanceof HttpMethodNotAllowedException) { + $allowedMethods = implode(', ', $this->exception->getAllowedMethods()); + $response = $response->withHeader('Allow', $allowedMethods); + } + + $renderer = $this->determineRenderer(); + $body = call_user_func($renderer, $this->exception, $this->displayErrorDetails); + if ($body !== false) { + /** @var string $body */ + $response->getBody()->write($body); + } + + return $response; + } +} diff --git a/vendor/slim/slim/Slim/Handlers/Strategies/RequestHandler.php b/vendor/slim/slim/Slim/Handlers/Strategies/RequestHandler.php new file mode 100644 index 0000000..ea88a5f --- /dev/null +++ b/vendor/slim/slim/Slim/Handlers/Strategies/RequestHandler.php @@ -0,0 +1,48 @@ +appendRouteArgumentsToRequestAttributes = $appendRouteArgumentsToRequestAttributes; + } + + /** + * Invoke a route callable that implements RequestHandlerInterface + * + * @param array $routeArguments + */ + public function __invoke( + callable $callable, + ServerRequestInterface $request, + ResponseInterface $response, + array $routeArguments + ): ResponseInterface { + if ($this->appendRouteArgumentsToRequestAttributes) { + foreach ($routeArguments as $k => $v) { + $request = $request->withAttribute($k, $v); + } + } + + return $callable($request); + } +} diff --git a/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php b/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php new file mode 100644 index 0000000..45b2c05 --- /dev/null +++ b/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php @@ -0,0 +1,40 @@ + $routeArguments + */ + public function __invoke( + callable $callable, + ServerRequestInterface $request, + ResponseInterface $response, + array $routeArguments + ): ResponseInterface { + foreach ($routeArguments as $k => $v) { + $request = $request->withAttribute($k, $v); + } + + return $callable($request, $response, $routeArguments); + } +} diff --git a/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponseArgs.php b/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponseArgs.php new file mode 100644 index 0000000..6eab63a --- /dev/null +++ b/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponseArgs.php @@ -0,0 +1,39 @@ + $routeArguments + */ + public function __invoke( + callable $callable, + ServerRequestInterface $request, + ResponseInterface $response, + array $routeArguments + ): ResponseInterface { + return $callable($request, $response, ...array_values($routeArguments)); + } +} diff --git a/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponseNamedArgs.php b/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponseNamedArgs.php new file mode 100644 index 0000000..f360596 --- /dev/null +++ b/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponseNamedArgs.php @@ -0,0 +1,45 @@ += 8.0.0'); + } + } + + /** + * Invoke a route callable with request, response and all route parameters + * as individual arguments. + * + * @param array $routeArguments + */ + public function __invoke( + callable $callable, + ServerRequestInterface $request, + ResponseInterface $response, + array $routeArguments + ): ResponseInterface { + return $callable($request, $response, ...$routeArguments); + } +} diff --git a/vendor/slim/slim/Slim/Interfaces/AdvancedCallableResolverInterface.php b/vendor/slim/slim/Slim/Interfaces/AdvancedCallableResolverInterface.php new file mode 100644 index 0000000..aa1d897 --- /dev/null +++ b/vendor/slim/slim/Slim/Interfaces/AdvancedCallableResolverInterface.php @@ -0,0 +1,28 @@ + $routeArguments The route's placeholder arguments + * + * @return ResponseInterface The response from the callable. + */ + public function __invoke( + callable $callable, + ServerRequestInterface $request, + ResponseInterface $response, + array $routeArguments + ): ResponseInterface; +} diff --git a/vendor/slim/slim/Slim/Interfaces/MiddlewareDispatcherInterface.php b/vendor/slim/slim/Slim/Interfaces/MiddlewareDispatcherInterface.php new file mode 100644 index 0000000..9fa34a6 --- /dev/null +++ b/vendor/slim/slim/Slim/Interfaces/MiddlewareDispatcherInterface.php @@ -0,0 +1,43 @@ + + */ + public function setBasePath(string $basePath): RouteCollectorProxyInterface; + + /** + * Add GET route + * + * @param string $pattern The route URI pattern + * @param callable|string $callable The route callback routine + */ + public function get(string $pattern, $callable): RouteInterface; + + /** + * Add POST route + * + * @param string $pattern The route URI pattern + * @param callable|string $callable The route callback routine + */ + public function post(string $pattern, $callable): RouteInterface; + + /** + * Add PUT route + * + * @param string $pattern The route URI pattern + * @param callable|string $callable The route callback routine + */ + public function put(string $pattern, $callable): RouteInterface; + + /** + * Add PATCH route + * + * @param string $pattern The route URI pattern + * @param callable|string $callable The route callback routine + */ + public function patch(string $pattern, $callable): RouteInterface; + + /** + * Add DELETE route + * + * @param string $pattern The route URI pattern + * @param callable|string $callable The route callback routine + */ + public function delete(string $pattern, $callable): RouteInterface; + + /** + * Add OPTIONS route + * + * @param string $pattern The route URI pattern + * @param callable|string $callable The route callback routine + */ + public function options(string $pattern, $callable): RouteInterface; + + /** + * Add route for any HTTP method + * + * @param string $pattern The route URI pattern + * @param callable|string $callable The route callback routine + */ + public function any(string $pattern, $callable): RouteInterface; + + /** + * Add route with multiple methods + * + * @param string[] $methods Numeric array of HTTP method names + * @param string $pattern The route URI pattern + * @param callable|string $callable The route callback routine + */ + public function map(array $methods, string $pattern, $callable): RouteInterface; + + /** + * Route Groups + * + * This method accepts a route pattern and a callback. All route + * declarations in the callback will be prepended by the group(s) + * that it is in. + * @param string|callable $callable + */ + public function group(string $pattern, $callable): RouteGroupInterface; + + /** + * Add a route that sends an HTTP redirect + * + * @param string|UriInterface $to + */ + public function redirect(string $from, $to, int $status = 302): RouteInterface; +} diff --git a/vendor/slim/slim/Slim/Interfaces/RouteGroupInterface.php b/vendor/slim/slim/Slim/Interfaces/RouteGroupInterface.php new file mode 100644 index 0000000..efc1c5a --- /dev/null +++ b/vendor/slim/slim/Slim/Interfaces/RouteGroupInterface.php @@ -0,0 +1,43 @@ + $dispatcher + */ + public function appendMiddlewareToDispatcher(MiddlewareDispatcher $dispatcher): RouteGroupInterface; + + /** + * Get the RouteGroup's pattern + */ + public function getPattern(): string; +} diff --git a/vendor/slim/slim/Slim/Interfaces/RouteInterface.php b/vendor/slim/slim/Slim/Interfaces/RouteInterface.php new file mode 100644 index 0000000..8ed817e --- /dev/null +++ b/vendor/slim/slim/Slim/Interfaces/RouteInterface.php @@ -0,0 +1,124 @@ + + */ + public function getArguments(): array; + + /** + * Set a route argument + */ + public function setArgument(string $name, string $value): RouteInterface; + + /** + * Replace route arguments + * + * @param array $arguments + */ + public function setArguments(array $arguments): self; + + /** + * @param MiddlewareInterface|string|callable $middleware + */ + public function add($middleware): self; + + public function addMiddleware(MiddlewareInterface $middleware): self; + + /** + * Prepare the route for use + * + * @param array $arguments + */ + public function prepare(array $arguments): self; + + /** + * Run route + * + * This method traverses the middleware stack, including the route's callable + * and captures the resultant HTTP response object. It then sends the response + * back to the Application. + */ + public function run(ServerRequestInterface $request): ResponseInterface; +} diff --git a/vendor/slim/slim/Slim/Interfaces/RouteParserInterface.php b/vendor/slim/slim/Slim/Interfaces/RouteParserInterface.php new file mode 100644 index 0000000..8ccea3b --- /dev/null +++ b/vendor/slim/slim/Slim/Interfaces/RouteParserInterface.php @@ -0,0 +1,53 @@ + $data Named argument replacement data + * @param array $queryParams Optional query string parameters + * + * @throws RuntimeException If named route does not exist + * @throws InvalidArgumentException If required data not provided + */ + public function relativeUrlFor(string $routeName, array $data = [], array $queryParams = []): string; + + /** + * Build the path for a named route including the base path + * + * @param string $routeName Route name + * @param array $data Named argument replacement data + * @param array $queryParams Optional query string parameters + * + * @throws RuntimeException If named route does not exist + * @throws InvalidArgumentException If required data not provided + */ + public function urlFor(string $routeName, array $data = [], array $queryParams = []): string; + + /** + * Get fully qualified URL for named route + * + * @param UriInterface $uri + * @param string $routeName Route name + * @param array $data Named argument replacement data + * @param array $queryParams Optional query string parameters + */ + public function fullUrlFor(UriInterface $uri, string $routeName, array $data = [], array $queryParams = []): string; +} diff --git a/vendor/slim/slim/Slim/Interfaces/RouteResolverInterface.php b/vendor/slim/slim/Slim/Interfaces/RouteResolverInterface.php new file mode 100644 index 0000000..256a359 --- /dev/null +++ b/vendor/slim/slim/Slim/Interfaces/RouteResolverInterface.php @@ -0,0 +1,17 @@ +getPath() + */ + public function computeRoutingResults(string $uri, string $method): RoutingResults; + + public function resolveRoute(string $identifier): RouteInterface; +} diff --git a/vendor/slim/slim/Slim/Interfaces/ServerRequestCreatorInterface.php b/vendor/slim/slim/Slim/Interfaces/ServerRequestCreatorInterface.php new file mode 100644 index 0000000..54d231e --- /dev/null +++ b/vendor/slim/slim/Slim/Interfaces/ServerRequestCreatorInterface.php @@ -0,0 +1,18 @@ + $context + * + * @throws InvalidArgumentException + */ + public function log($level, $message, array $context = []): void + { + error_log((string) $message); + } +} diff --git a/vendor/slim/slim/Slim/Middleware/BodyParsingMiddleware.php b/vendor/slim/slim/Slim/Middleware/BodyParsingMiddleware.php new file mode 100644 index 0000000..94bba37 --- /dev/null +++ b/vendor/slim/slim/Slim/Middleware/BodyParsingMiddleware.php @@ -0,0 +1,197 @@ + callable + */ + public function __construct(array $bodyParsers = []) + { + $this->registerDefaultBodyParsers(); + + foreach ($bodyParsers as $mediaType => $parser) { + $this->registerBodyParser($mediaType, $parser); + } + } + + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + $parsedBody = $request->getParsedBody(); + + if (empty($parsedBody)) { + $parsedBody = $this->parseBody($request); + $request = $request->withParsedBody($parsedBody); + } + + return $handler->handle($request); + } + + /** + * @param string $mediaType A HTTP media type (excluding content-type params). + * @param callable $callable A callable that returns parsed contents for media type. + */ + public function registerBodyParser(string $mediaType, callable $callable): self + { + $this->bodyParsers[$mediaType] = $callable; + return $this; + } + + /** + * @param string $mediaType A HTTP media type (excluding content-type params). + */ + public function hasBodyParser(string $mediaType): bool + { + return isset($this->bodyParsers[$mediaType]); + } + + /** + * @param string $mediaType A HTTP media type (excluding content-type params). + * @throws RuntimeException + */ + public function getBodyParser(string $mediaType): callable + { + if (!isset($this->bodyParsers[$mediaType])) { + throw new RuntimeException('No parser for type ' . $mediaType); + } + return $this->bodyParsers[$mediaType]; + } + + protected function registerDefaultBodyParsers(): void + { + $this->registerBodyParser('application/json', static function ($input) { + $result = json_decode($input, true); + + if (!is_array($result)) { + return null; + } + + return $result; + }); + + $this->registerBodyParser('application/x-www-form-urlencoded', static function ($input) { + parse_str($input, $data); + return $data; + }); + + $xmlCallable = static function ($input) { + $backup = self::disableXmlEntityLoader(true); + $backup_errors = libxml_use_internal_errors(true); + $result = simplexml_load_string($input); + + self::disableXmlEntityLoader($backup); + libxml_clear_errors(); + libxml_use_internal_errors($backup_errors); + + if ($result === false) { + return null; + } + + return $result; + }; + + $this->registerBodyParser('application/xml', $xmlCallable); + $this->registerBodyParser('text/xml', $xmlCallable); + } + + /** + * @return null|array|object + */ + protected function parseBody(ServerRequestInterface $request) + { + $mediaType = $this->getMediaType($request); + if ($mediaType === null) { + return null; + } + + // Check if this specific media type has a parser registered first + if (!isset($this->bodyParsers[$mediaType])) { + // If not, look for a media type with a structured syntax suffix (RFC 6839) + $parts = explode('+', $mediaType); + if (count($parts) >= 2) { + $mediaType = 'application/' . $parts[count($parts) - 1]; + } + } + + if (isset($this->bodyParsers[$mediaType])) { + $body = (string)$request->getBody(); + $parsed = $this->bodyParsers[$mediaType]($body); + + if ($parsed !== null && !is_object($parsed) && !is_array($parsed)) { + throw new RuntimeException( + 'Request body media type parser return value must be an array, an object, or null' + ); + } + + return $parsed; + } + + return null; + } + + /** + * @return string|null The serverRequest media type, minus content-type params + */ + protected function getMediaType(ServerRequestInterface $request): ?string + { + $contentType = $request->getHeader('Content-Type')[0] ?? null; + + if (is_string($contentType) && trim($contentType) !== '') { + $contentTypeParts = explode(';', $contentType); + return strtolower(trim($contentTypeParts[0])); + } + + return null; + } + + protected static function disableXmlEntityLoader(bool $disable): bool + { + if (LIBXML_VERSION >= 20900) { + // libxml >= 2.9.0 disables entity loading by default, so it is + // safe to skip the real call (deprecated in PHP 8). + return true; + } + + // @codeCoverageIgnoreStart + return libxml_disable_entity_loader($disable); + // @codeCoverageIgnoreEnd + } +} diff --git a/vendor/slim/slim/Slim/Middleware/ContentLengthMiddleware.php b/vendor/slim/slim/Slim/Middleware/ContentLengthMiddleware.php new file mode 100644 index 0000000..e289fa3 --- /dev/null +++ b/vendor/slim/slim/Slim/Middleware/ContentLengthMiddleware.php @@ -0,0 +1,33 @@ +handle($request); + + // Add Content-Length header if not already added + $size = $response->getBody()->getSize(); + if ($size !== null && !$response->hasHeader('Content-Length')) { + $response = $response->withHeader('Content-Length', (string) $size); + } + + return $response; + } +} diff --git a/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php b/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php new file mode 100644 index 0000000..39b1e58 --- /dev/null +++ b/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php @@ -0,0 +1,213 @@ +callableResolver = $callableResolver; + $this->responseFactory = $responseFactory; + $this->displayErrorDetails = $displayErrorDetails; + $this->logErrors = $logErrors; + $this->logErrorDetails = $logErrorDetails; + $this->logger = $logger; + } + + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + try { + return $handler->handle($request); + } catch (Throwable $e) { + return $this->handleException($request, $e); + } + } + + public function handleException(ServerRequestInterface $request, Throwable $exception): ResponseInterface + { + if ($exception instanceof HttpException) { + $request = $exception->getRequest(); + } + + $exceptionType = get_class($exception); + $handler = $this->getErrorHandler($exceptionType); + + return $handler($request, $exception, $this->displayErrorDetails, $this->logErrors, $this->logErrorDetails); + } + + /** + * Get callable to handle scenarios where an error + * occurs when processing the current request. + * + * @param string $type Exception/Throwable name. ie: RuntimeException::class + * @return callable|ErrorHandler + */ + public function getErrorHandler(string $type) + { + if (isset($this->handlers[$type])) { + return $this->callableResolver->resolve($this->handlers[$type]); + } + + if (isset($this->subClassHandlers[$type])) { + return $this->callableResolver->resolve($this->subClassHandlers[$type]); + } + + foreach ($this->subClassHandlers as $class => $handler) { + if (is_subclass_of($type, $class)) { + return $this->callableResolver->resolve($handler); + } + } + + return $this->getDefaultErrorHandler(); + } + + /** + * Get default error handler + * + * @return ErrorHandler|callable + */ + public function getDefaultErrorHandler() + { + if ($this->defaultErrorHandler === null) { + $this->defaultErrorHandler = new ErrorHandler( + $this->callableResolver, + $this->responseFactory, + $this->logger + ); + } + + return $this->callableResolver->resolve($this->defaultErrorHandler); + } + + /** + * Set callable as the default Slim application error handler. + * + * The callable signature MUST match the ErrorHandlerInterface + * + * @see \Slim\Interfaces\ErrorHandlerInterface + * + * 1. Instance of \Psr\Http\Message\ServerRequestInterface + * 2. Instance of \Throwable + * 3. Boolean $displayErrorDetails + * 4. Boolean $logErrors + * 5. Boolean $logErrorDetails + * + * The callable MUST return an instance of + * \Psr\Http\Message\ResponseInterface. + * + * @param string|callable|ErrorHandler $handler + */ + public function setDefaultErrorHandler($handler): self + { + $this->defaultErrorHandler = $handler; + return $this; + } + + /** + * Set callable to handle scenarios where an error + * occurs when processing the current request. + * + * The callable signature MUST match the ErrorHandlerInterface + * + * Pass true to $handleSubclasses to make the handler handle all subclasses of + * the type as well. Pass an array of classes to make the same function handle multiple exceptions. + * + * @see \Slim\Interfaces\ErrorHandlerInterface + * + * 1. Instance of \Psr\Http\Message\ServerRequestInterface + * 2. Instance of \Throwable + * 3. Boolean $displayErrorDetails + * 4. Boolean $logErrors + * 5. Boolean $logErrorDetails + * + * The callable MUST return an instance of + * \Psr\Http\Message\ResponseInterface. + * + * @param string|string[] $typeOrTypes Exception/Throwable name. + * ie: RuntimeException::class or an array of classes + * ie: [HttpNotFoundException::class, HttpMethodNotAllowedException::class] + * @param string|callable|ErrorHandlerInterface $handler + */ + public function setErrorHandler($typeOrTypes, $handler, bool $handleSubclasses = false): self + { + if (is_array($typeOrTypes)) { + foreach ($typeOrTypes as $type) { + $this->addErrorHandler($type, $handler, $handleSubclasses); + } + } else { + $this->addErrorHandler($typeOrTypes, $handler, $handleSubclasses); + } + + return $this; + } + + /** + * Used internally to avoid code repetition when passing multiple exceptions to setErrorHandler(). + * @param string|callable|ErrorHandlerInterface $handler + */ + private function addErrorHandler(string $type, $handler, bool $handleSubclasses): void + { + if ($handleSubclasses) { + $this->subClassHandlers[$type] = $handler; + } else { + $this->handlers[$type] = $handler; + } + } +} diff --git a/vendor/slim/slim/Slim/Middleware/MethodOverrideMiddleware.php b/vendor/slim/slim/Slim/Middleware/MethodOverrideMiddleware.php new file mode 100644 index 0000000..553463e --- /dev/null +++ b/vendor/slim/slim/Slim/Middleware/MethodOverrideMiddleware.php @@ -0,0 +1,44 @@ +getHeaderLine('X-Http-Method-Override'); + + if ($methodHeader) { + $request = $request->withMethod($methodHeader); + } elseif (strtoupper($request->getMethod()) === 'POST') { + $body = $request->getParsedBody(); + + if (is_array($body) && !empty($body['_METHOD'])) { + $request = $request->withMethod($body['_METHOD']); + } + + if ($request->getBody()->eof()) { + $request->getBody()->rewind(); + } + } + + return $handler->handle($request); + } +} diff --git a/vendor/slim/slim/Slim/Middleware/OutputBufferingMiddleware.php b/vendor/slim/slim/Slim/Middleware/OutputBufferingMiddleware.php new file mode 100644 index 0000000..8bfbbf6 --- /dev/null +++ b/vendor/slim/slim/Slim/Middleware/OutputBufferingMiddleware.php @@ -0,0 +1,75 @@ +streamFactory = $streamFactory; + $this->style = $style; + + if (!in_array($style, [static::APPEND, static::PREPEND], true)) { + throw new InvalidArgumentException("Invalid style `{$style}`. Must be `append` or `prepend`"); + } + } + + /** + * @throws Throwable + */ + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + try { + ob_start(); + $response = $handler->handle($request); + $output = ob_get_clean(); + } catch (Throwable $e) { + ob_end_clean(); + throw $e; + } + + if (!empty($output)) { + if ($this->style === static::PREPEND) { + $body = $this->streamFactory->createStream(); + $body->write($output . $response->getBody()); + $response = $response->withBody($body); + } elseif ($this->style === static::APPEND && $response->getBody()->isWritable()) { + $response->getBody()->write($output); + } + } + + return $response; + } +} diff --git a/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php b/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php new file mode 100644 index 0000000..a3d3085 --- /dev/null +++ b/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php @@ -0,0 +1,98 @@ +routeResolver = $routeResolver; + $this->routeParser = $routeParser; + } + + /** + * @throws HttpNotFoundException + * @throws HttpMethodNotAllowedException + * @throws RuntimeException + */ + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + $request = $this->performRouting($request); + return $handler->handle($request); + } + + /** + * Perform routing + * + * @param ServerRequestInterface $request PSR7 Server Request + * + * @throws HttpNotFoundException + * @throws HttpMethodNotAllowedException + * @throws RuntimeException + */ + public function performRouting(ServerRequestInterface $request): ServerRequestInterface + { + $request = $request->withAttribute(RouteContext::ROUTE_PARSER, $this->routeParser); + + $routingResults = $this->resolveRoutingResultsFromRequest($request); + $routeStatus = $routingResults->getRouteStatus(); + + $request = $request->withAttribute(RouteContext::ROUTING_RESULTS, $routingResults); + + switch ($routeStatus) { + case RoutingResults::FOUND: + $routeArguments = $routingResults->getRouteArguments(); + $routeIdentifier = $routingResults->getRouteIdentifier() ?? ''; + $route = $this->routeResolver + ->resolveRoute($routeIdentifier) + ->prepare($routeArguments); + return $request->withAttribute(RouteContext::ROUTE, $route); + + case RoutingResults::NOT_FOUND: + throw new HttpNotFoundException($request); + + case RoutingResults::METHOD_NOT_ALLOWED: + $exception = new HttpMethodNotAllowedException($request); + $exception->setAllowedMethods($routingResults->getAllowedMethods()); + throw $exception; + + default: + throw new RuntimeException('An unexpected error occurred while performing routing.'); + } + } + + /** + * Resolves the route from the given request + */ + protected function resolveRoutingResultsFromRequest(ServerRequestInterface $request): RoutingResults + { + return $this->routeResolver->computeRoutingResults( + $request->getUri()->getPath(), + $request->getMethod() + ); + } +} diff --git a/vendor/slim/slim/Slim/MiddlewareDispatcher.php b/vendor/slim/slim/Slim/MiddlewareDispatcher.php new file mode 100644 index 0000000..1d4c668 --- /dev/null +++ b/vendor/slim/slim/Slim/MiddlewareDispatcher.php @@ -0,0 +1,286 @@ +seedMiddlewareStack($kernel); + $this->callableResolver = $callableResolver; + $this->container = $container; + } + + /** + * {@inheritdoc} + */ + public function seedMiddlewareStack(RequestHandlerInterface $kernel): void + { + $this->tip = $kernel; + } + + /** + * Invoke the middleware stack + */ + public function handle(ServerRequestInterface $request): ResponseInterface + { + return $this->tip->handle($request); + } + + /** + * Add a new middleware to the stack + * + * Middleware are organized as a stack. That means middleware + * that have been added before will be executed after the newly + * added one (last in, first out). + * + * @param MiddlewareInterface|string|callable $middleware + */ + public function add($middleware): MiddlewareDispatcherInterface + { + if ($middleware instanceof MiddlewareInterface) { + return $this->addMiddleware($middleware); + } + + if (is_string($middleware)) { + return $this->addDeferred($middleware); + } + + if (is_callable($middleware)) { + return $this->addCallable($middleware); + } + + /** @phpstan-ignore-next-line */ + throw new RuntimeException( + 'A middleware must be an object/class name referencing an implementation of ' . + 'MiddlewareInterface or a callable with a matching signature.' + ); + } + + /** + * Add a new middleware to the stack + * + * Middleware are organized as a stack. That means middleware + * that have been added before will be executed after the newly + * added one (last in, first out). + */ + public function addMiddleware(MiddlewareInterface $middleware): MiddlewareDispatcherInterface + { + $next = $this->tip; + $this->tip = new class ($middleware, $next) implements RequestHandlerInterface { + private MiddlewareInterface $middleware; + + private RequestHandlerInterface $next; + + public function __construct(MiddlewareInterface $middleware, RequestHandlerInterface $next) + { + $this->middleware = $middleware; + $this->next = $next; + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + return $this->middleware->process($request, $this->next); + } + }; + + return $this; + } + + /** + * Add a new middleware by class name + * + * Middleware are organized as a stack. That means middleware + * that have been added before will be executed after the newly + * added one (last in, first out). + * @return MiddlewareDispatcher + */ + public function addDeferred(string $middleware): self + { + $next = $this->tip; + $this->tip = new class ( + $middleware, + $next, + $this->container, + $this->callableResolver + ) implements RequestHandlerInterface { + private string $middleware; + + private RequestHandlerInterface $next; + + private ?ContainerInterface $container; + + private ?CallableResolverInterface $callableResolver; + + public function __construct( + string $middleware, + RequestHandlerInterface $next, + ?ContainerInterface $container = null, + ?CallableResolverInterface $callableResolver = null + ) { + $this->middleware = $middleware; + $this->next = $next; + $this->container = $container; + $this->callableResolver = $callableResolver; + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + if ($this->callableResolver instanceof AdvancedCallableResolverInterface) { + $callable = $this->callableResolver->resolveMiddleware($this->middleware); + return $callable($request, $this->next); + } + + $callable = null; + + if ($this->callableResolver instanceof CallableResolverInterface) { + try { + $callable = $this->callableResolver->resolve($this->middleware); + } catch (RuntimeException $e) { + // Do Nothing + } + } + + if (!$callable) { + $resolved = $this->middleware; + $instance = null; + $method = null; + + /** @psalm-suppress ArgumentTypeCoercion */ + // Check for Slim callable as `class:method` + if (preg_match(CallableResolver::$callablePattern, $resolved, $matches)) { + $resolved = $matches[1]; + $method = $matches[2]; + } + + if ($this->container && $this->container->has($resolved)) { + $instance = $this->container->get($resolved); + if ($instance instanceof MiddlewareInterface) { + return $instance->process($request, $this->next); + } + } elseif (!function_exists($resolved)) { + if (!class_exists($resolved)) { + throw new RuntimeException(sprintf('Middleware %s does not exist', $resolved)); + } + $instance = new $resolved($this->container); + } + + if ($instance && $instance instanceof MiddlewareInterface) { + return $instance->process($request, $this->next); + } + + $callable = $instance ?? $resolved; + if ($instance && $method) { + $callable = [$instance, $method]; + } + + if ($this->container && $callable instanceof Closure) { + $callable = $callable->bindTo($this->container); + } + } + + if (!is_callable($callable)) { + throw new RuntimeException( + sprintf( + 'Middleware %s is not resolvable', + $this->middleware + ) + ); + } + + return $callable($request, $this->next); + } + }; + + return $this; + } + + /** + * Add a (non-standard) callable middleware to the stack + * + * Middleware are organized as a stack. That means middleware + * that have been added before will be executed after the newly + * added one (last in, first out). + * @return MiddlewareDispatcher + */ + public function addCallable(callable $middleware): self + { + $next = $this->tip; + + if ($this->container && $middleware instanceof Closure) { + /** @var Closure $middleware */ + $middleware = $middleware->bindTo($this->container); + } + + $this->tip = new class ($middleware, $next) implements RequestHandlerInterface { + /** + * @var callable + */ + private $middleware; + + /** + * @var RequestHandlerInterface + */ + private $next; + + public function __construct(callable $middleware, RequestHandlerInterface $next) + { + $this->middleware = $middleware; + $this->next = $next; + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + return ($this->middleware)($request, $this->next); + } + }; + + return $this; + } +} diff --git a/vendor/slim/slim/Slim/ResponseEmitter.php b/vendor/slim/slim/Slim/ResponseEmitter.php new file mode 100644 index 0000000..fac36e9 --- /dev/null +++ b/vendor/slim/slim/Slim/ResponseEmitter.php @@ -0,0 +1,136 @@ +responseChunkSize = $responseChunkSize; + } + + /** + * Send the response the client + */ + public function emit(ResponseInterface $response): void + { + $isEmpty = $this->isResponseEmpty($response); + if (headers_sent() === false) { + $this->emitHeaders($response); + + // Set the status _after_ the headers, because of PHP's "helpful" behavior with location headers. + // See https://github.com/slimphp/Slim/issues/1730 + + $this->emitStatusLine($response); + } + + if (!$isEmpty) { + $this->emitBody($response); + } + } + + /** + * Emit Response Headers + */ + private function emitHeaders(ResponseInterface $response): void + { + foreach ($response->getHeaders() as $name => $values) { + $first = strtolower($name) !== 'set-cookie'; + foreach ($values as $value) { + $header = sprintf('%s: %s', $name, $value); + header($header, $first); + $first = false; + } + } + } + + /** + * Emit Status Line + */ + private function emitStatusLine(ResponseInterface $response): void + { + $statusLine = sprintf( + 'HTTP/%s %s %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + ); + header($statusLine, true, $response->getStatusCode()); + } + + /** + * Emit Body + */ + private function emitBody(ResponseInterface $response): void + { + $body = $response->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + + $amountToRead = (int) $response->getHeaderLine('Content-Length'); + if (!$amountToRead) { + $amountToRead = $body->getSize(); + } + + if ($amountToRead) { + while ($amountToRead > 0 && !$body->eof()) { + $length = min($this->responseChunkSize, $amountToRead); + $data = $body->read($length); + echo $data; + + $amountToRead -= strlen($data); + + if (connection_status() !== CONNECTION_NORMAL) { + break; + } + } + } else { + while (!$body->eof()) { + echo $body->read($this->responseChunkSize); + if (connection_status() !== CONNECTION_NORMAL) { + break; + } + } + } + } + + /** + * Asserts response body is empty or status code is 204, 205 or 304 + */ + public function isResponseEmpty(ResponseInterface $response): bool + { + if (in_array($response->getStatusCode(), [204, 205, 304], true)) { + return true; + } + $stream = $response->getBody(); + $seekable = $stream->isSeekable(); + if ($seekable) { + $stream->rewind(); + } + return $seekable ? $stream->read(1) === '' : $stream->eof(); + } +} diff --git a/vendor/slim/slim/Slim/Routing/Dispatcher.php b/vendor/slim/slim/Slim/Routing/Dispatcher.php new file mode 100644 index 0000000..e33eac3 --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/Dispatcher.php @@ -0,0 +1,78 @@ +routeCollector = $routeCollector; + } + + protected function createDispatcher(): FastRouteDispatcher + { + if ($this->dispatcher) { + return $this->dispatcher; + } + + $routeDefinitionCallback = function (FastRouteCollector $r): void { + $basePath = $this->routeCollector->getBasePath(); + + foreach ($this->routeCollector->getRoutes() as $route) { + $r->addRoute($route->getMethods(), $basePath . $route->getPattern(), $route->getIdentifier()); + } + }; + + $cacheFile = $this->routeCollector->getCacheFile(); + if ($cacheFile) { + /** @var FastRouteDispatcher $dispatcher */ + $dispatcher = \FastRoute\cachedDispatcher($routeDefinitionCallback, [ + 'dataGenerator' => GroupCountBased::class, + 'dispatcher' => FastRouteDispatcher::class, + 'routeParser' => new Std(), + 'cacheFile' => $cacheFile, + ]); + } else { + /** @var FastRouteDispatcher $dispatcher */ + $dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback, [ + 'dataGenerator' => GroupCountBased::class, + 'dispatcher' => FastRouteDispatcher::class, + 'routeParser' => new Std(), + ]); + } + + $this->dispatcher = $dispatcher; + return $this->dispatcher; + } + + /** + * {@inheritdoc} + */ + public function dispatch(string $method, string $uri): RoutingResults + { + $dispatcher = $this->createDispatcher(); + $results = $dispatcher->dispatch($method, $uri); + return new RoutingResults($this, $method, $uri, $results[0], $results[1], $results[2]); + } + + /** + * {@inheritdoc} + */ + public function getAllowedMethods(string $uri): array + { + $dispatcher = $this->createDispatcher(); + return $dispatcher->getAllowedMethods($uri); + } +} diff --git a/vendor/slim/slim/Slim/Routing/FastRouteDispatcher.php b/vendor/slim/slim/Slim/Routing/FastRouteDispatcher.php new file mode 100644 index 0000000..797746b --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/FastRouteDispatcher.php @@ -0,0 +1,109 @@ +} + */ + public function dispatch($httpMethod, $uri): array + { + $routingResults = $this->routingResults($httpMethod, $uri); + if ($routingResults[0] === self::FOUND) { + return $routingResults; + } + + // For HEAD requests, attempt fallback to GET + if ($httpMethod === 'HEAD') { + $routingResults = $this->routingResults('GET', $uri); + if ($routingResults[0] === self::FOUND) { + return $routingResults; + } + } + + // If nothing else matches, try fallback routes + $routingResults = $this->routingResults('*', $uri); + if ($routingResults[0] === self::FOUND) { + return $routingResults; + } + + if (!empty($this->getAllowedMethods($uri))) { + return [self::METHOD_NOT_ALLOWED, null, []]; + } + + return [self::NOT_FOUND, null, []]; + } + + /** + * @param string $httpMethod + * @param string $uri + * + * @return array{int, string|null, array} + */ + private function routingResults(string $httpMethod, string $uri): array + { + if (isset($this->staticRouteMap[$httpMethod][$uri])) { + /** @var string $routeIdentifier */ + $routeIdentifier = $this->staticRouteMap[$httpMethod][$uri]; + return [self::FOUND, $routeIdentifier, []]; + } + + if (isset($this->variableRouteData[$httpMethod])) { + /** @var array{0: int, 1?: string, 2?: array} $result */ + $result = $this->dispatchVariableRoute($this->variableRouteData[$httpMethod], $uri); + if ($result[0] === self::FOUND) { + /** @var array{int, string, array} $result */ + return [self::FOUND, $result[1], $result[2]]; + } + } + + return [self::NOT_FOUND, null, []]; + } + + /** + * @param string $uri + * + * @return string[] + */ + public function getAllowedMethods(string $uri): array + { + if (isset($this->allowedMethods[$uri])) { + return $this->allowedMethods[$uri]; + } + + $allowedMethods = []; + foreach ($this->staticRouteMap as $method => $uriMap) { + if (isset($uriMap[$uri])) { + $allowedMethods[$method] = true; + } + } + + foreach ($this->variableRouteData as $method => $routeData) { + $result = $this->dispatchVariableRoute($routeData, $uri); + if ($result[0] === self::FOUND) { + $allowedMethods[$method] = true; + } + } + + return $this->allowedMethods[$uri] = array_keys($allowedMethods); + } +} diff --git a/vendor/slim/slim/Slim/Routing/Route.php b/vendor/slim/slim/Slim/Routing/Route.php new file mode 100644 index 0000000..a2d9d04 --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/Route.php @@ -0,0 +1,365 @@ + + */ + protected array $arguments = []; + + /** + * Route arguments parameters + * + * @var string[] + */ + protected array $savedArguments = []; + + /** + * Container + * @var TContainerInterface $container + */ + protected ?ContainerInterface $container = null; + + /** @var MiddlewareDispatcher $middlewareDispatcher */ + protected MiddlewareDispatcher $middlewareDispatcher; + + /** + * Route callable + * + * @var callable|string + */ + protected $callable; + + protected CallableResolverInterface $callableResolver; + + protected ResponseFactoryInterface $responseFactory; + + /** + * Route pattern + */ + protected string $pattern; + + protected bool $groupMiddlewareAppended = false; + + /** + * @param string[] $methods The route HTTP methods + * @param string $pattern The route pattern + * @param callable|string $callable The route callable + * @param ResponseFactoryInterface $responseFactory + * @param CallableResolverInterface $callableResolver + * @param TContainerInterface $container + * @param InvocationStrategyInterface|null $invocationStrategy + * @param RouteGroupInterface[] $groups The parent route groups + * @param int $identifier The route identifier + */ + public function __construct( + array $methods, + string $pattern, + $callable, + ResponseFactoryInterface $responseFactory, + CallableResolverInterface $callableResolver, + ?ContainerInterface $container = null, + ?InvocationStrategyInterface $invocationStrategy = null, + array $groups = [], + int $identifier = 0 + ) { + $this->methods = $methods; + $this->pattern = $pattern; + $this->callable = $callable; + $this->responseFactory = $responseFactory; + $this->callableResolver = $callableResolver; + $this->container = $container; + $this->invocationStrategy = $invocationStrategy ?? new RequestResponse(); + $this->groups = $groups; + $this->identifier = 'route' . $identifier; + $this->middlewareDispatcher = new MiddlewareDispatcher($this, $callableResolver, $container); + } + + public function getCallableResolver(): CallableResolverInterface + { + return $this->callableResolver; + } + + /** + * {@inheritdoc} + */ + public function getInvocationStrategy(): InvocationStrategyInterface + { + return $this->invocationStrategy; + } + + /** + * {@inheritdoc} + */ + public function setInvocationStrategy(InvocationStrategyInterface $invocationStrategy): RouteInterface + { + $this->invocationStrategy = $invocationStrategy; + return $this; + } + + /** + * {@inheritdoc} + */ + public function getMethods(): array + { + return $this->methods; + } + + /** + * {@inheritdoc} + */ + public function getPattern(): string + { + return $this->pattern; + } + + /** + * {@inheritdoc} + */ + public function setPattern(string $pattern): RouteInterface + { + $this->pattern = $pattern; + return $this; + } + + /** + * {@inheritdoc} + */ + public function getCallable() + { + return $this->callable; + } + + /** + * {@inheritdoc} + */ + public function setCallable($callable): RouteInterface + { + $this->callable = $callable; + return $this; + } + + /** + * {@inheritdoc} + */ + public function getName(): ?string + { + return $this->name; + } + + /** + * {@inheritdoc} + */ + public function setName(string $name): RouteInterface + { + $this->name = $name; + return $this; + } + + /** + * {@inheritdoc} + */ + public function getIdentifier(): string + { + return $this->identifier; + } + + /** + * {@inheritdoc} + */ + public function getArgument(string $name, ?string $default = null): ?string + { + if (array_key_exists($name, $this->arguments)) { + return $this->arguments[$name]; + } + return $default; + } + + /** + * {@inheritdoc} + */ + public function getArguments(): array + { + return $this->arguments; + } + + /** + * {@inheritdoc} + */ + public function setArguments(array $arguments, bool $includeInSavedArguments = true): RouteInterface + { + if ($includeInSavedArguments) { + $this->savedArguments = $arguments; + } + + $this->arguments = $arguments; + return $this; + } + + /** + * @return RouteGroupInterface[] + */ + public function getGroups(): array + { + return $this->groups; + } + + /** + * {@inheritdoc} + */ + public function add($middleware): RouteInterface + { + $this->middlewareDispatcher->add($middleware); + return $this; + } + + /** + * {@inheritdoc} + */ + public function addMiddleware(MiddlewareInterface $middleware): RouteInterface + { + $this->middlewareDispatcher->addMiddleware($middleware); + return $this; + } + + /** + * {@inheritdoc} + */ + public function prepare(array $arguments): RouteInterface + { + $this->arguments = array_replace($this->savedArguments, $arguments); + return $this; + } + + /** + * {@inheritdoc} + */ + public function setArgument(string $name, string $value, bool $includeInSavedArguments = true): RouteInterface + { + if ($includeInSavedArguments) { + $this->savedArguments[$name] = $value; + } + + $this->arguments[$name] = $value; + return $this; + } + + /** + * {@inheritdoc} + */ + public function run(ServerRequestInterface $request): ResponseInterface + { + if (!$this->groupMiddlewareAppended) { + $this->appendGroupMiddlewareToRoute(); + } + + return $this->middlewareDispatcher->handle($request); + } + + /** + * @return void + */ + protected function appendGroupMiddlewareToRoute(): void + { + $inner = $this->middlewareDispatcher; + $this->middlewareDispatcher = new MiddlewareDispatcher($inner, $this->callableResolver, $this->container); + + foreach (array_reverse($this->groups) as $group) { + $group->appendMiddlewareToDispatcher($this->middlewareDispatcher); + } + + $this->groupMiddlewareAppended = true; + } + + /** + * {@inheritdoc} + */ + public function handle(ServerRequestInterface $request): ResponseInterface + { + if ($this->callableResolver instanceof AdvancedCallableResolverInterface) { + $callable = $this->callableResolver->resolveRoute($this->callable); + } else { + $callable = $this->callableResolver->resolve($this->callable); + } + $strategy = $this->invocationStrategy; + + /** @var string[] $strategyImplements */ + $strategyImplements = class_implements($strategy); + + if ( + is_array($callable) + && $callable[0] instanceof RequestHandlerInterface + && !in_array(RequestHandlerInvocationStrategyInterface::class, $strategyImplements) + ) { + $strategy = new RequestHandler(); + } + + $response = $this->responseFactory->createResponse(); + return $strategy($callable, $request, $response, $this->arguments); + } +} diff --git a/vendor/slim/slim/Slim/Routing/RouteCollector.php b/vendor/slim/slim/Slim/Routing/RouteCollector.php new file mode 100644 index 0000000..6f9f0f6 --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/RouteCollector.php @@ -0,0 +1,302 @@ +responseFactory = $responseFactory; + $this->callableResolver = $callableResolver; + $this->container = $container; + $this->defaultInvocationStrategy = $defaultInvocationStrategy ?? new RequestResponse(); + $this->routeParser = $routeParser ?? new RouteParser($this); + + if ($cacheFile) { + $this->setCacheFile($cacheFile); + } + } + + public function getRouteParser(): RouteParserInterface + { + return $this->routeParser; + } + + /** + * Get default route invocation strategy + */ + public function getDefaultInvocationStrategy(): InvocationStrategyInterface + { + return $this->defaultInvocationStrategy; + } + + public function setDefaultInvocationStrategy(InvocationStrategyInterface $strategy): RouteCollectorInterface + { + $this->defaultInvocationStrategy = $strategy; + return $this; + } + + /** + * {@inheritdoc} + */ + public function getCacheFile(): ?string + { + return $this->cacheFile; + } + + /** + * {@inheritdoc} + */ + public function setCacheFile(string $cacheFile): RouteCollectorInterface + { + if (file_exists($cacheFile) && !is_readable($cacheFile)) { + throw new RuntimeException( + sprintf('Route collector cache file `%s` is not readable', $cacheFile) + ); + } + + if (!file_exists($cacheFile) && !is_writable(dirname($cacheFile))) { + throw new RuntimeException( + sprintf('Route collector cache file directory `%s` is not writable', dirname($cacheFile)) + ); + } + + $this->cacheFile = $cacheFile; + return $this; + } + + /** + * {@inheritdoc} + */ + public function getBasePath(): string + { + return $this->basePath; + } + + /** + * Set the base path used in urlFor() + */ + public function setBasePath(string $basePath): RouteCollectorInterface + { + $this->basePath = $basePath; + + return $this; + } + + /** + * {@inheritdoc} + */ + public function getRoutes(): array + { + return $this->routes; + } + + /** + * {@inheritdoc} + */ + public function removeNamedRoute(string $name): RouteCollectorInterface + { + $route = $this->getNamedRoute($name); + + /** @psalm-suppress PossiblyNullArrayOffset */ + unset($this->routesByName[$route->getName()], $this->routes[$route->getIdentifier()]); + return $this; + } + + /** + * {@inheritdoc} + */ + public function getNamedRoute(string $name): RouteInterface + { + if (isset($this->routesByName[$name])) { + $route = $this->routesByName[$name]; + if ($route->getName() === $name) { + return $route; + } + + unset($this->routesByName[$name]); + } + + foreach ($this->routes as $route) { + if ($name === $route->getName()) { + $this->routesByName[$name] = $route; + return $route; + } + } + + throw new RuntimeException('Named route does not exist for name: ' . $name); + } + + /** + * {@inheritdoc} + */ + public function lookupRoute(string $identifier): RouteInterface + { + if (!isset($this->routes[$identifier])) { + throw new RuntimeException('Route not found, looks like your route cache is stale.'); + } + return $this->routes[$identifier]; + } + + /** + * {@inheritdoc} + */ + public function group(string $pattern, $callable): RouteGroupInterface + { + $routeGroup = $this->createGroup($pattern, $callable); + $this->routeGroups[] = $routeGroup; + + $routeGroup->collectRoutes(); + array_pop($this->routeGroups); + + return $routeGroup; + } + + /** + * @param string|callable $callable + */ + protected function createGroup(string $pattern, $callable): RouteGroupInterface + { + $routeCollectorProxy = $this->createProxy($pattern); + return new RouteGroup($pattern, $callable, $this->callableResolver, $routeCollectorProxy); + } + + /** + * @return RouteCollectorProxyInterface + */ + protected function createProxy(string $pattern): RouteCollectorProxyInterface + { + /** @var RouteCollectorProxyInterface */ + return new RouteCollectorProxy( + $this->responseFactory, + $this->callableResolver, + $this->container, + $this, + $pattern + ); + } + + /** + * {@inheritdoc} + */ + public function map(array $methods, string $pattern, $handler): RouteInterface + { + $route = $this->createRoute($methods, $pattern, $handler); + $this->routes[$route->getIdentifier()] = $route; + + $routeName = $route->getName(); + if ($routeName !== null && !isset($this->routesByName[$routeName])) { + $this->routesByName[$routeName] = $route; + } + + $this->routeCounter++; + + return $route; + } + + /** + * @param string[] $methods + * @param callable|string $callable + */ + protected function createRoute(array $methods, string $pattern, $callable): RouteInterface + { + return new Route( + $methods, + $pattern, + $callable, + $this->responseFactory, + $this->callableResolver, + $this->container, + $this->defaultInvocationStrategy, + $this->routeGroups, + $this->routeCounter + ); + } +} diff --git a/vendor/slim/slim/Slim/Routing/RouteCollectorProxy.php b/vendor/slim/slim/Slim/Routing/RouteCollectorProxy.php new file mode 100644 index 0000000..a946d14 --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/RouteCollectorProxy.php @@ -0,0 +1,196 @@ + + */ +class RouteCollectorProxy implements RouteCollectorProxyInterface +{ + protected ResponseFactoryInterface $responseFactory; + + protected CallableResolverInterface $callableResolver; + + /** @var TContainerInterface */ + protected ?ContainerInterface $container = null; + + protected RouteCollectorInterface $routeCollector; + + protected string $groupPattern; + + /** + * @param TContainerInterface $container + */ + public function __construct( + ResponseFactoryInterface $responseFactory, + CallableResolverInterface $callableResolver, + ?ContainerInterface $container = null, + ?RouteCollectorInterface $routeCollector = null, + string $groupPattern = '' + ) { + $this->responseFactory = $responseFactory; + $this->callableResolver = $callableResolver; + $this->container = $container; + $this->routeCollector = $routeCollector ?? new RouteCollector($responseFactory, $callableResolver, $container); + $this->groupPattern = $groupPattern; + } + + /** + * {@inheritdoc} + */ + public function getResponseFactory(): ResponseFactoryInterface + { + return $this->responseFactory; + } + + /** + * {@inheritdoc} + */ + public function getCallableResolver(): CallableResolverInterface + { + return $this->callableResolver; + } + + /** + * {@inheritdoc} + * @return TContainerInterface + */ + public function getContainer(): ?ContainerInterface + { + return $this->container; + } + + /** + * {@inheritdoc} + */ + public function getRouteCollector(): RouteCollectorInterface + { + return $this->routeCollector; + } + + /** + * {@inheritdoc} + */ + public function getBasePath(): string + { + return $this->routeCollector->getBasePath(); + } + + /** + * {@inheritdoc} + */ + public function setBasePath(string $basePath): RouteCollectorProxyInterface + { + $this->routeCollector->setBasePath($basePath); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function get(string $pattern, $callable): RouteInterface + { + return $this->map(['GET'], $pattern, $callable); + } + + /** + * {@inheritdoc} + */ + public function post(string $pattern, $callable): RouteInterface + { + return $this->map(['POST'], $pattern, $callable); + } + + /** + * {@inheritdoc} + */ + public function put(string $pattern, $callable): RouteInterface + { + return $this->map(['PUT'], $pattern, $callable); + } + + /** + * {@inheritdoc} + */ + public function patch(string $pattern, $callable): RouteInterface + { + return $this->map(['PATCH'], $pattern, $callable); + } + + /** + * {@inheritdoc} + */ + public function delete(string $pattern, $callable): RouteInterface + { + return $this->map(['DELETE'], $pattern, $callable); + } + + /** + * {@inheritdoc} + */ + public function options(string $pattern, $callable): RouteInterface + { + return $this->map(['OPTIONS'], $pattern, $callable); + } + + /** + * {@inheritdoc} + */ + public function any(string $pattern, $callable): RouteInterface + { + return $this->map(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], $pattern, $callable); + } + + /** + * {@inheritdoc} + */ + public function map(array $methods, string $pattern, $callable): RouteInterface + { + $pattern = $this->groupPattern . $pattern; + + return $this->routeCollector->map($methods, $pattern, $callable); + } + + /** + * {@inheritdoc} + */ + public function group(string $pattern, $callable): RouteGroupInterface + { + $pattern = $this->groupPattern . $pattern; + + return $this->routeCollector->group($pattern, $callable); + } + + /** + * {@inheritdoc} + */ + public function redirect(string $from, $to, int $status = 302): RouteInterface + { + $responseFactory = $this->responseFactory; + + $handler = function () use ($to, $status, $responseFactory) { + $response = $responseFactory->createResponse($status); + return $response->withHeader('Location', (string) $to); + }; + + return $this->get($from, $handler); + } +} diff --git a/vendor/slim/slim/Slim/Routing/RouteContext.php b/vendor/slim/slim/Slim/Routing/RouteContext.php new file mode 100644 index 0000000..853b0df --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/RouteContext.php @@ -0,0 +1,89 @@ +getAttribute(self::ROUTE); + $routeParser = $serverRequest->getAttribute(self::ROUTE_PARSER); + $routingResults = $serverRequest->getAttribute(self::ROUTING_RESULTS); + $basePath = $serverRequest->getAttribute(self::BASE_PATH); + + if ($routeParser === null || $routingResults === null) { + throw new RuntimeException('Cannot create RouteContext before routing has been completed'); + } + + /** @var RouteInterface|null $route */ + /** @var RouteParserInterface $routeParser */ + /** @var RoutingResults $routingResults */ + /** @var string|null $basePath */ + return new self($route, $routeParser, $routingResults, $basePath); + } + + private ?RouteInterface $route; + + private RouteParserInterface $routeParser; + + private RoutingResults $routingResults; + + private ?string $basePath; + + private function __construct( + ?RouteInterface $route, + RouteParserInterface $routeParser, + RoutingResults $routingResults, + ?string $basePath = null + ) { + $this->route = $route; + $this->routeParser = $routeParser; + $this->routingResults = $routingResults; + $this->basePath = $basePath; + } + + public function getRoute(): ?RouteInterface + { + return $this->route; + } + + public function getRouteParser(): RouteParserInterface + { + return $this->routeParser; + } + + public function getRoutingResults(): RoutingResults + { + return $this->routingResults; + } + + public function getBasePath(): string + { + if ($this->basePath === null) { + throw new RuntimeException('No base path defined.'); + } + return $this->basePath; + } +} diff --git a/vendor/slim/slim/Slim/Routing/RouteGroup.php b/vendor/slim/slim/Slim/Routing/RouteGroup.php new file mode 100644 index 0000000..60d3df3 --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/RouteGroup.php @@ -0,0 +1,109 @@ + + */ + protected RouteCollectorProxyInterface $routeCollectorProxy; + + /** + * @var MiddlewareInterface[]|string[]|callable[] + */ + protected array $middleware = []; + + protected string $pattern; + + /** + * @param callable|string $callable + * @param RouteCollectorProxyInterface<\Psr\Container\ContainerInterface|null> $routeCollectorProxy + */ + public function __construct( + string $pattern, + $callable, + CallableResolverInterface $callableResolver, + RouteCollectorProxyInterface $routeCollectorProxy + ) { + $this->pattern = $pattern; + $this->callable = $callable; + $this->callableResolver = $callableResolver; + $this->routeCollectorProxy = $routeCollectorProxy; + } + + /** + * {@inheritdoc} + */ + public function collectRoutes(): RouteGroupInterface + { + if ($this->callableResolver instanceof AdvancedCallableResolverInterface) { + $callable = $this->callableResolver->resolveRoute($this->callable); + } else { + $callable = $this->callableResolver->resolve($this->callable); + } + $callable($this->routeCollectorProxy); + return $this; + } + + /** + * {@inheritdoc} + */ + public function add($middleware): RouteGroupInterface + { + $this->middleware[] = $middleware; + return $this; + } + + /** + * {@inheritdoc} + */ + public function addMiddleware(MiddlewareInterface $middleware): RouteGroupInterface + { + $this->middleware[] = $middleware; + return $this; + } + + /** + * {@inheritdoc} + * @param MiddlewareDispatcher<\Psr\Container\ContainerInterface|null> $dispatcher + */ + public function appendMiddlewareToDispatcher(MiddlewareDispatcher $dispatcher): RouteGroupInterface + { + foreach ($this->middleware as $middleware) { + $dispatcher->add($middleware); + } + + return $this; + } + + /** + * {@inheritdoc} + */ + public function getPattern(): string + { + return $this->pattern; + } +} diff --git a/vendor/slim/slim/Slim/Routing/RouteParser.php b/vendor/slim/slim/Slim/Routing/RouteParser.php new file mode 100644 index 0000000..afb533c --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/RouteParser.php @@ -0,0 +1,127 @@ +routeCollector = $routeCollector; + $this->routeParser = new Std(); + } + + /** + * {@inheritdoc} + */ + public function relativeUrlFor(string $routeName, array $data = [], array $queryParams = []): string + { + $route = $this->routeCollector->getNamedRoute($routeName); + $pattern = $route->getPattern(); + + $segments = []; + $segmentName = ''; + + /* + * $routes is an associative array of expressions representing a route as multiple segments + * There is an expression for each optional parameter plus one without the optional parameters + * The most specific is last, hence why we reverse the array before iterating over it + */ + $expressions = array_reverse($this->routeParser->parse($pattern)); + foreach ($expressions as $expression) { + foreach ($expression as $segment) { + /* + * Each $segment is either a string or an array of strings + * containing optional parameters of an expression + */ + if (is_string($segment)) { + $segments[] = $segment; + continue; + } + + /** @var string[] $segment */ + /* + * If we don't have a data element for this segment in the provided $data + * we cancel testing to move onto the next expression with a less specific item + */ + if (!array_key_exists($segment[0], $data)) { + $segments = []; + $segmentName = $segment[0]; + break; + } + + $segments[] = $data[$segment[0]]; + } + + /* + * If we get to this logic block we have found all the parameters + * for the provided $data which means we don't need to continue testing + * less specific expressions + */ + if (!empty($segments)) { + break; + } + } + + if (empty($segments)) { + throw new InvalidArgumentException('Missing data for URL segment: ' . $segmentName); + } + + $url = implode('', $segments); + if ($queryParams) { + $url .= '?' . http_build_query($queryParams); + } + + return $url; + } + + /** + * {@inheritdoc} + */ + public function urlFor(string $routeName, array $data = [], array $queryParams = []): string + { + $basePath = $this->routeCollector->getBasePath(); + $url = $this->relativeUrlFor($routeName, $data, $queryParams); + + if ($basePath) { + $url = $basePath . $url; + } + + return $url; + } + + /** + * {@inheritdoc} + */ + public function fullUrlFor(UriInterface $uri, string $routeName, array $data = [], array $queryParams = []): string + { + $path = $this->urlFor($routeName, $data, $queryParams); + $scheme = $uri->getScheme(); + $authority = $uri->getAuthority(); + $protocol = ($scheme ? $scheme . ':' : '') . ($authority ? '//' . $authority : ''); + return $protocol . $path; + } +} diff --git a/vendor/slim/slim/Slim/Routing/RouteResolver.php b/vendor/slim/slim/Slim/Routing/RouteResolver.php new file mode 100644 index 0000000..d4f4eaf --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/RouteResolver.php @@ -0,0 +1,56 @@ +routeCollector = $routeCollector; + $this->dispatcher = $dispatcher ?? new Dispatcher($routeCollector); + } + + /** + * @param string $uri Should be $request->getUri()->getPath() + */ + public function computeRoutingResults(string $uri, string $method): RoutingResults + { + $uri = rawurldecode($uri); + if ($uri === '' || $uri[0] !== '/') { + $uri = '/' . $uri; + } + return $this->dispatcher->dispatch($method, $uri); + } + + /** + * @throws RuntimeException + */ + public function resolveRoute(string $identifier): RouteInterface + { + return $this->routeCollector->lookupRoute($identifier); + } +} diff --git a/vendor/slim/slim/Slim/Routing/RouteRunner.php b/vendor/slim/slim/Slim/Routing/RouteRunner.php new file mode 100644 index 0000000..3fb5413 --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/RouteRunner.php @@ -0,0 +1,76 @@ + + */ + private ?RouteCollectorProxyInterface $routeCollectorProxy; + + /** + * @param RouteCollectorProxyInterface<\Psr\Container\ContainerInterface|null> $routeCollectorProxy + */ + public function __construct( + RouteResolverInterface $routeResolver, + RouteParserInterface $routeParser, + ?RouteCollectorProxyInterface $routeCollectorProxy = null + ) { + $this->routeResolver = $routeResolver; + $this->routeParser = $routeParser; + $this->routeCollectorProxy = $routeCollectorProxy; + } + + /** + * This request handler is instantiated automatically in App::__construct() + * It is at the very tip of the middleware queue meaning it will be executed + * last and it detects whether or not routing has been performed in the user + * defined middleware stack. In the event that the user did not perform routing + * it is done here + * + * @throws HttpNotFoundException + * @throws HttpMethodNotAllowedException + */ + public function handle(ServerRequestInterface $request): ResponseInterface + { + // If routing hasn't been done, then do it now so we can dispatch + if ($request->getAttribute(RouteContext::ROUTING_RESULTS) === null) { + $routingMiddleware = new RoutingMiddleware($this->routeResolver, $this->routeParser); + $request = $routingMiddleware->performRouting($request); + } + + if ($this->routeCollectorProxy !== null) { + $request = $request->withAttribute( + RouteContext::BASE_PATH, + $this->routeCollectorProxy->getBasePath() + ); + } + + /** @var Route<\Psr\Container\ContainerInterface|null> $route */ + $route = $request->getAttribute(RouteContext::ROUTE); + return $route->run($request); + } +} diff --git a/vendor/slim/slim/Slim/Routing/RoutingResults.php b/vendor/slim/slim/Slim/Routing/RoutingResults.php new file mode 100644 index 0000000..4fd8973 --- /dev/null +++ b/vendor/slim/slim/Slim/Routing/RoutingResults.php @@ -0,0 +1,113 @@ + + */ + protected array $routeArguments; + + /** + * @param array $routeArguments + */ + public function __construct( + DispatcherInterface $dispatcher, + string $method, + string $uri, + int $routeStatus, + ?string $routeIdentifier = null, + array $routeArguments = [] + ) { + $this->dispatcher = $dispatcher; + $this->method = $method; + $this->uri = $uri; + $this->routeStatus = $routeStatus; + $this->routeIdentifier = $routeIdentifier; + $this->routeArguments = $routeArguments; + } + + public function getDispatcher(): DispatcherInterface + { + return $this->dispatcher; + } + + public function getMethod(): string + { + return $this->method; + } + + public function getUri(): string + { + return $this->uri; + } + + public function getRouteStatus(): int + { + return $this->routeStatus; + } + + public function getRouteIdentifier(): ?string + { + return $this->routeIdentifier; + } + + /** + * @return array + */ + public function getRouteArguments(bool $urlDecode = true): array + { + if (!$urlDecode) { + return $this->routeArguments; + } + + $routeArguments = []; + foreach ($this->routeArguments as $key => $value) { + $routeArguments[$key] = rawurldecode($value); + } + + return $routeArguments; + } + + /** + * @return string[] + */ + public function getAllowedMethods(): array + { + return $this->dispatcher->getAllowedMethods($this->uri); + } +} diff --git a/vendor/slim/slim/composer.json b/vendor/slim/slim/composer.json new file mode 100644 index 0000000..fdbc786 --- /dev/null +++ b/vendor/slim/slim/composer.json @@ -0,0 +1,105 @@ +{ + "name": "slim/slim", + "type": "library", + "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", + "keywords": ["framework","micro","api","router"], + "homepage": "https://www.slimframework.com", + "license": "MIT", + "authors": [ + { + "name": "Josh Lockhart", + "email": "hello@joshlockhart.com", + "homepage": "https://joshlockhart.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" + }, + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, + { + "name": "Pierre Berube", + "email": "pierre@lgse.com", + "homepage": "http://www.lgse.com" + }, + { + "name": "Gabriel Manricks", + "email": "gmanricks@me.com", + "homepage": "http://gabrielmanricks.com" + } + ], + "support": { + "docs": "https://www.slimframework.com/docs/v4/", + "forum": "https://discourse.slimframework.com/", + "irc": "irc://irc.freenode.net:6667/slimphp", + "issues": "https://github.com/slimphp/Slim/issues", + "rss": "https://www.slimframework.com/blog/feed.rss", + "slack": "https://slimphp.slack.com/", + "source": "https://github.com/slimphp/Slim", + "wiki": "https://github.com/slimphp/Slim/wiki" + }, + "require": { + "php": "^7.4 || ^8.0", + "ext-json": "*", + "nikic/fast-route": "^1.3", + "psr/container": "^1.0 || ^2.0", + "psr/http-factory": "^1.1", + "psr/http-message": "^1.1 || ^2.0", + "psr/http-server-handler": "^1.0", + "psr/http-server-middleware": "^1.0", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "require-dev": { + "ext-simplexml": "*", + "adriansuter/php-autoload-override": "^1.4", + "guzzlehttp/psr7": "^2.6", + "httpsoft/http-message": "^1.1", + "httpsoft/http-server-request": "^1.1", + "laminas/laminas-diactoros": "^2.17 || ^3", + "nyholm/psr7": "^1.8", + "nyholm/psr7-server": "^1.1", + "phpspec/prophecy": "^1.19", + "phpspec/prophecy-phpunit": "^2.1", + "phpstan/phpstan": "^1.11", + "phpunit/phpunit": "^9.6", + "slim/http": "^1.3", + "slim/psr7": "^1.6", + "squizlabs/php_codesniffer": "^3.10", + "vimeo/psalm": "^5.24" + }, + "autoload": { + "psr-4": { + "Slim\\": "Slim" + } + }, + "autoload-dev": { + "psr-4": { + "Slim\\Tests\\": "tests" + } + }, + "scripts": { + "test": [ + "@phpunit", + "@phpcs", + "@phpstan", + "@psalm" + ], + "phpunit": "phpunit", + "phpcs": "phpcs", + "phpstan": "phpstan --memory-limit=-1", + "psalm": "psalm --no-cache" + }, + "suggest": { + "ext-simplexml": "Needed to support XML format in BodyParsingMiddleware", + "ext-xml": "Needed to support XML format in BodyParsingMiddleware", + "slim/psr7": "Slim PSR-7 implementation. See https://www.slimframework.com/docs/v4/start/installation.html for more information.", + "php-di/php-di": "PHP-DI is the recommended container library to be used with Slim" + }, + "config": { + "sort-packages": true + } +} diff --git a/vendor/slim/slim/psalm.xml b/vendor/slim/slim/psalm.xml new file mode 100644 index 0000000..af258ff --- /dev/null +++ b/vendor/slim/slim/psalm.xml @@ -0,0 +1,17 @@ + + + + + + + + + diff --git a/vendor/symfony/polyfill-php80/LICENSE b/vendor/symfony/polyfill-php80/LICENSE new file mode 100644 index 0000000..0ed3a24 --- /dev/null +++ b/vendor/symfony/polyfill-php80/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020-present Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/symfony/polyfill-php80/Php80.php b/vendor/symfony/polyfill-php80/Php80.php new file mode 100644 index 0000000..362dd1a --- /dev/null +++ b/vendor/symfony/polyfill-php80/Php80.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php80; + +/** + * @author Ion Bazan + * @author Nico Oelgart + * @author Nicolas Grekas + * + * @internal + */ +final class Php80 +{ + public static function fdiv(float $dividend, float $divisor): float + { + return @($dividend / $divisor); + } + + public static function get_debug_type($value): string + { + switch (true) { + case null === $value: return 'null'; + case \is_bool($value): return 'bool'; + case \is_string($value): return 'string'; + case \is_array($value): return 'array'; + case \is_int($value): return 'int'; + case \is_float($value): return 'float'; + case \is_object($value): break; + case $value instanceof \__PHP_Incomplete_Class: return '__PHP_Incomplete_Class'; + default: + if (null === $type = @get_resource_type($value)) { + return 'unknown'; + } + + if ('Unknown' === $type) { + $type = 'closed'; + } + + return "resource ($type)"; + } + + $class = \get_class($value); + + if (false === strpos($class, '@')) { + return $class; + } + + return (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous'; + } + + public static function get_resource_id($res): int + { + if (!\is_resource($res) && null === @get_resource_type($res)) { + throw new \TypeError(sprintf('Argument 1 passed to get_resource_id() must be of the type resource, %s given', get_debug_type($res))); + } + + return (int) $res; + } + + public static function preg_last_error_msg(): string + { + switch (preg_last_error()) { + case \PREG_INTERNAL_ERROR: + return 'Internal error'; + case \PREG_BAD_UTF8_ERROR: + return 'Malformed UTF-8 characters, possibly incorrectly encoded'; + case \PREG_BAD_UTF8_OFFSET_ERROR: + return 'The offset did not correspond to the beginning of a valid UTF-8 code point'; + case \PREG_BACKTRACK_LIMIT_ERROR: + return 'Backtrack limit exhausted'; + case \PREG_RECURSION_LIMIT_ERROR: + return 'Recursion limit exhausted'; + case \PREG_JIT_STACKLIMIT_ERROR: + return 'JIT stack limit exhausted'; + case \PREG_NO_ERROR: + return 'No error'; + default: + return 'Unknown error'; + } + } + + public static function str_contains(string $haystack, string $needle): bool + { + return '' === $needle || false !== strpos($haystack, $needle); + } + + public static function str_starts_with(string $haystack, string $needle): bool + { + return 0 === strncmp($haystack, $needle, \strlen($needle)); + } + + public static function str_ends_with(string $haystack, string $needle): bool + { + if ('' === $needle || $needle === $haystack) { + return true; + } + + if ('' === $haystack) { + return false; + } + + $needleLength = \strlen($needle); + + return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength); + } +} diff --git a/vendor/symfony/polyfill-php80/PhpToken.php b/vendor/symfony/polyfill-php80/PhpToken.php new file mode 100644 index 0000000..fe6e691 --- /dev/null +++ b/vendor/symfony/polyfill-php80/PhpToken.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php80; + +/** + * @author Fedonyuk Anton + * + * @internal + */ +class PhpToken implements \Stringable +{ + /** + * @var int + */ + public $id; + + /** + * @var string + */ + public $text; + + /** + * @var int + */ + public $line; + + /** + * @var int + */ + public $pos; + + public function __construct(int $id, string $text, int $line = -1, int $position = -1) + { + $this->id = $id; + $this->text = $text; + $this->line = $line; + $this->pos = $position; + } + + public function getTokenName(): ?string + { + if ('UNKNOWN' === $name = token_name($this->id)) { + $name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text; + } + + return $name; + } + + /** + * @param int|string|array $kind + */ + public function is($kind): bool + { + foreach ((array) $kind as $value) { + if (\in_array($value, [$this->id, $this->text], true)) { + return true; + } + } + + return false; + } + + public function isIgnorable(): bool + { + return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true); + } + + public function __toString(): string + { + return (string) $this->text; + } + + /** + * @return static[] + */ + public static function tokenize(string $code, int $flags = 0): array + { + $line = 1; + $position = 0; + $tokens = token_get_all($code, $flags); + foreach ($tokens as $index => $token) { + if (\is_string($token)) { + $id = \ord($token); + $text = $token; + } else { + [$id, $text, $line] = $token; + } + $tokens[$index] = new static($id, $text, $line, $position); + $position += \strlen($text); + } + + return $tokens; + } +} diff --git a/vendor/symfony/polyfill-php80/README.md b/vendor/symfony/polyfill-php80/README.md new file mode 100644 index 0000000..3816c55 --- /dev/null +++ b/vendor/symfony/polyfill-php80/README.md @@ -0,0 +1,25 @@ +Symfony Polyfill / Php80 +======================== + +This component provides features added to PHP 8.0 core: + +- [`Stringable`](https://php.net/stringable) interface +- [`fdiv`](https://php.net/fdiv) +- [`ValueError`](https://php.net/valueerror) class +- [`UnhandledMatchError`](https://php.net/unhandledmatcherror) class +- `FILTER_VALIDATE_BOOL` constant +- [`get_debug_type`](https://php.net/get_debug_type) +- [`PhpToken`](https://php.net/phptoken) class +- [`preg_last_error_msg`](https://php.net/preg_last_error_msg) +- [`str_contains`](https://php.net/str_contains) +- [`str_starts_with`](https://php.net/str_starts_with) +- [`str_ends_with`](https://php.net/str_ends_with) +- [`get_resource_id`](https://php.net/get_resource_id) + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php b/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php new file mode 100644 index 0000000..2b95542 --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#[Attribute(Attribute::TARGET_CLASS)] +final class Attribute +{ + public const TARGET_CLASS = 1; + public const TARGET_FUNCTION = 2; + public const TARGET_METHOD = 4; + public const TARGET_PROPERTY = 8; + public const TARGET_CLASS_CONSTANT = 16; + public const TARGET_PARAMETER = 32; + public const TARGET_ALL = 63; + public const IS_REPEATABLE = 64; + + /** @var int */ + public $flags; + + public function __construct(int $flags = self::TARGET_ALL) + { + $this->flags = $flags; + } +} diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php b/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php new file mode 100644 index 0000000..bd1212f --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000 && extension_loaded('tokenizer')) { + class PhpToken extends Symfony\Polyfill\Php80\PhpToken + { + } +} diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php b/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php new file mode 100644 index 0000000..7c62d75 --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + interface Stringable + { + /** + * @return string + */ + public function __toString(); + } +} diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php b/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php new file mode 100644 index 0000000..01c6c6c --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + class UnhandledMatchError extends Error + { + } +} diff --git a/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php b/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php new file mode 100644 index 0000000..783dbc2 --- /dev/null +++ b/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000) { + class ValueError extends Error + { + } +} diff --git a/vendor/symfony/polyfill-php80/bootstrap.php b/vendor/symfony/polyfill-php80/bootstrap.php new file mode 100644 index 0000000..e5f7dbc --- /dev/null +++ b/vendor/symfony/polyfill-php80/bootstrap.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Php80 as p; + +if (\PHP_VERSION_ID >= 80000) { + return; +} + +if (!defined('FILTER_VALIDATE_BOOL') && defined('FILTER_VALIDATE_BOOLEAN')) { + define('FILTER_VALIDATE_BOOL', \FILTER_VALIDATE_BOOLEAN); +} + +if (!function_exists('fdiv')) { + function fdiv(float $num1, float $num2): float { return p\Php80::fdiv($num1, $num2); } +} +if (!function_exists('preg_last_error_msg')) { + function preg_last_error_msg(): string { return p\Php80::preg_last_error_msg(); } +} +if (!function_exists('str_contains')) { + function str_contains(?string $haystack, ?string $needle): bool { return p\Php80::str_contains($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('str_starts_with')) { + function str_starts_with(?string $haystack, ?string $needle): bool { return p\Php80::str_starts_with($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('str_ends_with')) { + function str_ends_with(?string $haystack, ?string $needle): bool { return p\Php80::str_ends_with($haystack ?? '', $needle ?? ''); } +} +if (!function_exists('get_debug_type')) { + function get_debug_type($value): string { return p\Php80::get_debug_type($value); } +} +if (!function_exists('get_resource_id')) { + function get_resource_id($resource): int { return p\Php80::get_resource_id($resource); } +} diff --git a/vendor/symfony/polyfill-php80/composer.json b/vendor/symfony/polyfill-php80/composer.json new file mode 100644 index 0000000..a503b03 --- /dev/null +++ b/vendor/symfony/polyfill-php80/composer.json @@ -0,0 +1,37 @@ +{ + "name": "symfony/polyfill-php80", + "type": "library", + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "keywords": ["polyfill", "shim", "compatibility", "portable"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.2" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Php80\\": "" }, + "files": [ "bootstrap.php" ], + "classmap": [ "Resources/stubs" ] + }, + "minimum-stability": "dev", + "extra": { + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +}