function advancedcontentfilter_init()
{
if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] == 'api') {
- $slim = new \Slim\App();
+ $slim = \Slim\Factory\AppFactory::create();
require __DIR__ . '/src/middlewares.php';
* API
*/
-function advancedcontentfilter_get_rules()
+function advancedcontentfilter_get_rules(ServerRequestInterface $request, ResponseInterface $response)
{
if (!DI::userSession()->getLocalUserId()) {
throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
$rules = DBA::toArray(DBA::select('advancedcontentfilter_rules', [], ['uid' => DI::userSession()->getLocalUserId()]));
- return json_encode($rules);
+ $response->getBody()->write(json_encode($rules));
+ return $response->withHeader('Content-Type', 'application/json');
}
function advancedcontentfilter_get_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
$rule = DBA::selectFirst('advancedcontentfilter_rules', [], ['id' => $args['id'], 'uid' => DI::userSession()->getLocalUserId()]);
- return json_encode($rule);
+ $response->getBody()->write(json_encode($rule));
+ return $response->withHeader('Content-Type', 'application/json');
}
-function advancedcontentfilter_post_rules(ServerRequestInterface $request)
+function advancedcontentfilter_post_rules(ServerRequestInterface $request, ResponseInterface $response)
{
if (!DI::userSession()->getLocalUserId()) {
throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
DI::cache()->delete('rules_' . DI::userSession()->getLocalUserId());
- return json_encode(['message' => DI::l10n()->t('Rule successfully added'), 'rule' => $rule]);
+ $response->getBody()->write(json_encode(['message' => DI::l10n()->t('Rule successfully added'), 'rule' => $rule]));
+ return $response->withHeader('Content-Type', 'application/json');
}
function advancedcontentfilter_put_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
DI::cache()->delete('rules_' . DI::userSession()->getLocalUserId());
- return json_encode(['message' => DI::l10n()->t('Rule successfully updated')]);
+ $response->getBody()->write(json_encode(['message' => DI::l10n()->t('Rule successfully updated')]));
+ return $response->withHeader('Content-Type', 'application/json');
}
function advancedcontentfilter_delete_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
DI::cache()->delete('rules_' . DI::userSession()->getLocalUserId());
- return json_encode(['message' => DI::l10n()->t('Rule successfully deleted')]);
+ $response->getBody()->write(json_encode(['message' => DI::l10n()->t('Rule successfully deleted')]));
+ return $response->withHeader('Content-Type', 'application/json');
}
function advancedcontentfilter_get_variables_guid(ServerRequestInterface $request, ResponseInterface $response, $args)
$return = advancedcontentfilter_get_filter_fields(advancedcontentfilter_prepare_item_row($item_row));
- return json_encode(['variables' => str_replace('\\\'', '\'', var_export($return, true))]);
+ $response->getBody()->write(json_encode(['variables' => str_replace('\\\'', '\'', var_export($return, true))]));
+ return $response->withHeader('Content-Type', 'application/json');
}
/**
}
],
"require": {
- "php": ">=5.6.0",
- "slim/slim": "^3.1",
+ "slim/slim": "^4",
"symfony/expression-language": "^3.4"
},
"license": "3-clause BSD license",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "d0e3662dd9d910ffe4f71d325bc39319",
+ "content-hash": "3e87f0369e4799fc35d98f399c67f1e9",
"packages": [
- {
- "name": "container-interop/container-interop",
- "version": "1.2.0",
- "source": {
- "type": "git",
- "url": "https://github.com/container-interop/container-interop.git",
- "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/container-interop/container-interop/zipball/79cbf1341c22ec75643d841642dd5d6acd83bdb8",
- "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8",
- "shasum": ""
- },
- "require": {
- "psr/container": "^1.0"
- },
- "type": "library",
- "autoload": {
- "psr-4": {
- "Interop\\Container\\": "src/Interop/Container/"
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "description": "Promoting the interoperability of container objects (DIC, SL, etc.)",
- "homepage": "https://github.com/container-interop/container-interop",
- "abandoned": "psr/container",
- "time": "2017-02-14T19:40:03+00:00"
- },
{
"name": "nikic/fast-route",
"version": "v1.3.0",
"time": "2018-02-13T20:26:39+00:00"
},
{
- "name": "pimple/pimple",
- "version": "v3.2.3",
+ "name": "psr/cache",
+ "version": "1.0.1",
"source": {
"type": "git",
- "url": "https://github.com/silexphp/Pimple.git",
- "reference": "9e403941ef9d65d20cba7d54e29fe906db42cf32"
+ "url": "https://github.com/php-fig/cache.git",
+ "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/silexphp/Pimple/zipball/9e403941ef9d65d20cba7d54e29fe906db42cf32",
- "reference": "9e403941ef9d65d20cba7d54e29fe906db42cf32",
+ "url": "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8",
+ "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8",
"shasum": ""
},
"require": {
- "php": ">=5.3.0",
- "psr/container": "^1.0"
- },
- "require-dev": {
- "symfony/phpunit-bridge": "^3.2"
+ "php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "3.2.x-dev"
+ "dev-master": "1.0.x-dev"
}
},
"autoload": {
- "psr-0": {
- "Pimple": "src/"
+ "psr-4": {
+ "Psr\\Cache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
],
"authors": [
{
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com"
+ "name": "PHP-FIG",
+ "homepage": "http://www.php-fig.org/"
}
],
- "description": "Pimple, a simple Dependency Injection Container",
- "homepage": "http://pimple.sensiolabs.org",
+ "description": "Common interface for caching libraries",
"keywords": [
- "container",
- "dependency injection"
+ "cache",
+ "psr",
+ "psr-6"
],
- "time": "2018-01-21T07:42:36+00:00"
+ "time": "2016-08-06T20:24:11+00:00"
},
{
- "name": "psr/cache",
- "version": "1.0.1",
+ "name": "psr/container",
+ "version": "2.0.2",
"source": {
"type": "git",
- "url": "https://github.com/php-fig/cache.git",
- "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8"
+ "url": "https://github.com/php-fig/container.git",
+ "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8",
- "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8",
+ "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963",
+ "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963",
"shasum": ""
},
"require": {
- "php": ">=5.3.0"
+ "php": ">=7.4.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-master": "2.0.x-dev"
}
},
"autoload": {
"psr-4": {
- "Psr\\Cache\\": "src/"
+ "Psr\\Container\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"authors": [
{
"name": "PHP-FIG",
- "homepage": "http://www.php-fig.org/"
+ "homepage": "https://www.php-fig.org/"
}
],
- "description": "Common interface for caching libraries",
+ "description": "Common Container Interface (PHP FIG PSR-11)",
+ "homepage": "https://github.com/php-fig/container",
"keywords": [
- "cache",
- "psr",
- "psr-6"
+ "PSR-11",
+ "container",
+ "container-interface",
+ "container-interop",
+ "psr"
],
- "time": "2016-08-06T20:24:11+00:00"
+ "time": "2021-11-05T16:47:00+00:00"
},
{
- "name": "psr/container",
- "version": "1.0.0",
+ "name": "psr/http-factory",
+ "version": "1.0.2",
"source": {
"type": "git",
- "url": "https://github.com/php-fig/container.git",
- "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f"
+ "url": "https://github.com/php-fig/http-factory.git",
+ "reference": "e616d01114759c4c489f93b099585439f795fe35"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f",
- "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f",
+ "url": "https://api.github.com/repos/php-fig/http-factory/zipball/e616d01114759c4c489f93b099585439f795fe35",
+ "reference": "e616d01114759c4c489f93b099585439f795fe35",
"shasum": ""
},
"require": {
- "php": ">=5.3.0"
+ "php": ">=7.0.0",
+ "psr/http-message": "^1.0 || ^2.0"
},
"type": "library",
"extra": {
},
"autoload": {
"psr-4": {
- "Psr\\Container\\": "src/"
+ "Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"authors": [
{
"name": "PHP-FIG",
- "homepage": "http://www.php-fig.org/"
+ "homepage": "https://www.php-fig.org/"
}
],
- "description": "Common Container Interface (PHP FIG PSR-11)",
- "homepage": "https://github.com/php-fig/container",
+ "description": "Common interfaces for PSR-7 HTTP message factories",
"keywords": [
- "PSR-11",
- "container",
- "container-interface",
- "container-interop",
- "psr"
+ "factory",
+ "http",
+ "message",
+ "psr",
+ "psr-17",
+ "psr-7",
+ "request",
+ "response"
],
- "time": "2017-02-14T16:28:37+00:00"
+ "time": "2023-04-10T20:10:41+00:00"
},
{
"name": "psr/http-message",
- "version": "1.0.1",
+ "version": "1.1",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
- "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
+ "reference": "cb6ce4845ce34a8ad9e68117c10ee90a29919eba"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363",
- "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
+ "url": "https://api.github.com/repos/php-fig/http-message/zipball/cb6ce4845ce34a8ad9e68117c10ee90a29919eba",
+ "reference": "cb6ce4845ce34a8ad9e68117c10ee90a29919eba",
"shasum": ""
},
"require": {
- "php": ">=5.3.0"
+ "php": "^7.2 || ^8.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-master": "1.1.x-dev"
}
},
"autoload": {
"request",
"response"
],
- "time": "2016-08-06T14:39:51+00:00"
+ "time": "2023-04-04T09:50:52+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"
+ ],
+ "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"
+ ],
+ "time": "2023-04-11T06:14:47+00:00"
},
{
"name": "psr/log",
- "version": "1.1.2",
+ "version": "1.1.4",
"source": {
"type": "git",
"url": "https://github.com/php-fig/log.git",
- "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801"
+ "reference": "d49695b909c3b7628b6289db5479a1c204601f11"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/log/zipball/446d54b4cb6bf489fc9d75f55843658e6f25d801",
- "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801",
+ "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11",
+ "reference": "d49695b909c3b7628b6289db5479a1c204601f11",
"shasum": ""
},
"require": {
"authors": [
{
"name": "PHP-FIG",
- "homepage": "http://www.php-fig.org/"
+ "homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for logging libraries",
"psr",
"psr-3"
],
- "time": "2019-11-01T11:05:21+00:00"
+ "time": "2021-05-03T11:20:27+00:00"
},
{
"name": "psr/simple-cache",
},
{
"name": "slim/slim",
- "version": "3.9.2",
+ "version": "4.12.0",
"source": {
"type": "git",
"url": "https://github.com/slimphp/Slim.git",
- "reference": "4086d0106cf5a7135c69fce4161fe355a8feb118"
+ "reference": "e9e99c2b24398b967841c6c4c3048622cc7e2b18"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/slimphp/Slim/zipball/4086d0106cf5a7135c69fce4161fe355a8feb118",
- "reference": "4086d0106cf5a7135c69fce4161fe355a8feb118",
+ "url": "https://api.github.com/repos/slimphp/Slim/zipball/e9e99c2b24398b967841c6c4c3048622cc7e2b18",
+ "reference": "e9e99c2b24398b967841c6c4c3048622cc7e2b18",
"shasum": ""
},
"require": {
- "container-interop/container-interop": "^1.2",
- "nikic/fast-route": "^1.0",
- "php": ">=5.5.0",
- "pimple/pimple": "^3.0",
- "psr/container": "^1.0",
- "psr/http-message": "^1.0"
- },
- "provide": {
- "psr/http-message-implementation": "1.0"
+ "ext-json": "*",
+ "nikic/fast-route": "^1.3",
+ "php": "^7.4 || ^8.0",
+ "psr/container": "^1.0 || ^2.0",
+ "psr/http-factory": "^1.0",
+ "psr/http-message": "^1.1",
+ "psr/http-server-handler": "^1.0",
+ "psr/http-server-middleware": "^1.0",
+ "psr/log": "^1.1 || ^2.0 || ^3.0"
},
"require-dev": {
- "phpunit/phpunit": "^4.0",
- "squizlabs/php_codesniffer": "^2.5"
+ "adriansuter/php-autoload-override": "^1.4",
+ "ext-simplexml": "*",
+ "guzzlehttp/psr7": "^2.5",
+ "httpsoft/http-message": "^1.1",
+ "httpsoft/http-server-request": "^1.1",
+ "laminas/laminas-diactoros": "^2.17",
+ "nyholm/psr7": "^1.8",
+ "nyholm/psr7-server": "^1.0",
+ "phpspec/prophecy": "^1.17",
+ "phpspec/prophecy-phpunit": "^2.0",
+ "phpstan/phpstan": "^1.10",
+ "phpunit/phpunit": "^9.6",
+ "slim/http": "^1.3",
+ "slim/psr7": "^1.6",
+ "squizlabs/php_codesniffer": "^3.7"
+ },
+ "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": {
"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": "Josh Lockhart",
- "email": "hello@joshlockhart.com",
- "homepage": "https://joshlockhart.com"
+ "name": "Pierre Berube",
+ "email": "pierre@lgse.com",
+ "homepage": "http://www.lgse.com"
},
{
"name": "Gabriel Manricks",
"email": "gmanricks@me.com",
"homepage": "http://gabrielmanricks.com"
- },
- {
- "name": "Andrew Smith",
- "email": "a.smith@silentworks.co.uk",
- "homepage": "http://silentworks.co.uk"
}
],
"description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs",
- "homepage": "https://slimframework.com",
+ "homepage": "https://www.slimframework.com",
"keywords": [
"api",
"framework",
"micro",
"router"
],
- "time": "2017-11-26T19:13:09+00:00"
+ "funding": [
+ {
+ "url": "https://opencollective.com/slimphp",
+ "type": "open_collective"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/slim/slim",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2023-07-23T04:54:29+00:00"
},
{
"name": "symfony/cache",
- "version": "v3.4.36",
+ "version": "v3.4.47",
"source": {
"type": "git",
"url": "https://github.com/symfony/cache.git",
- "reference": "3d9f46a6960fd5cd7f030f86adc5b4b63bcfa4e3"
+ "reference": "a7a14c4832760bd1fbd31be2859ffedc9b6ff813"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/cache/zipball/3d9f46a6960fd5cd7f030f86adc5b4b63bcfa4e3",
- "reference": "3d9f46a6960fd5cd7f030f86adc5b4b63bcfa4e3",
+ "url": "https://api.github.com/repos/symfony/cache/zipball/a7a14c4832760bd1fbd31be2859ffedc9b6ff813",
+ "reference": "a7a14c4832760bd1fbd31be2859ffedc9b6ff813",
"shasum": ""
},
"require": {
},
"require-dev": {
"cache/integration-tests": "dev-master",
- "doctrine/cache": "~1.6",
- "doctrine/dbal": "~2.4",
- "predis/predis": "~1.0"
+ "doctrine/cache": "^1.6",
+ "doctrine/dbal": "^2.4|^3.0",
+ "predis/predis": "^1.0"
},
"type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "3.4-dev"
- }
- },
"autoload": {
"psr-4": {
"Symfony\\Component\\Cache\\": ""
"caching",
"psr6"
],
- "time": "2019-12-01T10:45:41+00:00"
+ "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": "2020-10-24T10:57:07+00:00"
},
{
"name": "symfony/expression-language",
- "version": "v3.4.8",
+ "version": "v3.4.47",
"source": {
"type": "git",
"url": "https://github.com/symfony/expression-language.git",
- "reference": "867e4d1f5d4e52435a8ffff6b24fd6a801582241"
+ "reference": "de38e66398fca1fcb9c48e80279910e6889cb28f"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/expression-language/zipball/867e4d1f5d4e52435a8ffff6b24fd6a801582241",
- "reference": "867e4d1f5d4e52435a8ffff6b24fd6a801582241",
+ "url": "https://api.github.com/repos/symfony/expression-language/zipball/de38e66398fca1fcb9c48e80279910e6889cb28f",
+ "reference": "de38e66398fca1fcb9c48e80279910e6889cb28f",
"shasum": ""
},
"require": {
"php": "^5.5.9|>=7.0.8",
- "symfony/cache": "~3.1|~4.0"
+ "symfony/cache": "~3.1|~4.0",
+ "symfony/polyfill-php70": "~1.6"
},
"type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "3.4-dev"
- }
- },
"autoload": {
"psr-4": {
"Symfony\\Component\\ExpressionLanguage\\": ""
],
"description": "Symfony ExpressionLanguage Component",
"homepage": "https://symfony.com",
- "time": "2018-01-03T07:37:34+00:00"
+ "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": "2020-10-24T10:57:07+00:00"
},
{
"name": "symfony/polyfill-apcu",
- "version": "v1.13.1",
+ "version": "v1.28.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-apcu.git",
- "reference": "a8e961c841b9ec52927a87914f8820a1ad8f8116"
+ "reference": "c6c2c0f5f4cb0b100c5dfea807ef5cd27bbe9899"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/polyfill-apcu/zipball/a8e961c841b9ec52927a87914f8820a1ad8f8116",
- "reference": "a8e961c841b9ec52927a87914f8820a1ad8f8116",
+ "url": "https://api.github.com/repos/symfony/polyfill-apcu/zipball/c6c2c0f5f4cb0b100c5dfea807ef5cd27bbe9899",
+ "reference": "c6c2c0f5f4cb0b100c5dfea807ef5cd27bbe9899",
"shasum": ""
},
"require": {
- "php": ">=5.3.3"
+ "php": ">=7.1"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.13-dev"
+ "dev-main": "1.28-dev"
+ },
+ "thanks": {
+ "name": "symfony/polyfill",
+ "url": "https://github.com/symfony/polyfill"
}
},
"autoload": {
- "psr-4": {
- "Symfony\\Polyfill\\Apcu\\": ""
- },
"files": [
"bootstrap.php"
- ]
+ ],
+ "psr-4": {
+ "Symfony\\Polyfill\\Apcu\\": ""
+ }
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"portable",
"shim"
],
- "time": "2019-11-27T13:56:44+00:00"
+ "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": "2023-01-26T09:26:14+00:00"
+ },
+ {
+ "name": "symfony/polyfill-php70",
+ "version": "v1.20.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-php70.git",
+ "reference": "5f03a781d984aae42cebd18e7912fa80f02ee644"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/5f03a781d984aae42cebd18e7912fa80f02ee644",
+ "reference": "5f03a781d984aae42cebd18e7912fa80f02ee644",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.1"
+ },
+ "type": "metapackage",
+ "extra": {
+ "branch-alias": {
+ "dev-main": "1.20-dev"
+ },
+ "thanks": {
+ "name": "symfony/polyfill",
+ "url": "https://github.com/symfony/polyfill"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "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": "2020-10-23T14:02:19+00:00"
}
],
"packages-dev": [],
"platform": {
"php": ">=5.6.0"
},
- "platform-dev": []
+ "platform-dev": [],
+ "plugin-api-version": "1.1.0"
}
use Friendica\DI;
-$container = $slim->getContainer();
+/** @var $slim \Slim\App */
-// Error handler based off https://stackoverflow.com/a/48135009/757392
-$container['errorHandler'] = function () {
- return function(Psr\Http\Message\RequestInterface $request, Psr\Http\Message\ResponseInterface $response, Exception $exception)
- {
- $responseCode = 500;
-
- if (is_a($exception, 'Friendica\Network\HTTPException')) {
- $responseCode = $exception->getCode();
- }
-
- $errors['message'] = $exception->getMessage();
-
- $errors['responseCode'] = $responseCode;
-
- return $response
- ->withStatus($responseCode)
- ->withJson($errors);
- };
-};
+/**
+ * The routing middleware should be added before the ErrorMiddleware
+ * Otherwise exceptions thrown from it will not be handled
+ */
+$slim->addRoutingMiddleware();
-$container['notFoundHandler'] = function () {
- return function ()
- {
- throw new \Friendica\Network\HTTPException\NotFoundException(DI::l10n()->t('Method not found'));
- };
-};
+$errorMiddleware = $slim->addErrorMiddleware(true, true, true);
*/
/* @var $slim Slim\App */
-$slim->group('/advancedcontentfilter/api', function () {
- /* @var $this Slim\App */
- $this->group('/rules', function () {
- /* @var $this Slim\App */
- $this->get('', 'advancedcontentfilter_get_rules');
- $this->post('', 'advancedcontentfilter_post_rules');
+$slim->group('/advancedcontentfilter/api', function (\Slim\Routing\RouteCollectorProxy $app) {
+ $app->group('/rules', function (\Slim\Routing\RouteCollectorProxy $app) {
+ $app->get('', 'advancedcontentfilter_get_rules');
+ $app->post('', 'advancedcontentfilter_post_rules');
- $this->get('/{id}', 'advancedcontentfilter_get_rules_id');
- $this->put('/{id}', 'advancedcontentfilter_put_rules_id');
- $this->delete('/{id}', 'advancedcontentfilter_delete_rules_id');
+ $app->get('/{id}', 'advancedcontentfilter_get_rules_id');
+ $app->put('/{id}', 'advancedcontentfilter_put_rules_id');
+ $app->delete('/{id}', 'advancedcontentfilter_delete_rules_id');
});
- $this->group('/variables', function () {
- /* @var $this Slim\App */
- $this->get('/{guid}', 'advancedcontentfilter_get_variables_guid');
+ $app->group('/variables', function (\Slim\Routing\RouteCollectorProxy $app) {
+ $app->get('/{guid}', 'advancedcontentfilter_get_variables_guid');
});
});
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
- return call_user_func_array('array_merge', $this->prefixesPsr0);
+ return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
*/
public function setApcuPrefix($apcuPrefix)
{
- $this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null;
+ $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
- $search = $subPath.'\\';
+ $search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
'FastRoute\\RouteCollector' => $vendorDir . '/nikic/fast-route/src/RouteCollector.php',
'FastRoute\\RouteParser' => $vendorDir . '/nikic/fast-route/src/RouteParser.php',
'FastRoute\\RouteParser\\Std' => $vendorDir . '/nikic/fast-route/src/RouteParser/Std.php',
- 'Interop\\Container\\ContainerInterface' => $vendorDir . '/container-interop/container-interop/src/Interop/Container/ContainerInterface.php',
- 'Interop\\Container\\Exception\\ContainerException' => $vendorDir . '/container-interop/container-interop/src/Interop/Container/Exception/ContainerException.php',
- 'Interop\\Container\\Exception\\NotFoundException' => $vendorDir . '/container-interop/container-interop/src/Interop/Container/Exception/NotFoundException.php',
- 'Pimple\\Container' => $vendorDir . '/pimple/pimple/src/Pimple/Container.php',
- 'Pimple\\Exception\\ExpectedInvokableException' => $vendorDir . '/pimple/pimple/src/Pimple/Exception/ExpectedInvokableException.php',
- 'Pimple\\Exception\\FrozenServiceException' => $vendorDir . '/pimple/pimple/src/Pimple/Exception/FrozenServiceException.php',
- 'Pimple\\Exception\\InvalidServiceIdentifierException' => $vendorDir . '/pimple/pimple/src/Pimple/Exception/InvalidServiceIdentifierException.php',
- 'Pimple\\Exception\\UnknownIdentifierException' => $vendorDir . '/pimple/pimple/src/Pimple/Exception/UnknownIdentifierException.php',
- 'Pimple\\Psr11\\Container' => $vendorDir . '/pimple/pimple/src/Pimple/Psr11/Container.php',
- 'Pimple\\Psr11\\ServiceLocator' => $vendorDir . '/pimple/pimple/src/Pimple/Psr11/ServiceLocator.php',
- 'Pimple\\ServiceIterator' => $vendorDir . '/pimple/pimple/src/Pimple/ServiceIterator.php',
- 'Pimple\\ServiceProviderInterface' => $vendorDir . '/pimple/pimple/src/Pimple/ServiceProviderInterface.php',
- 'Pimple\\Tests\\Fixtures\\Invokable' => $vendorDir . '/pimple/pimple/src/Pimple/Tests/Fixtures/Invokable.php',
- 'Pimple\\Tests\\Fixtures\\NonInvokable' => $vendorDir . '/pimple/pimple/src/Pimple/Tests/Fixtures/NonInvokable.php',
- 'Pimple\\Tests\\Fixtures\\PimpleServiceProvider' => $vendorDir . '/pimple/pimple/src/Pimple/Tests/Fixtures/PimpleServiceProvider.php',
- 'Pimple\\Tests\\Fixtures\\Service' => $vendorDir . '/pimple/pimple/src/Pimple/Tests/Fixtures/Service.php',
- 'Pimple\\Tests\\PimpleServiceProviderInterfaceTest' => $vendorDir . '/pimple/pimple/src/Pimple/Tests/PimpleServiceProviderInterfaceTest.php',
- 'Pimple\\Tests\\PimpleTest' => $vendorDir . '/pimple/pimple/src/Pimple/Tests/PimpleTest.php',
- 'Pimple\\Tests\\Psr11\\ContainerTest' => $vendorDir . '/pimple/pimple/src/Pimple/Tests/Psr11/ContainerTest.php',
- 'Pimple\\Tests\\Psr11\\ServiceLocatorTest' => $vendorDir . '/pimple/pimple/src/Pimple/Tests/Psr11/ServiceLocatorTest.php',
- 'Pimple\\Tests\\ServiceIteratorTest' => $vendorDir . '/pimple/pimple/src/Pimple/Tests/ServiceIteratorTest.php',
'Psr\\Cache\\CacheException' => $vendorDir . '/psr/cache/src/CacheException.php',
'Psr\\Cache\\CacheItemInterface' => $vendorDir . '/psr/cache/src/CacheItemInterface.php',
'Psr\\Cache\\CacheItemPoolInterface' => $vendorDir . '/psr/cache/src/CacheItemPoolInterface.php',
'Psr\\Container\\ContainerInterface' => $vendorDir . '/psr/container/src/ContainerInterface.php',
'Psr\\Container\\NotFoundExceptionInterface' => $vendorDir . '/psr/container/src/NotFoundExceptionInterface.php',
'Psr\\Http\\Message\\MessageInterface' => $vendorDir . '/psr/http-message/src/MessageInterface.php',
+ 'Psr\\Http\\Message\\RequestFactoryInterface' => $vendorDir . '/psr/http-factory/src/RequestFactoryInterface.php',
'Psr\\Http\\Message\\RequestInterface' => $vendorDir . '/psr/http-message/src/RequestInterface.php',
+ 'Psr\\Http\\Message\\ResponseFactoryInterface' => $vendorDir . '/psr/http-factory/src/ResponseFactoryInterface.php',
'Psr\\Http\\Message\\ResponseInterface' => $vendorDir . '/psr/http-message/src/ResponseInterface.php',
+ 'Psr\\Http\\Message\\ServerRequestFactoryInterface' => $vendorDir . '/psr/http-factory/src/ServerRequestFactoryInterface.php',
'Psr\\Http\\Message\\ServerRequestInterface' => $vendorDir . '/psr/http-message/src/ServerRequestInterface.php',
+ 'Psr\\Http\\Message\\StreamFactoryInterface' => $vendorDir . '/psr/http-factory/src/StreamFactoryInterface.php',
'Psr\\Http\\Message\\StreamInterface' => $vendorDir . '/psr/http-message/src/StreamInterface.php',
+ 'Psr\\Http\\Message\\UploadedFileFactoryInterface' => $vendorDir . '/psr/http-factory/src/UploadedFileFactoryInterface.php',
'Psr\\Http\\Message\\UploadedFileInterface' => $vendorDir . '/psr/http-message/src/UploadedFileInterface.php',
+ 'Psr\\Http\\Message\\UriFactoryInterface' => $vendorDir . '/psr/http-factory/src/UriFactoryInterface.php',
'Psr\\Http\\Message\\UriInterface' => $vendorDir . '/psr/http-message/src/UriInterface.php',
+ 'Psr\\Http\\Server\\MiddlewareInterface' => $vendorDir . '/psr/http-server-middleware/src/MiddlewareInterface.php',
+ 'Psr\\Http\\Server\\RequestHandlerInterface' => $vendorDir . '/psr/http-server-handler/src/RequestHandlerInterface.php',
'Psr\\Log\\AbstractLogger' => $vendorDir . '/psr/log/Psr/Log/AbstractLogger.php',
'Psr\\Log\\InvalidArgumentException' => $vendorDir . '/psr/log/Psr/Log/InvalidArgumentException.php',
'Psr\\Log\\LogLevel' => $vendorDir . '/psr/log/Psr/Log/LogLevel.php',
'Psr\\Log\\LoggerInterface' => $vendorDir . '/psr/log/Psr/Log/LoggerInterface.php',
'Psr\\Log\\LoggerTrait' => $vendorDir . '/psr/log/Psr/Log/LoggerTrait.php',
'Psr\\Log\\NullLogger' => $vendorDir . '/psr/log/Psr/Log/NullLogger.php',
- 'Psr\\Log\\Test\\DummyTest' => $vendorDir . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
+ 'Psr\\Log\\Test\\DummyTest' => $vendorDir . '/psr/log/Psr/Log/Test/DummyTest.php',
'Psr\\Log\\Test\\LoggerInterfaceTest' => $vendorDir . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
+ 'Psr\\Log\\Test\\TestLogger' => $vendorDir . '/psr/log/Psr/Log/Test/TestLogger.php',
'Psr\\SimpleCache\\CacheException' => $vendorDir . '/psr/simple-cache/src/CacheException.php',
'Psr\\SimpleCache\\CacheInterface' => $vendorDir . '/psr/simple-cache/src/CacheInterface.php',
'Psr\\SimpleCache\\InvalidArgumentException' => $vendorDir . '/psr/simple-cache/src/InvalidArgumentException.php',
'Slim\\App' => $vendorDir . '/slim/slim/Slim/App.php',
'Slim\\CallableResolver' => $vendorDir . '/slim/slim/Slim/CallableResolver.php',
- 'Slim\\CallableResolverAwareTrait' => $vendorDir . '/slim/slim/Slim/CallableResolverAwareTrait.php',
- 'Slim\\Collection' => $vendorDir . '/slim/slim/Slim/Collection.php',
- 'Slim\\Container' => $vendorDir . '/slim/slim/Slim/Container.php',
- 'Slim\\DefaultServicesProvider' => $vendorDir . '/slim/slim/Slim/DefaultServicesProvider.php',
- 'Slim\\DeferredCallable' => $vendorDir . '/slim/slim/Slim/DeferredCallable.php',
- 'Slim\\Exception\\ContainerException' => $vendorDir . '/slim/slim/Slim/Exception/ContainerException.php',
- 'Slim\\Exception\\ContainerValueNotFoundException' => $vendorDir . '/slim/slim/Slim/Exception/ContainerValueNotFoundException.php',
- 'Slim\\Exception\\InvalidMethodException' => $vendorDir . '/slim/slim/Slim/Exception/InvalidMethodException.php',
- 'Slim\\Exception\\MethodNotAllowedException' => $vendorDir . '/slim/slim/Slim/Exception/MethodNotAllowedException.php',
- 'Slim\\Exception\\NotFoundException' => $vendorDir . '/slim/slim/Slim/Exception/NotFoundException.php',
- 'Slim\\Exception\\SlimException' => $vendorDir . '/slim/slim/Slim/Exception/SlimException.php',
- 'Slim\\Handlers\\AbstractError' => $vendorDir . '/slim/slim/Slim/Handlers/AbstractError.php',
- 'Slim\\Handlers\\AbstractHandler' => $vendorDir . '/slim/slim/Slim/Handlers/AbstractHandler.php',
- 'Slim\\Handlers\\Error' => $vendorDir . '/slim/slim/Slim/Handlers/Error.php',
- 'Slim\\Handlers\\NotAllowed' => $vendorDir . '/slim/slim/Slim/Handlers/NotAllowed.php',
- 'Slim\\Handlers\\NotFound' => $vendorDir . '/slim/slim/Slim/Handlers/NotFound.php',
- 'Slim\\Handlers\\PhpError' => $vendorDir . '/slim/slim/Slim/Handlers/PhpError.php',
+ 'Slim\\Error\\AbstractErrorRenderer' => $vendorDir . '/slim/slim/Slim/Error/AbstractErrorRenderer.php',
+ 'Slim\\Error\\Renderers\\HtmlErrorRenderer' => $vendorDir . '/slim/slim/Slim/Error/Renderers/HtmlErrorRenderer.php',
+ 'Slim\\Error\\Renderers\\JsonErrorRenderer' => $vendorDir . '/slim/slim/Slim/Error/Renderers/JsonErrorRenderer.php',
+ 'Slim\\Error\\Renderers\\PlainTextErrorRenderer' => $vendorDir . '/slim/slim/Slim/Error/Renderers/PlainTextErrorRenderer.php',
+ 'Slim\\Error\\Renderers\\XmlErrorRenderer' => $vendorDir . '/slim/slim/Slim/Error/Renderers/XmlErrorRenderer.php',
+ 'Slim\\Exception\\HttpBadRequestException' => $vendorDir . '/slim/slim/Slim/Exception/HttpBadRequestException.php',
+ 'Slim\\Exception\\HttpException' => $vendorDir . '/slim/slim/Slim/Exception/HttpException.php',
+ 'Slim\\Exception\\HttpForbiddenException' => $vendorDir . '/slim/slim/Slim/Exception/HttpForbiddenException.php',
+ 'Slim\\Exception\\HttpGoneException' => $vendorDir . '/slim/slim/Slim/Exception/HttpGoneException.php',
+ 'Slim\\Exception\\HttpInternalServerErrorException' => $vendorDir . '/slim/slim/Slim/Exception/HttpInternalServerErrorException.php',
+ 'Slim\\Exception\\HttpMethodNotAllowedException' => $vendorDir . '/slim/slim/Slim/Exception/HttpMethodNotAllowedException.php',
+ 'Slim\\Exception\\HttpNotFoundException' => $vendorDir . '/slim/slim/Slim/Exception/HttpNotFoundException.php',
+ 'Slim\\Exception\\HttpNotImplementedException' => $vendorDir . '/slim/slim/Slim/Exception/HttpNotImplementedException.php',
+ 'Slim\\Exception\\HttpSpecializedException' => $vendorDir . '/slim/slim/Slim/Exception/HttpSpecializedException.php',
+ 'Slim\\Exception\\HttpUnauthorizedException' => $vendorDir . '/slim/slim/Slim/Exception/HttpUnauthorizedException.php',
+ 'Slim\\Factory\\AppFactory' => $vendorDir . '/slim/slim/Slim/Factory/AppFactory.php',
+ 'Slim\\Factory\\Psr17\\GuzzlePsr17Factory' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/GuzzlePsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\HttpSoftPsr17Factory' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/HttpSoftPsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\LaminasDiactorosPsr17Factory' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/LaminasDiactorosPsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\NyholmPsr17Factory' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/NyholmPsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\Psr17Factory' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/Psr17Factory.php',
+ 'Slim\\Factory\\Psr17\\Psr17FactoryProvider' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/Psr17FactoryProvider.php',
+ 'Slim\\Factory\\Psr17\\ServerRequestCreator' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/ServerRequestCreator.php',
+ 'Slim\\Factory\\Psr17\\SlimHttpPsr17Factory' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/SlimHttpPsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\SlimHttpServerRequestCreator' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/SlimHttpServerRequestCreator.php',
+ 'Slim\\Factory\\Psr17\\SlimPsr17Factory' => $vendorDir . '/slim/slim/Slim/Factory/Psr17/SlimPsr17Factory.php',
+ 'Slim\\Factory\\ServerRequestCreatorFactory' => $vendorDir . '/slim/slim/Slim/Factory/ServerRequestCreatorFactory.php',
+ 'Slim\\Handlers\\ErrorHandler' => $vendorDir . '/slim/slim/Slim/Handlers/ErrorHandler.php',
+ 'Slim\\Handlers\\Strategies\\RequestHandler' => $vendorDir . '/slim/slim/Slim/Handlers/Strategies/RequestHandler.php',
'Slim\\Handlers\\Strategies\\RequestResponse' => $vendorDir . '/slim/slim/Slim/Handlers/Strategies/RequestResponse.php',
'Slim\\Handlers\\Strategies\\RequestResponseArgs' => $vendorDir . '/slim/slim/Slim/Handlers/Strategies/RequestResponseArgs.php',
- 'Slim\\Http\\Body' => $vendorDir . '/slim/slim/Slim/Http/Body.php',
- 'Slim\\Http\\Cookies' => $vendorDir . '/slim/slim/Slim/Http/Cookies.php',
- 'Slim\\Http\\Environment' => $vendorDir . '/slim/slim/Slim/Http/Environment.php',
- 'Slim\\Http\\Headers' => $vendorDir . '/slim/slim/Slim/Http/Headers.php',
- 'Slim\\Http\\Message' => $vendorDir . '/slim/slim/Slim/Http/Message.php',
- 'Slim\\Http\\Request' => $vendorDir . '/slim/slim/Slim/Http/Request.php',
- 'Slim\\Http\\RequestBody' => $vendorDir . '/slim/slim/Slim/Http/RequestBody.php',
- 'Slim\\Http\\Response' => $vendorDir . '/slim/slim/Slim/Http/Response.php',
- 'Slim\\Http\\Stream' => $vendorDir . '/slim/slim/Slim/Http/Stream.php',
- 'Slim\\Http\\UploadedFile' => $vendorDir . '/slim/slim/Slim/Http/UploadedFile.php',
- 'Slim\\Http\\Uri' => $vendorDir . '/slim/slim/Slim/Http/Uri.php',
+ 'Slim\\Handlers\\Strategies\\RequestResponseNamedArgs' => $vendorDir . '/slim/slim/Slim/Handlers/Strategies/RequestResponseNamedArgs.php',
+ 'Slim\\Interfaces\\AdvancedCallableResolverInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/AdvancedCallableResolverInterface.php',
'Slim\\Interfaces\\CallableResolverInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/CallableResolverInterface.php',
- 'Slim\\Interfaces\\CollectionInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/CollectionInterface.php',
- 'Slim\\Interfaces\\Http\\CookiesInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/Http/CookiesInterface.php',
- 'Slim\\Interfaces\\Http\\EnvironmentInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/Http/EnvironmentInterface.php',
- 'Slim\\Interfaces\\Http\\HeadersInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/Http/HeadersInterface.php',
+ 'Slim\\Interfaces\\DispatcherInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/DispatcherInterface.php',
+ 'Slim\\Interfaces\\ErrorHandlerInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/ErrorHandlerInterface.php',
+ 'Slim\\Interfaces\\ErrorRendererInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/ErrorRendererInterface.php',
'Slim\\Interfaces\\InvocationStrategyInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/InvocationStrategyInterface.php',
+ 'Slim\\Interfaces\\MiddlewareDispatcherInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/MiddlewareDispatcherInterface.php',
+ 'Slim\\Interfaces\\Psr17FactoryInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/Psr17FactoryInterface.php',
+ 'Slim\\Interfaces\\Psr17FactoryProviderInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/Psr17FactoryProviderInterface.php',
+ 'Slim\\Interfaces\\RequestHandlerInvocationStrategyInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/RequestHandlerInvocationStrategyInterface.php',
+ 'Slim\\Interfaces\\RouteCollectorInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/RouteCollectorInterface.php',
+ 'Slim\\Interfaces\\RouteCollectorProxyInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/RouteCollectorProxyInterface.php',
'Slim\\Interfaces\\RouteGroupInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/RouteGroupInterface.php',
'Slim\\Interfaces\\RouteInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/RouteInterface.php',
- 'Slim\\Interfaces\\RouterInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/RouterInterface.php',
- 'Slim\\MiddlewareAwareTrait' => $vendorDir . '/slim/slim/Slim/MiddlewareAwareTrait.php',
- 'Slim\\Routable' => $vendorDir . '/slim/slim/Slim/Routable.php',
- 'Slim\\Route' => $vendorDir . '/slim/slim/Slim/Route.php',
- 'Slim\\RouteGroup' => $vendorDir . '/slim/slim/Slim/RouteGroup.php',
- 'Slim\\Router' => $vendorDir . '/slim/slim/Slim/Router.php',
+ 'Slim\\Interfaces\\RouteParserInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/RouteParserInterface.php',
+ 'Slim\\Interfaces\\RouteResolverInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/RouteResolverInterface.php',
+ 'Slim\\Interfaces\\ServerRequestCreatorInterface' => $vendorDir . '/slim/slim/Slim/Interfaces/ServerRequestCreatorInterface.php',
+ 'Slim\\Logger' => $vendorDir . '/slim/slim/Slim/Logger.php',
+ 'Slim\\MiddlewareDispatcher' => $vendorDir . '/slim/slim/Slim/MiddlewareDispatcher.php',
+ 'Slim\\Middleware\\BodyParsingMiddleware' => $vendorDir . '/slim/slim/Slim/Middleware/BodyParsingMiddleware.php',
+ 'Slim\\Middleware\\ContentLengthMiddleware' => $vendorDir . '/slim/slim/Slim/Middleware/ContentLengthMiddleware.php',
+ 'Slim\\Middleware\\ErrorMiddleware' => $vendorDir . '/slim/slim/Slim/Middleware/ErrorMiddleware.php',
+ 'Slim\\Middleware\\MethodOverrideMiddleware' => $vendorDir . '/slim/slim/Slim/Middleware/MethodOverrideMiddleware.php',
+ 'Slim\\Middleware\\OutputBufferingMiddleware' => $vendorDir . '/slim/slim/Slim/Middleware/OutputBufferingMiddleware.php',
+ 'Slim\\Middleware\\RoutingMiddleware' => $vendorDir . '/slim/slim/Slim/Middleware/RoutingMiddleware.php',
+ 'Slim\\ResponseEmitter' => $vendorDir . '/slim/slim/Slim/ResponseEmitter.php',
+ 'Slim\\Routing\\Dispatcher' => $vendorDir . '/slim/slim/Slim/Routing/Dispatcher.php',
+ 'Slim\\Routing\\FastRouteDispatcher' => $vendorDir . '/slim/slim/Slim/Routing/FastRouteDispatcher.php',
+ 'Slim\\Routing\\Route' => $vendorDir . '/slim/slim/Slim/Routing/Route.php',
+ 'Slim\\Routing\\RouteCollector' => $vendorDir . '/slim/slim/Slim/Routing/RouteCollector.php',
+ 'Slim\\Routing\\RouteCollectorProxy' => $vendorDir . '/slim/slim/Slim/Routing/RouteCollectorProxy.php',
+ 'Slim\\Routing\\RouteContext' => $vendorDir . '/slim/slim/Slim/Routing/RouteContext.php',
+ 'Slim\\Routing\\RouteGroup' => $vendorDir . '/slim/slim/Slim/Routing/RouteGroup.php',
+ 'Slim\\Routing\\RouteParser' => $vendorDir . '/slim/slim/Slim/Routing/RouteParser.php',
+ 'Slim\\Routing\\RouteResolver' => $vendorDir . '/slim/slim/Slim/Routing/RouteResolver.php',
+ 'Slim\\Routing\\RouteRunner' => $vendorDir . '/slim/slim/Slim/Routing/RouteRunner.php',
+ 'Slim\\Routing\\RoutingResults' => $vendorDir . '/slim/slim/Slim/Routing/RoutingResults.php',
'Symfony\\Component\\Cache\\Adapter\\AbstractAdapter' => $vendorDir . '/symfony/cache/Adapter/AbstractAdapter.php',
'Symfony\\Component\\Cache\\Adapter\\AdapterInterface' => $vendorDir . '/symfony/cache/Adapter/AdapterInterface.php',
'Symfony\\Component\\Cache\\Adapter\\ApcuAdapter' => $vendorDir . '/symfony/cache/Adapter/ApcuAdapter.php',
$baseDir = dirname($vendorDir);
return array(
- 'Pimple' => array($vendorDir . '/pimple/pimple/src'),
);
'Slim\\' => array($vendorDir . '/slim/slim/Slim'),
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
- 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'),
+ 'Psr\\Http\\Server\\' => array($vendorDir . '/psr/http-server-handler/src', $vendorDir . '/psr/http-server-middleware/src'),
+ 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'Psr\\Cache\\' => array($vendorDir . '/psr/cache/src'),
- 'Interop\\Container\\' => array($vendorDir . '/container-interop/container-interop/src/Interop/Container'),
'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'),
);
}
}
+ /**
+ * @return \Composer\Autoload\ClassLoader
+ */
public static function getLoader()
{
if (null !== self::$loader) {
array (
'Psr\\SimpleCache\\' => 16,
'Psr\\Log\\' => 8,
+ 'Psr\\Http\\Server\\' => 16,
'Psr\\Http\\Message\\' => 17,
'Psr\\Container\\' => 14,
'Psr\\Cache\\' => 10,
),
- 'I' =>
- array (
- 'Interop\\Container\\' => 18,
- ),
'F' =>
array (
'FastRoute\\' => 10,
array (
0 => __DIR__ . '/..' . '/psr/log/Psr/Log',
),
+ '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',
+ 0 => __DIR__ . '/..' . '/psr/http-factory/src',
+ 1 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\Container\\' =>
array (
array (
0 => __DIR__ . '/..' . '/psr/cache/src',
),
- 'Interop\\Container\\' =>
- array (
- 0 => __DIR__ . '/..' . '/container-interop/container-interop/src/Interop/Container',
- ),
'FastRoute\\' =>
array (
0 => __DIR__ . '/..' . '/nikic/fast-route/src',
),
);
- public static $prefixesPsr0 = array (
- 'P' =>
- array (
- 'Pimple' =>
- array (
- 0 => __DIR__ . '/..' . '/pimple/pimple/src',
- ),
- ),
- );
-
public static $classMap = array (
'FastRoute\\BadRouteException' => __DIR__ . '/..' . '/nikic/fast-route/src/BadRouteException.php',
'FastRoute\\DataGenerator' => __DIR__ . '/..' . '/nikic/fast-route/src/DataGenerator.php',
'FastRoute\\RouteCollector' => __DIR__ . '/..' . '/nikic/fast-route/src/RouteCollector.php',
'FastRoute\\RouteParser' => __DIR__ . '/..' . '/nikic/fast-route/src/RouteParser.php',
'FastRoute\\RouteParser\\Std' => __DIR__ . '/..' . '/nikic/fast-route/src/RouteParser/Std.php',
- 'Interop\\Container\\ContainerInterface' => __DIR__ . '/..' . '/container-interop/container-interop/src/Interop/Container/ContainerInterface.php',
- 'Interop\\Container\\Exception\\ContainerException' => __DIR__ . '/..' . '/container-interop/container-interop/src/Interop/Container/Exception/ContainerException.php',
- 'Interop\\Container\\Exception\\NotFoundException' => __DIR__ . '/..' . '/container-interop/container-interop/src/Interop/Container/Exception/NotFoundException.php',
- 'Pimple\\Container' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Container.php',
- 'Pimple\\Exception\\ExpectedInvokableException' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Exception/ExpectedInvokableException.php',
- 'Pimple\\Exception\\FrozenServiceException' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Exception/FrozenServiceException.php',
- 'Pimple\\Exception\\InvalidServiceIdentifierException' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Exception/InvalidServiceIdentifierException.php',
- 'Pimple\\Exception\\UnknownIdentifierException' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Exception/UnknownIdentifierException.php',
- 'Pimple\\Psr11\\Container' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Psr11/Container.php',
- 'Pimple\\Psr11\\ServiceLocator' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Psr11/ServiceLocator.php',
- 'Pimple\\ServiceIterator' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/ServiceIterator.php',
- 'Pimple\\ServiceProviderInterface' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/ServiceProviderInterface.php',
- 'Pimple\\Tests\\Fixtures\\Invokable' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Tests/Fixtures/Invokable.php',
- 'Pimple\\Tests\\Fixtures\\NonInvokable' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Tests/Fixtures/NonInvokable.php',
- 'Pimple\\Tests\\Fixtures\\PimpleServiceProvider' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Tests/Fixtures/PimpleServiceProvider.php',
- 'Pimple\\Tests\\Fixtures\\Service' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Tests/Fixtures/Service.php',
- 'Pimple\\Tests\\PimpleServiceProviderInterfaceTest' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Tests/PimpleServiceProviderInterfaceTest.php',
- 'Pimple\\Tests\\PimpleTest' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Tests/PimpleTest.php',
- 'Pimple\\Tests\\Psr11\\ContainerTest' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Tests/Psr11/ContainerTest.php',
- 'Pimple\\Tests\\Psr11\\ServiceLocatorTest' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Tests/Psr11/ServiceLocatorTest.php',
- 'Pimple\\Tests\\ServiceIteratorTest' => __DIR__ . '/..' . '/pimple/pimple/src/Pimple/Tests/ServiceIteratorTest.php',
'Psr\\Cache\\CacheException' => __DIR__ . '/..' . '/psr/cache/src/CacheException.php',
'Psr\\Cache\\CacheItemInterface' => __DIR__ . '/..' . '/psr/cache/src/CacheItemInterface.php',
'Psr\\Cache\\CacheItemPoolInterface' => __DIR__ . '/..' . '/psr/cache/src/CacheItemPoolInterface.php',
'Psr\\Container\\ContainerInterface' => __DIR__ . '/..' . '/psr/container/src/ContainerInterface.php',
'Psr\\Container\\NotFoundExceptionInterface' => __DIR__ . '/..' . '/psr/container/src/NotFoundExceptionInterface.php',
'Psr\\Http\\Message\\MessageInterface' => __DIR__ . '/..' . '/psr/http-message/src/MessageInterface.php',
+ 'Psr\\Http\\Message\\RequestFactoryInterface' => __DIR__ . '/..' . '/psr/http-factory/src/RequestFactoryInterface.php',
'Psr\\Http\\Message\\RequestInterface' => __DIR__ . '/..' . '/psr/http-message/src/RequestInterface.php',
+ 'Psr\\Http\\Message\\ResponseFactoryInterface' => __DIR__ . '/..' . '/psr/http-factory/src/ResponseFactoryInterface.php',
'Psr\\Http\\Message\\ResponseInterface' => __DIR__ . '/..' . '/psr/http-message/src/ResponseInterface.php',
+ 'Psr\\Http\\Message\\ServerRequestFactoryInterface' => __DIR__ . '/..' . '/psr/http-factory/src/ServerRequestFactoryInterface.php',
'Psr\\Http\\Message\\ServerRequestInterface' => __DIR__ . '/..' . '/psr/http-message/src/ServerRequestInterface.php',
+ 'Psr\\Http\\Message\\StreamFactoryInterface' => __DIR__ . '/..' . '/psr/http-factory/src/StreamFactoryInterface.php',
'Psr\\Http\\Message\\StreamInterface' => __DIR__ . '/..' . '/psr/http-message/src/StreamInterface.php',
+ 'Psr\\Http\\Message\\UploadedFileFactoryInterface' => __DIR__ . '/..' . '/psr/http-factory/src/UploadedFileFactoryInterface.php',
'Psr\\Http\\Message\\UploadedFileInterface' => __DIR__ . '/..' . '/psr/http-message/src/UploadedFileInterface.php',
+ 'Psr\\Http\\Message\\UriFactoryInterface' => __DIR__ . '/..' . '/psr/http-factory/src/UriFactoryInterface.php',
'Psr\\Http\\Message\\UriInterface' => __DIR__ . '/..' . '/psr/http-message/src/UriInterface.php',
+ 'Psr\\Http\\Server\\MiddlewareInterface' => __DIR__ . '/..' . '/psr/http-server-middleware/src/MiddlewareInterface.php',
+ 'Psr\\Http\\Server\\RequestHandlerInterface' => __DIR__ . '/..' . '/psr/http-server-handler/src/RequestHandlerInterface.php',
'Psr\\Log\\AbstractLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/AbstractLogger.php',
'Psr\\Log\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/log/Psr/Log/InvalidArgumentException.php',
'Psr\\Log\\LogLevel' => __DIR__ . '/..' . '/psr/log/Psr/Log/LogLevel.php',
'Psr\\Log\\LoggerInterface' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerInterface.php',
'Psr\\Log\\LoggerTrait' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerTrait.php',
'Psr\\Log\\NullLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/NullLogger.php',
- 'Psr\\Log\\Test\\DummyTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
+ 'Psr\\Log\\Test\\DummyTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/DummyTest.php',
'Psr\\Log\\Test\\LoggerInterfaceTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
+ 'Psr\\Log\\Test\\TestLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/TestLogger.php',
'Psr\\SimpleCache\\CacheException' => __DIR__ . '/..' . '/psr/simple-cache/src/CacheException.php',
'Psr\\SimpleCache\\CacheInterface' => __DIR__ . '/..' . '/psr/simple-cache/src/CacheInterface.php',
'Psr\\SimpleCache\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/simple-cache/src/InvalidArgumentException.php',
'Slim\\App' => __DIR__ . '/..' . '/slim/slim/Slim/App.php',
'Slim\\CallableResolver' => __DIR__ . '/..' . '/slim/slim/Slim/CallableResolver.php',
- 'Slim\\CallableResolverAwareTrait' => __DIR__ . '/..' . '/slim/slim/Slim/CallableResolverAwareTrait.php',
- 'Slim\\Collection' => __DIR__ . '/..' . '/slim/slim/Slim/Collection.php',
- 'Slim\\Container' => __DIR__ . '/..' . '/slim/slim/Slim/Container.php',
- 'Slim\\DefaultServicesProvider' => __DIR__ . '/..' . '/slim/slim/Slim/DefaultServicesProvider.php',
- 'Slim\\DeferredCallable' => __DIR__ . '/..' . '/slim/slim/Slim/DeferredCallable.php',
- 'Slim\\Exception\\ContainerException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/ContainerException.php',
- 'Slim\\Exception\\ContainerValueNotFoundException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/ContainerValueNotFoundException.php',
- 'Slim\\Exception\\InvalidMethodException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/InvalidMethodException.php',
- 'Slim\\Exception\\MethodNotAllowedException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/MethodNotAllowedException.php',
- 'Slim\\Exception\\NotFoundException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/NotFoundException.php',
- 'Slim\\Exception\\SlimException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/SlimException.php',
- 'Slim\\Handlers\\AbstractError' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/AbstractError.php',
- 'Slim\\Handlers\\AbstractHandler' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/AbstractHandler.php',
- 'Slim\\Handlers\\Error' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/Error.php',
- 'Slim\\Handlers\\NotAllowed' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/NotAllowed.php',
- 'Slim\\Handlers\\NotFound' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/NotFound.php',
- 'Slim\\Handlers\\PhpError' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/PhpError.php',
+ 'Slim\\Error\\AbstractErrorRenderer' => __DIR__ . '/..' . '/slim/slim/Slim/Error/AbstractErrorRenderer.php',
+ 'Slim\\Error\\Renderers\\HtmlErrorRenderer' => __DIR__ . '/..' . '/slim/slim/Slim/Error/Renderers/HtmlErrorRenderer.php',
+ 'Slim\\Error\\Renderers\\JsonErrorRenderer' => __DIR__ . '/..' . '/slim/slim/Slim/Error/Renderers/JsonErrorRenderer.php',
+ 'Slim\\Error\\Renderers\\PlainTextErrorRenderer' => __DIR__ . '/..' . '/slim/slim/Slim/Error/Renderers/PlainTextErrorRenderer.php',
+ 'Slim\\Error\\Renderers\\XmlErrorRenderer' => __DIR__ . '/..' . '/slim/slim/Slim/Error/Renderers/XmlErrorRenderer.php',
+ 'Slim\\Exception\\HttpBadRequestException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpBadRequestException.php',
+ 'Slim\\Exception\\HttpException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpException.php',
+ 'Slim\\Exception\\HttpForbiddenException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpForbiddenException.php',
+ 'Slim\\Exception\\HttpGoneException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpGoneException.php',
+ 'Slim\\Exception\\HttpInternalServerErrorException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpInternalServerErrorException.php',
+ 'Slim\\Exception\\HttpMethodNotAllowedException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpMethodNotAllowedException.php',
+ 'Slim\\Exception\\HttpNotFoundException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpNotFoundException.php',
+ 'Slim\\Exception\\HttpNotImplementedException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpNotImplementedException.php',
+ 'Slim\\Exception\\HttpSpecializedException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpSpecializedException.php',
+ 'Slim\\Exception\\HttpUnauthorizedException' => __DIR__ . '/..' . '/slim/slim/Slim/Exception/HttpUnauthorizedException.php',
+ 'Slim\\Factory\\AppFactory' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/AppFactory.php',
+ 'Slim\\Factory\\Psr17\\GuzzlePsr17Factory' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/GuzzlePsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\HttpSoftPsr17Factory' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/HttpSoftPsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\LaminasDiactorosPsr17Factory' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/LaminasDiactorosPsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\NyholmPsr17Factory' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/NyholmPsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\Psr17Factory' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/Psr17Factory.php',
+ 'Slim\\Factory\\Psr17\\Psr17FactoryProvider' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/Psr17FactoryProvider.php',
+ 'Slim\\Factory\\Psr17\\ServerRequestCreator' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/ServerRequestCreator.php',
+ 'Slim\\Factory\\Psr17\\SlimHttpPsr17Factory' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/SlimHttpPsr17Factory.php',
+ 'Slim\\Factory\\Psr17\\SlimHttpServerRequestCreator' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/SlimHttpServerRequestCreator.php',
+ 'Slim\\Factory\\Psr17\\SlimPsr17Factory' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/Psr17/SlimPsr17Factory.php',
+ 'Slim\\Factory\\ServerRequestCreatorFactory' => __DIR__ . '/..' . '/slim/slim/Slim/Factory/ServerRequestCreatorFactory.php',
+ 'Slim\\Handlers\\ErrorHandler' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/ErrorHandler.php',
+ 'Slim\\Handlers\\Strategies\\RequestHandler' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/Strategies/RequestHandler.php',
'Slim\\Handlers\\Strategies\\RequestResponse' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/Strategies/RequestResponse.php',
'Slim\\Handlers\\Strategies\\RequestResponseArgs' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/Strategies/RequestResponseArgs.php',
- 'Slim\\Http\\Body' => __DIR__ . '/..' . '/slim/slim/Slim/Http/Body.php',
- 'Slim\\Http\\Cookies' => __DIR__ . '/..' . '/slim/slim/Slim/Http/Cookies.php',
- 'Slim\\Http\\Environment' => __DIR__ . '/..' . '/slim/slim/Slim/Http/Environment.php',
- 'Slim\\Http\\Headers' => __DIR__ . '/..' . '/slim/slim/Slim/Http/Headers.php',
- 'Slim\\Http\\Message' => __DIR__ . '/..' . '/slim/slim/Slim/Http/Message.php',
- 'Slim\\Http\\Request' => __DIR__ . '/..' . '/slim/slim/Slim/Http/Request.php',
- 'Slim\\Http\\RequestBody' => __DIR__ . '/..' . '/slim/slim/Slim/Http/RequestBody.php',
- 'Slim\\Http\\Response' => __DIR__ . '/..' . '/slim/slim/Slim/Http/Response.php',
- 'Slim\\Http\\Stream' => __DIR__ . '/..' . '/slim/slim/Slim/Http/Stream.php',
- 'Slim\\Http\\UploadedFile' => __DIR__ . '/..' . '/slim/slim/Slim/Http/UploadedFile.php',
- 'Slim\\Http\\Uri' => __DIR__ . '/..' . '/slim/slim/Slim/Http/Uri.php',
+ 'Slim\\Handlers\\Strategies\\RequestResponseNamedArgs' => __DIR__ . '/..' . '/slim/slim/Slim/Handlers/Strategies/RequestResponseNamedArgs.php',
+ 'Slim\\Interfaces\\AdvancedCallableResolverInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/AdvancedCallableResolverInterface.php',
'Slim\\Interfaces\\CallableResolverInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/CallableResolverInterface.php',
- 'Slim\\Interfaces\\CollectionInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/CollectionInterface.php',
- 'Slim\\Interfaces\\Http\\CookiesInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/Http/CookiesInterface.php',
- 'Slim\\Interfaces\\Http\\EnvironmentInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/Http/EnvironmentInterface.php',
- 'Slim\\Interfaces\\Http\\HeadersInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/Http/HeadersInterface.php',
+ 'Slim\\Interfaces\\DispatcherInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/DispatcherInterface.php',
+ 'Slim\\Interfaces\\ErrorHandlerInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/ErrorHandlerInterface.php',
+ 'Slim\\Interfaces\\ErrorRendererInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/ErrorRendererInterface.php',
'Slim\\Interfaces\\InvocationStrategyInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/InvocationStrategyInterface.php',
+ 'Slim\\Interfaces\\MiddlewareDispatcherInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/MiddlewareDispatcherInterface.php',
+ 'Slim\\Interfaces\\Psr17FactoryInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/Psr17FactoryInterface.php',
+ 'Slim\\Interfaces\\Psr17FactoryProviderInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/Psr17FactoryProviderInterface.php',
+ 'Slim\\Interfaces\\RequestHandlerInvocationStrategyInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/RequestHandlerInvocationStrategyInterface.php',
+ 'Slim\\Interfaces\\RouteCollectorInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/RouteCollectorInterface.php',
+ 'Slim\\Interfaces\\RouteCollectorProxyInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/RouteCollectorProxyInterface.php',
'Slim\\Interfaces\\RouteGroupInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/RouteGroupInterface.php',
'Slim\\Interfaces\\RouteInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/RouteInterface.php',
- 'Slim\\Interfaces\\RouterInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/RouterInterface.php',
- 'Slim\\MiddlewareAwareTrait' => __DIR__ . '/..' . '/slim/slim/Slim/MiddlewareAwareTrait.php',
- 'Slim\\Routable' => __DIR__ . '/..' . '/slim/slim/Slim/Routable.php',
- 'Slim\\Route' => __DIR__ . '/..' . '/slim/slim/Slim/Route.php',
- 'Slim\\RouteGroup' => __DIR__ . '/..' . '/slim/slim/Slim/RouteGroup.php',
- 'Slim\\Router' => __DIR__ . '/..' . '/slim/slim/Slim/Router.php',
+ 'Slim\\Interfaces\\RouteParserInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/RouteParserInterface.php',
+ 'Slim\\Interfaces\\RouteResolverInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/RouteResolverInterface.php',
+ 'Slim\\Interfaces\\ServerRequestCreatorInterface' => __DIR__ . '/..' . '/slim/slim/Slim/Interfaces/ServerRequestCreatorInterface.php',
+ 'Slim\\Logger' => __DIR__ . '/..' . '/slim/slim/Slim/Logger.php',
+ 'Slim\\MiddlewareDispatcher' => __DIR__ . '/..' . '/slim/slim/Slim/MiddlewareDispatcher.php',
+ 'Slim\\Middleware\\BodyParsingMiddleware' => __DIR__ . '/..' . '/slim/slim/Slim/Middleware/BodyParsingMiddleware.php',
+ 'Slim\\Middleware\\ContentLengthMiddleware' => __DIR__ . '/..' . '/slim/slim/Slim/Middleware/ContentLengthMiddleware.php',
+ 'Slim\\Middleware\\ErrorMiddleware' => __DIR__ . '/..' . '/slim/slim/Slim/Middleware/ErrorMiddleware.php',
+ 'Slim\\Middleware\\MethodOverrideMiddleware' => __DIR__ . '/..' . '/slim/slim/Slim/Middleware/MethodOverrideMiddleware.php',
+ 'Slim\\Middleware\\OutputBufferingMiddleware' => __DIR__ . '/..' . '/slim/slim/Slim/Middleware/OutputBufferingMiddleware.php',
+ 'Slim\\Middleware\\RoutingMiddleware' => __DIR__ . '/..' . '/slim/slim/Slim/Middleware/RoutingMiddleware.php',
+ 'Slim\\ResponseEmitter' => __DIR__ . '/..' . '/slim/slim/Slim/ResponseEmitter.php',
+ 'Slim\\Routing\\Dispatcher' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/Dispatcher.php',
+ 'Slim\\Routing\\FastRouteDispatcher' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/FastRouteDispatcher.php',
+ 'Slim\\Routing\\Route' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/Route.php',
+ 'Slim\\Routing\\RouteCollector' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/RouteCollector.php',
+ 'Slim\\Routing\\RouteCollectorProxy' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/RouteCollectorProxy.php',
+ 'Slim\\Routing\\RouteContext' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/RouteContext.php',
+ 'Slim\\Routing\\RouteGroup' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/RouteGroup.php',
+ 'Slim\\Routing\\RouteParser' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/RouteParser.php',
+ 'Slim\\Routing\\RouteResolver' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/RouteResolver.php',
+ 'Slim\\Routing\\RouteRunner' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/RouteRunner.php',
+ 'Slim\\Routing\\RoutingResults' => __DIR__ . '/..' . '/slim/slim/Slim/Routing/RoutingResults.php',
'Symfony\\Component\\Cache\\Adapter\\AbstractAdapter' => __DIR__ . '/..' . '/symfony/cache/Adapter/AbstractAdapter.php',
'Symfony\\Component\\Cache\\Adapter\\AdapterInterface' => __DIR__ . '/..' . '/symfony/cache/Adapter/AdapterInterface.php',
'Symfony\\Component\\Cache\\Adapter\\ApcuAdapter' => __DIR__ . '/..' . '/symfony/cache/Adapter/ApcuAdapter.php',
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitAdvancedContentFilterAddon::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitAdvancedContentFilterAddon::$prefixDirsPsr4;
- $loader->prefixesPsr0 = ComposerStaticInitAdvancedContentFilterAddon::$prefixesPsr0;
$loader->classMap = ComposerStaticInitAdvancedContentFilterAddon::$classMap;
}, null, ClassLoader::class);
[
- {
- "name": "container-interop/container-interop",
- "version": "1.2.0",
- "version_normalized": "1.2.0.0",
- "source": {
- "type": "git",
- "url": "https://github.com/container-interop/container-interop.git",
- "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/container-interop/container-interop/zipball/79cbf1341c22ec75643d841642dd5d6acd83bdb8",
- "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8",
- "shasum": ""
- },
- "require": {
- "psr/container": "^1.0"
- },
- "time": "2017-02-14T19:40:03+00:00",
- "type": "library",
- "installation-source": "dist",
- "autoload": {
- "psr-4": {
- "Interop\\Container\\": "src/Interop/Container/"
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "description": "Promoting the interoperability of container objects (DIC, SL, etc.)",
- "homepage": "https://github.com/container-interop/container-interop"
- },
{
"name": "nikic/fast-route",
"version": "v1.3.0",
]
},
{
- "name": "pimple/pimple",
- "version": "v3.2.3",
- "version_normalized": "3.2.3.0",
+ "name": "psr/cache",
+ "version": "1.0.1",
+ "version_normalized": "1.0.1.0",
"source": {
"type": "git",
- "url": "https://github.com/silexphp/Pimple.git",
- "reference": "9e403941ef9d65d20cba7d54e29fe906db42cf32"
+ "url": "https://github.com/php-fig/cache.git",
+ "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/silexphp/Pimple/zipball/9e403941ef9d65d20cba7d54e29fe906db42cf32",
- "reference": "9e403941ef9d65d20cba7d54e29fe906db42cf32",
+ "url": "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8",
+ "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8",
"shasum": ""
},
"require": {
- "php": ">=5.3.0",
- "psr/container": "^1.0"
- },
- "require-dev": {
- "symfony/phpunit-bridge": "^3.2"
+ "php": ">=5.3.0"
},
- "time": "2018-01-21T07:42:36+00:00",
+ "time": "2016-08-06T20:24:11+00:00",
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "3.2.x-dev"
+ "dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
- "psr-0": {
- "Pimple": "src/"
+ "psr-4": {
+ "Psr\\Cache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
],
"authors": [
{
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com"
+ "name": "PHP-FIG",
+ "homepage": "http://www.php-fig.org/"
}
],
- "description": "Pimple, a simple Dependency Injection Container",
- "homepage": "http://pimple.sensiolabs.org",
+ "description": "Common interface for caching libraries",
"keywords": [
- "container",
- "dependency injection"
+ "cache",
+ "psr",
+ "psr-6"
]
},
{
- "name": "psr/cache",
- "version": "1.0.1",
- "version_normalized": "1.0.1.0",
+ "name": "psr/container",
+ "version": "2.0.2",
+ "version_normalized": "2.0.2.0",
"source": {
"type": "git",
- "url": "https://github.com/php-fig/cache.git",
- "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8"
+ "url": "https://github.com/php-fig/container.git",
+ "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8",
- "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8",
+ "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963",
+ "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963",
"shasum": ""
},
"require": {
- "php": ">=5.3.0"
+ "php": ">=7.4.0"
},
- "time": "2016-08-06T20:24:11+00:00",
+ "time": "2021-11-05T16:47:00+00:00",
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-master": "2.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
- "Psr\\Cache\\": "src/"
+ "Psr\\Container\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"authors": [
{
"name": "PHP-FIG",
- "homepage": "http://www.php-fig.org/"
+ "homepage": "https://www.php-fig.org/"
}
],
- "description": "Common interface for caching libraries",
+ "description": "Common Container Interface (PHP FIG PSR-11)",
+ "homepage": "https://github.com/php-fig/container",
"keywords": [
- "cache",
- "psr",
- "psr-6"
+ "PSR-11",
+ "container",
+ "container-interface",
+ "container-interop",
+ "psr"
]
},
{
- "name": "psr/container",
- "version": "1.0.0",
- "version_normalized": "1.0.0.0",
+ "name": "psr/http-factory",
+ "version": "1.0.2",
+ "version_normalized": "1.0.2.0",
"source": {
"type": "git",
- "url": "https://github.com/php-fig/container.git",
- "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f"
+ "url": "https://github.com/php-fig/http-factory.git",
+ "reference": "e616d01114759c4c489f93b099585439f795fe35"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f",
- "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f",
+ "url": "https://api.github.com/repos/php-fig/http-factory/zipball/e616d01114759c4c489f93b099585439f795fe35",
+ "reference": "e616d01114759c4c489f93b099585439f795fe35",
"shasum": ""
},
"require": {
- "php": ">=5.3.0"
+ "php": ">=7.0.0",
+ "psr/http-message": "^1.0 || ^2.0"
},
- "time": "2017-02-14T16:28:37+00:00",
+ "time": "2023-04-10T20:10:41+00:00",
"type": "library",
"extra": {
"branch-alias": {
"installation-source": "dist",
"autoload": {
"psr-4": {
- "Psr\\Container\\": "src/"
+ "Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"authors": [
{
"name": "PHP-FIG",
- "homepage": "http://www.php-fig.org/"
+ "homepage": "https://www.php-fig.org/"
}
],
- "description": "Common Container Interface (PHP FIG PSR-11)",
- "homepage": "https://github.com/php-fig/container",
+ "description": "Common interfaces for PSR-7 HTTP message factories",
"keywords": [
- "PSR-11",
- "container",
- "container-interface",
- "container-interop",
- "psr"
+ "factory",
+ "http",
+ "message",
+ "psr",
+ "psr-17",
+ "psr-7",
+ "request",
+ "response"
]
},
{
"name": "psr/http-message",
- "version": "1.0.1",
- "version_normalized": "1.0.1.0",
+ "version": "1.1",
+ "version_normalized": "1.1.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
- "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
+ "reference": "cb6ce4845ce34a8ad9e68117c10ee90a29919eba"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363",
- "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
+ "url": "https://api.github.com/repos/php-fig/http-message/zipball/cb6ce4845ce34a8ad9e68117c10ee90a29919eba",
+ "reference": "cb6ce4845ce34a8ad9e68117c10ee90a29919eba",
"shasum": ""
},
"require": {
- "php": ">=5.3.0"
+ "php": "^7.2 || ^8.0"
},
- "time": "2016-08-06T14:39:51+00:00",
+ "time": "2023-04-04T09:50:52+00:00",
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-master": "1.1.x-dev"
}
},
"installation-source": "dist",
]
},
{
- "name": "psr/log",
+ "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"
+ ]
+ },
+ {
+ "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"
+ ]
+ },
+ {
+ "name": "psr/log",
+ "version": "1.1.4",
+ "version_normalized": "1.1.4.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/log.git",
- "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d"
+ "reference": "d49695b909c3b7628b6289db5479a1c204601f11"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
- "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
+ "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11",
+ "reference": "d49695b909c3b7628b6289db5479a1c204601f11",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
- "time": "2016-10-10T12:19:37+00:00",
+ "time": "2021-05-03T11:20:27+00:00",
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-master": "1.1.x-dev"
}
},
"installation-source": "dist",
"authors": [
{
"name": "PHP-FIG",
- "homepage": "http://www.php-fig.org/"
+ "homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for logging libraries",
},
{
"name": "slim/slim",
- "version": "3.9.2",
- "version_normalized": "3.9.2.0",
+ "version": "4.12.0",
+ "version_normalized": "4.12.0.0",
"source": {
"type": "git",
"url": "https://github.com/slimphp/Slim.git",
- "reference": "4086d0106cf5a7135c69fce4161fe355a8feb118"
+ "reference": "e9e99c2b24398b967841c6c4c3048622cc7e2b18"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/slimphp/Slim/zipball/4086d0106cf5a7135c69fce4161fe355a8feb118",
- "reference": "4086d0106cf5a7135c69fce4161fe355a8feb118",
+ "url": "https://api.github.com/repos/slimphp/Slim/zipball/e9e99c2b24398b967841c6c4c3048622cc7e2b18",
+ "reference": "e9e99c2b24398b967841c6c4c3048622cc7e2b18",
"shasum": ""
},
"require": {
- "container-interop/container-interop": "^1.2",
- "nikic/fast-route": "^1.0",
- "php": ">=5.5.0",
- "pimple/pimple": "^3.0",
- "psr/container": "^1.0",
- "psr/http-message": "^1.0"
- },
- "provide": {
- "psr/http-message-implementation": "1.0"
+ "ext-json": "*",
+ "nikic/fast-route": "^1.3",
+ "php": "^7.4 || ^8.0",
+ "psr/container": "^1.0 || ^2.0",
+ "psr/http-factory": "^1.0",
+ "psr/http-message": "^1.1",
+ "psr/http-server-handler": "^1.0",
+ "psr/http-server-middleware": "^1.0",
+ "psr/log": "^1.1 || ^2.0 || ^3.0"
},
"require-dev": {
- "phpunit/phpunit": "^4.0",
- "squizlabs/php_codesniffer": "^2.5"
- },
- "time": "2017-11-26T19:13:09+00:00",
+ "adriansuter/php-autoload-override": "^1.4",
+ "ext-simplexml": "*",
+ "guzzlehttp/psr7": "^2.5",
+ "httpsoft/http-message": "^1.1",
+ "httpsoft/http-server-request": "^1.1",
+ "laminas/laminas-diactoros": "^2.17",
+ "nyholm/psr7": "^1.8",
+ "nyholm/psr7-server": "^1.0",
+ "phpspec/prophecy": "^1.17",
+ "phpspec/prophecy-phpunit": "^2.0",
+ "phpstan/phpstan": "^1.10",
+ "phpunit/phpunit": "^9.6",
+ "slim/http": "^1.3",
+ "slim/psr7": "^1.6",
+ "squizlabs/php_codesniffer": "^3.7"
+ },
+ "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": "2023-07-23T04:54:29+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"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": "Josh Lockhart",
- "email": "hello@joshlockhart.com",
- "homepage": "https://joshlockhart.com"
+ "name": "Pierre Berube",
+ "email": "pierre@lgse.com",
+ "homepage": "http://www.lgse.com"
},
{
"name": "Gabriel Manricks",
"email": "gmanricks@me.com",
"homepage": "http://gabrielmanricks.com"
- },
- {
- "name": "Andrew Smith",
- "email": "a.smith@silentworks.co.uk",
- "homepage": "http://silentworks.co.uk"
}
],
"description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs",
- "homepage": "https://slimframework.com",
+ "homepage": "https://www.slimframework.com",
"keywords": [
"api",
"framework",
"micro",
"router"
+ ],
+ "funding": [
+ {
+ "url": "https://opencollective.com/slimphp",
+ "type": "open_collective"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/slim/slim",
+ "type": "tidelift"
+ }
]
},
{
"name": "symfony/cache",
- "version": "v3.4.8",
- "version_normalized": "3.4.8.0",
+ "version": "v3.4.47",
+ "version_normalized": "3.4.47.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/cache.git",
- "reference": "13255ddd056e49f3154747943f8ee175d555d394"
+ "reference": "a7a14c4832760bd1fbd31be2859ffedc9b6ff813"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/cache/zipball/13255ddd056e49f3154747943f8ee175d555d394",
- "reference": "13255ddd056e49f3154747943f8ee175d555d394",
+ "url": "https://api.github.com/repos/symfony/cache/zipball/a7a14c4832760bd1fbd31be2859ffedc9b6ff813",
+ "reference": "a7a14c4832760bd1fbd31be2859ffedc9b6ff813",
"shasum": ""
},
"require": {
},
"require-dev": {
"cache/integration-tests": "dev-master",
- "doctrine/cache": "~1.6",
- "doctrine/dbal": "~2.4",
- "predis/predis": "~1.0"
+ "doctrine/cache": "^1.6",
+ "doctrine/dbal": "^2.4|^3.0",
+ "predis/predis": "^1.0"
},
- "time": "2018-04-02T14:35:16+00:00",
+ "time": "2020-10-24T10:57:07+00:00",
"type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "3.4-dev"
- }
- },
"installation-source": "dist",
"autoload": {
"psr-4": {
"keywords": [
"caching",
"psr6"
+ ],
+ "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"
+ }
]
},
{
"name": "symfony/expression-language",
- "version": "v3.4.8",
- "version_normalized": "3.4.8.0",
+ "version": "v3.4.47",
+ "version_normalized": "3.4.47.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/expression-language.git",
- "reference": "867e4d1f5d4e52435a8ffff6b24fd6a801582241"
+ "reference": "de38e66398fca1fcb9c48e80279910e6889cb28f"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/expression-language/zipball/867e4d1f5d4e52435a8ffff6b24fd6a801582241",
- "reference": "867e4d1f5d4e52435a8ffff6b24fd6a801582241",
+ "url": "https://api.github.com/repos/symfony/expression-language/zipball/de38e66398fca1fcb9c48e80279910e6889cb28f",
+ "reference": "de38e66398fca1fcb9c48e80279910e6889cb28f",
"shasum": ""
},
"require": {
"php": "^5.5.9|>=7.0.8",
- "symfony/cache": "~3.1|~4.0"
+ "symfony/cache": "~3.1|~4.0",
+ "symfony/polyfill-php70": "~1.6"
},
- "time": "2018-01-03T07:37:34+00:00",
+ "time": "2020-10-24T10:57:07+00:00",
"type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "3.4-dev"
- }
- },
"installation-source": "dist",
"autoload": {
"psr-4": {
}
],
"description": "Symfony ExpressionLanguage Component",
- "homepage": "https://symfony.com"
+ "homepage": "https://symfony.com",
+ "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"
+ }
+ ]
},
{
"name": "symfony/polyfill-apcu",
- "version": "v1.7.0",
- "version_normalized": "1.7.0.0",
+ "version": "v1.28.0",
+ "version_normalized": "1.28.0.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-apcu.git",
- "reference": "e8ae2136ddb53dea314df56fcd88e318ab936c00"
+ "reference": "c6c2c0f5f4cb0b100c5dfea807ef5cd27bbe9899"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/polyfill-apcu/zipball/e8ae2136ddb53dea314df56fcd88e318ab936c00",
- "reference": "e8ae2136ddb53dea314df56fcd88e318ab936c00",
+ "url": "https://api.github.com/repos/symfony/polyfill-apcu/zipball/c6c2c0f5f4cb0b100c5dfea807ef5cd27bbe9899",
+ "reference": "c6c2c0f5f4cb0b100c5dfea807ef5cd27bbe9899",
"shasum": ""
},
"require": {
- "php": ">=5.3.3"
+ "php": ">=7.1"
},
- "time": "2018-01-30T19:27:44+00:00",
+ "time": "2023-01-26T09:26:14+00:00",
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.7-dev"
+ "dev-main": "1.28-dev"
+ },
+ "thanks": {
+ "name": "symfony/polyfill",
+ "url": "https://github.com/symfony/polyfill"
}
},
"installation-source": "dist",
"autoload": {
- "psr-4": {
- "Symfony\\Polyfill\\Apcu\\": ""
- },
"files": [
"bootstrap.php"
- ]
+ ],
+ "psr-4": {
+ "Symfony\\Polyfill\\Apcu\\": ""
+ }
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"polyfill",
"portable",
"shim"
+ ],
+ "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"
+ }
+ ]
+ },
+ {
+ "name": "symfony/polyfill-php70",
+ "version": "v1.20.0",
+ "version_normalized": "1.20.0.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-php70.git",
+ "reference": "5f03a781d984aae42cebd18e7912fa80f02ee644"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/5f03a781d984aae42cebd18e7912fa80f02ee644",
+ "reference": "5f03a781d984aae42cebd18e7912fa80f02ee644",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.1"
+ },
+ "time": "2020-10-23T14:02:19+00:00",
+ "type": "metapackage",
+ "extra": {
+ "branch-alias": {
+ "dev-main": "1.20-dev"
+ },
+ "thanks": {
+ "name": "symfony/polyfill",
+ "url": "https://github.com/symfony/polyfill"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "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"
+ }
]
}
]
+++ /dev/null
-composer.lock
-composer.phar
-/vendor/
+++ /dev/null
-The MIT License (MIT)
-
-Copyright (c) 2013 container-interop
-
-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.
+++ /dev/null
-# Container Interoperability
-
-[](https://packagist.org/packages/container-interop/container-interop)
-[](https://packagist.org/packages/container-interop/container-interop)
-
-## Deprecation warning!
-
-Starting Feb. 13th 2017, container-interop is officially deprecated in favor of [PSR-11](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-11-container.md).
-Container-interop has been the test-bed of PSR-11. From v1.2, container-interop directly extends PSR-11 interfaces.
-Therefore, all containers implementing container-interop are now *de-facto* compatible with PSR-11.
-
-- Projects implementing container-interop interfaces are encouraged to directly implement PSR-11 interfaces instead.
-- Projects consuming container-interop interfaces are very strongly encouraged to directly type-hint on PSR-11 interfaces, in order to be compatible with PSR-11 containers that are not compatible with container-interop.
-
-Regarding the delegate lookup feature, that is present in container-interop and not in PSR-11, the feature is actually a design pattern. It is therefore not deprecated. Documentation regarding this design pattern will be migrated from this repository into a separate website in the future.
-
-## About
-
-*container-interop* tries to identify and standardize features in *container* objects (service locators,
-dependency injection containers, etc.) to achieve interoperability.
-
-Through discussions and trials, we try to create a standard, made of common interfaces but also recommendations.
-
-If PHP projects that provide container implementations begin to adopt these common standards, then PHP
-applications and projects that use containers can depend on the common interfaces instead of specific
-implementations. This facilitates a high-level of interoperability and flexibility that allows users to consume
-*any* container implementation that can be adapted to these interfaces.
-
-The work done in this project is not officially endorsed by the [PHP-FIG](http://www.php-fig.org/), but it is being
-worked on by members of PHP-FIG and other good developers. We adhere to the spirit and ideals of PHP-FIG, and hope
-this project will pave the way for one or more future PSRs.
-
-
-## Installation
-
-You can install this package through Composer:
-
-```json
-composer require container-interop/container-interop
-```
-
-The packages adheres to the [SemVer](http://semver.org/) specification, and there will be full backward compatibility
-between minor versions.
-
-## Standards
-
-### Available
-
-- [`ContainerInterface`](src/Interop/Container/ContainerInterface.php).
-[Description](docs/ContainerInterface.md) [Meta Document](docs/ContainerInterface-meta.md).
-Describes the interface of a container that exposes methods to read its entries.
-- [*Delegate lookup feature*](docs/Delegate-lookup.md).
-[Meta Document](docs/Delegate-lookup-meta.md).
-Describes the ability for a container to delegate the lookup of its dependencies to a third-party container. This
-feature lets several containers work together in a single application.
-
-### Proposed
-
-View open [request for comments](https://github.com/container-interop/container-interop/labels/RFC)
-
-## Compatible projects
-
-### Projects implementing `ContainerInterface`
-
-- [Acclimate](https://github.com/jeremeamia/acclimate-container): Adapters for
- Aura.Di, Laravel, Nette DI, Pimple, Symfony DI, ZF2 Service manager, ZF2
- Dependency injection and any container using `ArrayAccess`
-- [Aura.Di](https://github.com/auraphp/Aura.Di)
-- [auryn-container-interop](https://github.com/elazar/auryn-container-interop)
-- [Burlap](https://github.com/codeeverything/burlap)
-- [Chernozem](https://github.com/pyrsmk/Chernozem)
-- [Data Manager](https://github.com/chrismichaels84/data-manager)
-- [Disco](https://github.com/bitexpert/disco)
-- [InDI](https://github.com/idealogica/indi)
-- [League/Container](http://container.thephpleague.com/)
-- [Mouf](http://mouf-php.com)
-- [Njasm Container](https://github.com/njasm/container)
-- [PHP-DI](http://php-di.org)
-- [Picotainer](https://github.com/thecodingmachine/picotainer)
-- [PimpleInterop](https://github.com/moufmouf/pimple-interop)
-- [Pimple3-ContainerInterop](https://github.com/Sam-Burns/pimple3-containerinterop) (using Pimple v3)
-- [SitePoint Container](https://github.com/sitepoint/Container)
-- [Thruster Container](https://github.com/ThrusterIO/container) (PHP7 only)
-- [Ultra-Lite Container](https://github.com/ultra-lite/container)
-- [Unbox](https://github.com/mindplay-dk/unbox)
-- [XStatic](https://github.com/jeremeamia/xstatic)
-- [Zend\ServiceManager](https://github.com/zendframework/zend-servicemanager)
-- [Zit](https://github.com/inxilpro/Zit)
-
-### Projects implementing the *delegate lookup* feature
-
-- [Aura.Di](https://github.com/auraphp/Aura.Di)
-- [Burlap](https://github.com/codeeverything/burlap)
-- [Chernozem](https://github.com/pyrsmk/Chernozem)
-- [InDI](https://github.com/idealogica/indi)
-- [League/Container](http://container.thephpleague.com/)
-- [Mouf](http://mouf-php.com)
-- [Picotainer](https://github.com/thecodingmachine/picotainer)
-- [PHP-DI](http://php-di.org)
-- [PimpleInterop](https://github.com/moufmouf/pimple-interop)
-- [Ultra-Lite Container](https://github.com/ultra-lite/container)
-
-### Middlewares implementing `ContainerInterface`
-
-- [Alias-Container](https://github.com/thecodingmachine/alias-container): add
- aliases support to any container
-- [Prefixer-Container](https://github.com/thecodingmachine/prefixer-container):
- dynamically prefix identifiers
-- [Lazy-Container](https://github.com/snapshotpl/lazy-container): lazy services
-
-### Projects using `ContainerInterface`
-
-The list below contains only a sample of all the projects consuming `ContainerInterface`. For a more complete list have a look [here](http://packanalyst.com/class?q=Interop%5CContainer%5CContainerInterface).
-
-| | Downloads |
-| --- | --- |
-| [Adroit](https://github.com/bitexpert/adroit) |  |
-| [Behat](https://github.com/Behat/Behat/pull/974) |  |
-| [blast-facades](https://github.com/phpthinktank/blast-facades): Minimize complexity and represent dependencies as facades. |  |
-| [interop.silex.di](https://github.com/thecodingmachine/interop.silex.di): an extension to [Silex](http://silex.sensiolabs.org/) that adds support for any *container-interop* compatible container |  |
-| [mindplay/walkway](https://github.com/mindplay-dk/walkway): a modular request router |  |
-| [mindplay/middleman](https://github.com/mindplay-dk/middleman): minimalist PSR-7 middleware dispatcher |  |
-| [PHP-DI/Invoker](https://github.com/PHP-DI/Invoker): extensible and configurable invoker/dispatcher |  |
-| [Prophiler](https://github.com/fabfuel/prophiler) |  |
-| [Silly](https://github.com/mnapoli/silly): CLI micro-framework |  |
-| [Slim v3](https://github.com/slimphp/Slim) |  |
-| [Splash](http://mouf-php.com/packages/mouf/mvc.splash-common/version/8.0-dev/README.md) |  |
-| [Woohoo Labs. Harmony](https://github.com/woohoolabs/harmony): a flexible micro-framework |  |
-| [zend-expressive](https://github.com/zendframework/zend-expressive) |  |
-
-
-## Workflow
-
-Everyone is welcome to join and contribute.
-
-The general workflow looks like this:
-
-1. Someone opens a discussion (GitHub issue) to suggest an interface
-1. Feedback is gathered
-1. The interface is added to a development branch
-1. We release alpha versions so that the interface can be experimented with
-1. Discussions and edits ensue until the interface is deemed stable by a general consensus
-1. A new minor version of the package is released
-
-We try to not break BC by creating new interfaces instead of editing existing ones.
-
-While we currently work on interfaces, we are open to anything that might help towards interoperability, may that
-be code, best practices, etc.
+++ /dev/null
-{
- "name": "container-interop/container-interop",
- "type": "library",
- "description": "Promoting the interoperability of container objects (DIC, SL, etc.)",
- "homepage": "https://github.com/container-interop/container-interop",
- "license": "MIT",
- "autoload": {
- "psr-4": {
- "Interop\\Container\\": "src/Interop/Container/"
- }
- },
- "require": {
- "psr/container": "^1.0"
- }
-}
+++ /dev/null
-# ContainerInterface Meta Document
-
-## Introduction
-
-This document describes the process and discussions that lead to the `ContainerInterface`.
-Its goal is to explain the reasons behind each decision.
-
-## Goal
-
-The goal set by `ContainerInterface` is to standardize how frameworks and libraries make use of a
-container to obtain objects and parameters.
-
-By standardizing such a behavior, frameworks and libraries using the `ContainerInterface`
-could work with any compatible container.
-That would allow end users to choose their own container based on their own preferences.
-
-It is important to distinguish the two usages of a container:
-
-- configuring entries
-- fetching entries
-
-Most of the time, those two sides are not used by the same party.
-While it is often end users who tend to configure entries, it is generally the framework that fetch
-entries to build the application.
-
-This is why this interface focuses only on how entries can be fetched from a container.
-
-## Interface name
-
-The interface name has been thoroughly discussed and was decided by a vote.
-
-The list of options considered with their respective votes are:
-
-- `ContainerInterface`: +8
-- `ProviderInterface`: +2
-- `LocatorInterface`: 0
-- `ReadableContainerInterface`: -5
-- `ServiceLocatorInterface`: -6
-- `ObjectFactory`: -6
-- `ObjectStore`: -8
-- `ConsumerInterface`: -9
-
-[Full results of the vote](https://github.com/container-interop/container-interop/wiki/%231-interface-name:-Vote)
-
-The complete discussion can be read in [the issue #1](https://github.com/container-interop/container-interop/issues/1).
-
-## Interface methods
-
-The choice of which methods the interface would contain was made after a statistical analysis of existing containers.
-The results of this analysis are available [in this document](https://gist.github.com/mnapoli/6159681).
-
-The summary of the analysis showed that:
-
-- all containers offer a method to get an entry by its id
-- a large majority name such method `get()`
-- for all containers, the `get()` method has 1 mandatory parameter of type string
-- some containers have an optional additional argument for `get()`, but it doesn't have the same purpose between containers
-- a large majority of the containers offer a method to test if it can return an entry by its id
-- a majority name such method `has()`
-- for all containers offering `has()`, the method has exactly 1 parameter of type string
-- a large majority of the containers throw an exception rather than returning null when an entry is not found in `get()`
-- a large majority of the containers don't implement `ArrayAccess`
-
-The question of whether to include methods to define entries has been discussed in
-[issue #1](https://github.com/container-interop/container-interop/issues/1).
-It has been judged that such methods do not belong in the interface described here because it is out of its scope
-(see the "Goal" section).
-
-As a result, the `ContainerInterface` contains two methods:
-
-- `get()`, returning anything, with one mandatory string parameter. Should throw an exception if the entry is not found.
-- `has()`, returning a boolean, with one mandatory string parameter.
-
-### Number of parameters in `get()` method
-
-While `ContainerInterface` only defines one mandatory parameter in `get()`, it is not incompatible with
-existing containers that have additional optional parameters. PHP allows an implementation to offer more parameters
-as long as they are optional, because the implementation *does* satisfy the interface.
-
-This issue has been discussed in [issue #6](https://github.com/container-interop/container-interop/issues/6).
-
-### Type of the `$id` parameter
-
-The type of the `$id` parameter in `get()` and `has()` has been discussed in
-[issue #6](https://github.com/container-interop/container-interop/issues/6).
-While `string` is used in all the containers that were analyzed, it was suggested that allowing
-anything (such as objects) could allow containers to offer a more advanced query API.
-
-An example given was to use the container as an object builder. The `$id` parameter would then be an
-object that would describe how to create an instance.
-
-The conclusion of the discussion was that this was beyond the scope of getting entries from a container without
-knowing how the container provided them, and it was more fit for a factory.
-
-## Contributors
-
-Are listed here all people that contributed in the discussions or votes, by alphabetical order:
-
-- [Amy Stephen](https://github.com/AmyStephen)
-- [David Négrier](https://github.com/moufmouf)
-- [Don Gilbert](https://github.com/dongilbert)
-- [Jason Judge](https://github.com/judgej)
-- [Jeremy Lindblom](https://github.com/jeremeamia)
-- [Marco Pivetta](https://github.com/Ocramius)
-- [Matthieu Napoli](https://github.com/mnapoli)
-- [Paul M. Jones](https://github.com/pmjones)
-- [Stephan Hochdörfer](https://github.com/shochdoerfer)
-- [Taylor Otwell](https://github.com/taylorotwell)
-
-## Relevant links
-
-- [`ContainerInterface.php`](https://github.com/container-interop/container-interop/blob/master/src/Interop/Container/ContainerInterface.php)
-- [List of all issues](https://github.com/container-interop/container-interop/issues?labels=ContainerInterface&milestone=&page=1&state=closed)
-- [Vote for the interface name](https://github.com/container-interop/container-interop/wiki/%231-interface-name:-Vote)
+++ /dev/null
-Container interface
-===================
-
-This document describes a common interface for dependency injection containers.
-
-The goal set by `ContainerInterface` is to standardize how frameworks and libraries make use of a
-container to obtain objects and parameters (called *entries* in the rest of this document).
-
-The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
-"SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
-interpreted as described in [RFC 2119][].
-
-The word `implementor` in this document is to be interpreted as someone
-implementing the `ContainerInterface` in a dependency injection-related library or framework.
-Users of dependency injections containers (DIC) are referred to as `user`.
-
-[RFC 2119]: http://tools.ietf.org/html/rfc2119
-
-1. Specification
------------------
-
-### 1.1 Basics
-
-- The `Interop\Container\ContainerInterface` exposes two methods : `get` and `has`.
-
-- `get` takes one mandatory parameter: an entry identifier. It MUST be a string.
- A call to `get` can return anything (a *mixed* value), or throws an exception if the identifier
- is not known to the container. Two successive calls to `get` with the same
- identifier SHOULD return the same value. However, depending on the `implementor`
- design and/or `user` configuration, different values might be returned, so
- `user` SHOULD NOT rely on getting the same value on 2 successive calls.
- While `ContainerInterface` only defines one mandatory parameter in `get()`, implementations
- MAY accept additional optional parameters.
-
-- `has` takes one unique parameter: an entry identifier. It MUST return `true`
- if an entry identifier is known to the container and `false` if it is not.
- `has($id)` returning true does not mean that `get($id)` will not throw an exception.
- It does however mean that `get($id)` will not throw a `NotFoundException`.
-
-### 1.2 Exceptions
-
-Exceptions directly thrown by the container MUST implement the
-[`Interop\Container\Exception\ContainerException`](../src/Interop/Container/Exception/ContainerException.php).
-
-A call to the `get` method with a non-existing id SHOULD throw a
-[`Interop\Container\Exception\NotFoundException`](../src/Interop/Container/Exception/NotFoundException.php).
-
-### 1.3 Additional features
-
-This section describes additional features that MAY be added to a container. Containers are not
-required to implement these features to respect the ContainerInterface.
-
-#### 1.3.1 Delegate lookup feature
-
-The goal of the *delegate lookup* feature is to allow several containers to share entries.
-Containers implementing this feature can perform dependency lookups in other containers.
-
-Containers implementing this feature will offer a greater lever of interoperability
-with other containers. Implementation of this feature is therefore RECOMMENDED.
-
-A container implementing this feature:
-
-- MUST implement the `ContainerInterface`
-- MUST provide a way to register a delegate container (using a constructor parameter, or a setter,
- or any possible way). The delegate container MUST implement the `ContainerInterface`.
-
-When a container is configured to use a delegate container for dependencies:
-
-- Calls to the `get` method should only return an entry if the entry is part of the container.
- If the entry is not part of the container, an exception should be thrown
- (as requested by the `ContainerInterface`).
-- Calls to the `has` method should only return `true` if the entry is part of the container.
- If the entry is not part of the container, `false` should be returned.
-- If the fetched entry has dependencies, **instead** of performing
- the dependency lookup in the container, the lookup is performed on the *delegate container*.
-
-Important! By default, the lookup SHOULD be performed on the delegate container **only**, not on the container itself.
-
-It is however allowed for containers to provide exception cases for special entries, and a way to lookup
-into the same container (or another container) instead of the delegate container.
-
-2. Package
-----------
-
-The interfaces and classes described as well as relevant exception are provided as part of the
-[container-interop/container-interop](https://packagist.org/packages/container-interop/container-interop) package.
-
-3. `Interop\Container\ContainerInterface`
------------------------------------------
-
-```php
-<?php
-namespace Interop\Container;
-
-use Interop\Container\Exception\ContainerException;
-use Interop\Container\Exception\NotFoundException;
-
-/**
- * Describes the interface of a container that exposes methods to read its entries.
- */
-interface ContainerInterface
-{
- /**
- * Finds an entry of the container by its identifier and returns it.
- *
- * @param string $id Identifier of the entry to look for.
- *
- * @throws NotFoundException No entry was found for this identifier.
- * @throws ContainerException Error while retrieving the entry.
- *
- * @return mixed Entry.
- */
- public function get($id);
-
- /**
- * Returns true if the container can return an entry for the given identifier.
- * Returns false otherwise.
- *
- * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
- * It does however mean that `get($id)` will not throw a `NotFoundException`.
- *
- * @param string $id Identifier of the entry to look for.
- *
- * @return boolean
- */
- public function has($id);
-}
-```
-
-4. `Interop\Container\Exception\ContainerException`
----------------------------------------------------
-
-```php
-<?php
-namespace Interop\Container\Exception;
-
-/**
- * Base interface representing a generic exception in a container.
- */
-interface ContainerException
-{
-}
-```
-
-5. `Interop\Container\Exception\NotFoundException`
----------------------------------------------------
-
-```php
-<?php
-namespace Interop\Container\Exception;
-
-/**
- * No entry was found in the container.
- */
-interface NotFoundException extends ContainerException
-{
-}
-```
+++ /dev/null
-Delegate lookup feature Meta Document
-=====================================
-
-1. Summary
-----------
-
-This document describes the *delegate lookup feature*.
-Containers are not required to implement this feature to respect the `ContainerInterface`.
-However, containers implementing this feature will offer a greater lever of interoperability
-with other containers, allowing multiple containers to share entries in the same application.
-Implementation of this feature is therefore recommanded.
-
-2. Why Bother?
---------------
-
-The [`ContainerInterface`](../src/Interop/Container/ContainerInterface.php) ([meta doc](ContainerInterface.md))
-standardizes how frameworks and libraries make use of a container to obtain objects and parameters.
-
-By standardizing such a behavior, frameworks and libraries relying on the `ContainerInterface`
-could work with any compatible container.
-That would allow end users to choose their own container based on their own preferences.
-
-The `ContainerInterface` is also enough if we want to have several containers side-by-side in the same
-application. For instance, this is what the [CompositeContainer](https://github.com/jeremeamia/acclimate-container/blob/master/src/CompositeContainer.php)
-class of [Acclimate](https://github.com/jeremeamia/acclimate-container) is designed for:
-
-
-
-However, an instance in container 1 cannot reference an instance in container 2.
-
-It would be better if an instance of container 1 could reference an instance in container 2,
-and the opposite should be true.
-
-
-
-In the sample above, entry 1 in container 1 is referencing entry 3 in container 2.
-
-3. Scope
---------
-
-### 3.1 Goals
-
-The goal of the *delegate lookup* feature is to allow several containers to share entries.
-
-4. Approaches
--------------
-
-### 4.1 Chosen Approach
-
-Containers implementing this feature can perform dependency lookups in other containers.
-
-A container implementing this feature:
-
-- must implement the `ContainerInterface`
-- must provide a way to register a *delegate container* (using a constructor parameter, or a setter, or any
-possible way). The *delegate container* must implement the `ContainerInterface`.
-
-When a *delegate container* is configured on a container:
-
-- Calls to the `get` method should only return an entry if the entry is part of the container.
-If the entry is not part of the container, an exception should be thrown (as required in the `ContainerInterface`).
-- Calls to the `has` method should only return *true* if the entry is part of the container.
-If the entry is not part of the container, *false* should be returned.
- - Finally, the important part: if the entry we are fetching has dependencies,
-**instead** of perfoming the dependency lookup in the container, the lookup is performed on the *delegate container*.
-
-Important! By default, the lookup should be performed on the delegate container **only**, not on the container itself.
-
-It is however allowed for containers to provide exception cases for special entries, and a way to lookup into
-the same container (or another container) instead of the delegate container.
-
-### 4.2 Typical usage
-
-The *delegate container* will usually be a composite container. A composite container is a container that
-contains several other containers. When performing a lookup on a composite container, the inner containers are
-queried until one container returns an entry.
-An inner container implementing the *delegate lookup feature* will return entries it contains, but if these
-entries have dependencies, the dependencies lookup calls will be performed on the composite container, giving
-a chance to all containers to answer.
-
-Interestingly enough, the order in which containers are added in the composite container matters. Indeed,
-the first containers to be added in the composite container can "override" the entries of containers with
-lower priority.
-
-
-
-In the example above, "container 2" contains a controller "myController" and the controller is referencing an
-"entityManager" entry. "Container 1" contains also an entry named "entityManager".
-Without the *delegate lookup* feature, when requesting the "myController" instance to container 2, it would take
-in charge the instanciation of both entries.
-
-However, using the *delegate lookup* feature, here is what happens when we ask the composite container for the
-"myController" instance:
-
-- The composite container asks container 1 if if contains the "myController" instance. The answer is no.
-- The composite container asks container 2 if if contains the "myController" instance. The answer is yes.
-- The composite container performs a `get` call on container 2 for the "myController" instance.
-- Container 2 sees that "myController" has a dependency on "entityManager".
-- Container 2 delegates the lookup of "entityManager" to the composite container.
-- The composite container asks container 1 if if contains the "entityManager" instance. The answer is yes.
-- The composite container performs a `get` call on container 1 for the "entityManager" instance.
-
-In the end, we get a controller instanciated by container 2 that references an entityManager instanciated
-by container 1.
-
-### 4.3 Alternative: the fallback strategy
-
-The first proposed approach we tried was to perform all the lookups in the "local" container,
-and if a lookup fails in the container, to use the delegate container. In this scenario, the
-delegate container is used in "fallback" mode.
-
-This strategy has been described in @moufmouf blog post: http://mouf-php.com/container-interop-whats-next (solution 1).
-It was also discussed [here](https://github.com/container-interop/container-interop/pull/8#issuecomment-33570697) and
-[here](https://github.com/container-interop/container-interop/pull/20#issuecomment-56599631).
-
-Problems with this strategy:
-
-- Heavy problem regarding infinite loops
-- Unable to overload a container entry with the delegate container entry
-
-### 4.4 Alternative: force implementing an interface
-
-The first proposed approach was to develop a `ParentAwareContainerInterface` interface.
-It was proposed here: https://github.com/container-interop/container-interop/pull/8
-
-The interface would have had the behaviour of the delegate lookup feature but would have forced the addition of
-a `setParentContainter` method:
-
-```php
-interface ParentAwareContainerInterface extends ReadableContainerInterface {
- /**
- * Sets the parent container associated to that container. This container will call
- * the parent container to fetch dependencies.
- *
- * @param ContainerInterface $container
- */
- public function setParentContainer(ContainerInterface $container);
-}
-```
-
-The interface idea was first questioned by @Ocramius [here](https://github.com/container-interop/container-interop/pull/8#issuecomment-51721777).
-@Ocramius expressed the idea that an interface should not contain setters, otherwise, it is forcing implementation
-details on the class implementing the interface.
-Then @mnapoli made a proposal for a "convention" [here](https://github.com/container-interop/container-interop/pull/8#issuecomment-51841079),
-this idea was further discussed until all participants in the discussion agreed to remove the interface idea
-and replace it with a "standard" feature.
-
-**Pros:**
-
-If we had had an interface, we could have delegated the registration of the delegate/composite container to the
-the delegate/composite container itself.
-For instance:
-
-```php
-$containerA = new ContainerA();
-$containerB = new ContainerB();
-
-$compositeContainer = new CompositeContainer([$containerA, $containerB]);
-
-// The call to 'setParentContainer' is delegated to the CompositeContainer
-// It is not the responsibility of the user anymore.
-class CompositeContainer {
- ...
-
- public function __construct($containers) {
- foreach ($containers as $container) {
- if ($container instanceof ParentAwareContainerInterface) {
- $container->setParentContainer($this);
- }
- }
- ...
- }
-}
-
-```
-
-**Cons:**
-
-Cons have been extensively discussed [here](https://github.com/container-interop/container-interop/pull/8#issuecomment-51721777).
-Basically, forcing a setter into an interface is a bad idea. Setters are similar to constructor arguments,
-and it's a bad idea to standardize a constructor: how the delegate container is configured into a container is an implementation detail. This outweights the benefits of the interface.
-
-### 4.4 Alternative: no exception case for delegate lookups
-
-Originally, the proposed wording for delegate lookup calls was:
-
-> Important! The lookup MUST be performed on the delegate container **only**, not on the container itself.
-
-This was later replaced by:
-
-> Important! By default, the lookup SHOULD be performed on the delegate container **only**, not on the container itself.
->
-> It is however allowed for containers to provide exception cases for special entries, and a way to lookup
-> into the same container (or another container) instead of the delegate container.
-
-Exception cases have been allowed to avoid breaking dependencies with some services that must be provided
-by the container (on @njasm proposal). This was proposed here: https://github.com/container-interop/container-interop/pull/20#issuecomment-56597235
-
-### 4.5 Alternative: having one of the containers act as the composite container
-
-In real-life scenarios, we usually have a big framework (Symfony 2, Zend Framework 2, etc...) and we want to
-add another DI container to this container. Most of the time, the "big" framework will be responsible for
-creating the controller's instances, using it's own DI container. Until *container-interop* is fully adopted,
-the "big" framework will not be aware of the existence of a composite container that it should use instead
-of its own container.
-
-For this real-life use cases, @mnapoli and @moufmouf proposed to extend the "big" framework's DI container
-to make it act as a composite container.
-
-This has been discussed [here](https://github.com/container-interop/container-interop/pull/8#issuecomment-40367194)
-and [here](http://mouf-php.com/container-interop-whats-next#solution4).
-
-This was implemented in Symfony 2 using:
-
-- [interop.symfony.di](https://github.com/thecodingmachine/interop.symfony.di/tree/v0.1.0)
-- [framework interop](https://github.com/mnapoli/framework-interop/)
-
-This was implemented in Silex using:
-
-- [interop.silex.di](https://github.com/thecodingmachine/interop.silex.di)
-
-Having a container act as the composite container is not part of the delegate lookup standard because it is
-simply a temporary design pattern used to make existing frameworks that do not support yet ContainerInterop
-play nice with other DI containers.
-
-
-5. Implementations
-------------------
-
-The following projects already implement the delegate lookup feature:
-
-- [Mouf](http://mouf-php.com), through the [`setDelegateLookupContainer` method](https://github.com/thecodingmachine/mouf/blob/2.0/src/Mouf/MoufManager.php#L2120)
-- [PHP-DI](http://php-di.org/), through the [`$wrapperContainer` parameter of the constructor](https://github.com/mnapoli/PHP-DI/blob/master/src/DI/Container.php#L72)
-- [pimple-interop](https://github.com/moufmouf/pimple-interop), through the [`$container` parameter of the constructor](https://github.com/moufmouf/pimple-interop/blob/master/src/Interop/Container/Pimple/PimpleInterop.php#L62)
-
-6. People
----------
-
-Are listed here all people that contributed in the discussions, by alphabetical order:
-
-- [Alexandru Pătrănescu](https://github.com/drealecs)
-- [Ben Peachey](https://github.com/potherca)
-- [David Négrier](https://github.com/moufmouf)
-- [Jeremy Lindblom](https://github.com/jeremeamia)
-- [Marco Pivetta](https://github.com/Ocramius)
-- [Matthieu Napoli](https://github.com/mnapoli)
-- [Nelson J Morais](https://github.com/njasm)
-- [Phil Sturgeon](https://github.com/philsturgeon)
-- [Stephan Hochdörfer](https://github.com/shochdoerfer)
-
-7. Relevant Links
------------------
-
-_**Note:** Order descending chronologically._
-
-- [Pull request on the delegate lookup feature](https://github.com/container-interop/container-interop/pull/20)
-- [Pull request on the interface idea](https://github.com/container-interop/container-interop/pull/8)
-- [Original article exposing the delegate lookup idea along many others](http://mouf-php.com/container-interop-whats-next)
-
+++ /dev/null
-Delegate lookup feature
-=======================
-
-This document describes a standard for dependency injection containers.
-
-The goal set by the *delegate lookup* feature is to allow several containers to share entries.
-Containers implementing this feature can perform dependency lookups in other containers.
-
-Containers implementing this feature will offer a greater lever of interoperability
-with other containers. Implementation of this feature is therefore RECOMMENDED.
-
-The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
-"SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
-interpreted as described in [RFC 2119][].
-
-The word `implementor` in this document is to be interpreted as someone
-implementing the delegate lookup feature in a dependency injection-related library or framework.
-Users of dependency injections containers (DIC) are referred to as `user`.
-
-[RFC 2119]: http://tools.ietf.org/html/rfc2119
-
-1. Vocabulary
--------------
-
-In a dependency injection container, the container is used to fetch entries.
-Entries can have dependencies on other entries. Usually, these other entries are fetched by the container.
-
-The *delegate lookup* feature is the ability for a container to fetch dependencies in
-another container. In the rest of the document, the word "container" will reference the container
-implemented by the implementor. The word "delegate container" will reference the container we are
-fetching the dependencies from.
-
-2. Specification
-----------------
-
-A container implementing the *delegate lookup* feature:
-
-- MUST implement the [`ContainerInterface`](ContainerInterface.md)
-- MUST provide a way to register a delegate container (using a constructor parameter, or a setter,
- or any possible way). The delegate container MUST implement the [`ContainerInterface`](ContainerInterface.md).
-
-When a container is configured to use a delegate container for dependencies:
-
-- Calls to the `get` method should only return an entry if the entry is part of the container.
- If the entry is not part of the container, an exception should be thrown
- (as requested by the [`ContainerInterface`](ContainerInterface.md)).
-- Calls to the `has` method should only return `true` if the entry is part of the container.
- If the entry is not part of the container, `false` should be returned.
-- If the fetched entry has dependencies, **instead** of performing
- the dependency lookup in the container, the lookup is performed on the *delegate container*.
-
-Important: By default, the dependency lookups SHOULD be performed on the delegate container **only**, not on the container itself.
-
-It is however allowed for containers to provide exception cases for special entries, and a way to lookup
-into the same container (or another container) instead of the delegate container.
-
-3. Package / Interface
-----------------------
-
-This feature is not tied to any code, interface or package.
+++ /dev/null
-<?php
-/**
- * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
- */
-
-namespace Interop\Container;
-
-use Psr\Container\ContainerInterface as PsrContainerInterface;
-
-/**
- * Describes the interface of a container that exposes methods to read its entries.
- */
-interface ContainerInterface extends PsrContainerInterface
-{
-}
+++ /dev/null
-<?php
-/**
- * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
- */
-
-namespace Interop\Container\Exception;
-
-use Psr\Container\ContainerExceptionInterface as PsrContainerException;
-
-/**
- * Base interface representing a generic exception in a container.
- */
-interface ContainerException extends PsrContainerException
-{
-}
+++ /dev/null
-<?php
-/**
- * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
- */
-
-namespace Interop\Container\Exception;
-
-use Psr\Container\NotFoundExceptionInterface as PsrNotFoundException;
-
-/**
- * No entry was found in the container.
- */
-interface NotFoundException extends ContainerException, PsrNotFoundException
-{
-}
+++ /dev/null
-phpunit.xml
-composer.lock
-/vendor/
+++ /dev/null
-language: php
-
-env:
- matrix:
- - PIMPLE_EXT=no
- - PIMPLE_EXT=yes
- global:
- - REPORT_EXIT_STATUS=1
-
-php:
- - 5.3
- - 5.4
- - 5.5
- - 5.6
- - 7.0
- - 7.1
-
-before_script:
- - composer self-update
- - COMPOSER_ROOT_VERSION=dev-master composer install
- - if [ "$PIMPLE_EXT" == "yes" ]; then sh -c "cd ext/pimple && phpize && ./configure && make && sudo make install"; fi
- - if [ "$PIMPLE_EXT" == "yes" ]; then echo "extension=pimple.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`; fi
-
-script:
- - cd ext/pimple
- - if [ "$PIMPLE_EXT" == "yes" ]; then yes n | make test | tee output ; grep -E 'Tests failed +. +0' output; fi
- - if [ "$PIMPLE_EXT" == "yes" ]; then export SYMFONY_DEPRECATIONS_HELPER=weak; fi
- - cd ../..
- - ./vendor/bin/simple-phpunit
-
-matrix:
- include:
- - php: hhvm
- dist: trusty
- env: PIMPLE_EXT=no
- exclude:
- - php: 7.0
- env: PIMPLE_EXT=yes
- - php: 7.1
- env: PIMPLE_EXT=yes
+++ /dev/null
-* 3.2.3 (2017-XX-XX)
-
- * n/a
-
-* 3.2.2 (2017-07-23)
-
- * reverted extending a protected closure throws an exception (deprecated it instead)
-
-* 3.2.1 (2017-07-17)
-
- * fixed PHP error
-
-* 3.2.0 (2017-07-17)
-
- * added a PSR-11 service locator
- * added a PSR-11 wrapper
- * added ServiceIterator
- * fixed extending a protected closure (now throws InvalidServiceIdentifierException)
-
-* 3.1.0 (2017-07-03)
-
- * deprecated the C extension
- * added support for PSR-11 exceptions
-
-* 3.0.2 (2015-09-11)
-
- * refactored the C extension
- * minor non-significant changes
-
-* 3.0.1 (2015-07-30)
-
- * simplified some code
- * fixed a segfault in the C extension
-
-* 3.0.0 (2014-07-24)
-
- * removed the Pimple class alias (use Pimple\Container instead)
-
-* 2.1.1 (2014-07-24)
-
- * fixed compiler warnings for the C extension
- * fixed code when dealing with circular references
-
-* 2.1.0 (2014-06-24)
-
- * moved the Pimple to Pimple\Container (with a BC layer -- Pimple is now a
- deprecated alias which will be removed in Pimple 3.0)
- * added Pimple\ServiceProviderInterface (and Pimple::register())
-
-* 2.0.0 (2014-02-10)
-
- * changed extend to automatically re-assign the extended service and keep it as shared or factory
- (to keep BC, extend still returns the extended service)
- * changed services to be shared by default (use factory() for factory
- services)
-
-* 1.0.0
-
- * initial version
+++ /dev/null
-Copyright (c) 2009-2017 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.
+++ /dev/null
-Pimple
-======
-
-.. caution::
-
- This is the documentation for Pimple 3.x. If you are using Pimple 1.x, read
- the `Pimple 1.x documentation`_. Reading the Pimple 1.x code is also a good
- way to learn more about how to create a simple Dependency Injection
- Container (recent versions of Pimple are more focused on performance).
-
-Pimple is a small Dependency Injection Container for PHP.
-
-Installation
-------------
-
-Before using Pimple in your project, add it to your ``composer.json`` file:
-
-.. code-block:: bash
-
- $ ./composer.phar require pimple/pimple "^3.0"
-
-Usage
------
-
-Creating a container is a matter of creating a ``Container`` instance:
-
-.. code-block:: php
-
- use Pimple\Container;
-
- $container = new Container();
-
-As many other dependency injection containers, Pimple manages two different
-kind of data: **services** and **parameters**.
-
-Defining Services
-~~~~~~~~~~~~~~~~~
-
-A service is an object that does something as part of a larger system. Examples
-of services: a database connection, a templating engine, or a mailer. Almost
-any **global** object can be a service.
-
-Services are defined by **anonymous functions** that return an instance of an
-object:
-
-.. code-block:: php
-
- // define some services
- $container['session_storage'] = function ($c) {
- return new SessionStorage('SESSION_ID');
- };
-
- $container['session'] = function ($c) {
- return new Session($c['session_storage']);
- };
-
-Notice that the anonymous function has access to the current container
-instance, allowing references to other services or parameters.
-
-As objects are only created when you get them, the order of the definitions
-does not matter.
-
-Using the defined services is also very easy:
-
-.. code-block:: php
-
- // get the session object
- $session = $container['session'];
-
- // the above call is roughly equivalent to the following code:
- // $storage = new SessionStorage('SESSION_ID');
- // $session = new Session($storage);
-
-Defining Factory Services
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-By default, each time you get a service, Pimple returns the **same instance**
-of it. If you want a different instance to be returned for all calls, wrap your
-anonymous function with the ``factory()`` method
-
-.. code-block:: php
-
- $container['session'] = $container->factory(function ($c) {
- return new Session($c['session_storage']);
- });
-
-Now, each call to ``$container['session']`` returns a new instance of the
-session.
-
-Defining Parameters
-~~~~~~~~~~~~~~~~~~~
-
-Defining a parameter allows to ease the configuration of your container from
-the outside and to store global values:
-
-.. code-block:: php
-
- // define some parameters
- $container['cookie_name'] = 'SESSION_ID';
- $container['session_storage_class'] = 'SessionStorage';
-
-If you change the ``session_storage`` service definition like below:
-
-.. code-block:: php
-
- $container['session_storage'] = function ($c) {
- return new $c['session_storage_class']($c['cookie_name']);
- };
-
-You can now easily change the cookie name by overriding the
-``cookie_name`` parameter instead of redefining the service
-definition.
-
-Protecting Parameters
-~~~~~~~~~~~~~~~~~~~~~
-
-Because Pimple sees anonymous functions as service definitions, you need to
-wrap anonymous functions with the ``protect()`` method to store them as
-parameters:
-
-.. code-block:: php
-
- $container['random_func'] = $container->protect(function () {
- return rand();
- });
-
-Modifying Services after Definition
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-In some cases you may want to modify a service definition after it has been
-defined. You can use the ``extend()`` method to define additional code to be
-run on your service just after it is created:
-
-.. code-block:: php
-
- $container['session_storage'] = function ($c) {
- return new $c['session_storage_class']($c['cookie_name']);
- };
-
- $container->extend('session_storage', function ($storage, $c) {
- $storage->...();
-
- return $storage;
- });
-
-The first argument is the name of the service to extend, the second a function
-that gets access to the object instance and the container.
-
-Extending a Container
-~~~~~~~~~~~~~~~~~~~~~
-
-If you use the same libraries over and over, you might want to reuse some
-services from one project to the next one; package your services into a
-**provider** by implementing ``Pimple\ServiceProviderInterface``:
-
-.. code-block:: php
-
- use Pimple\Container;
-
- class FooProvider implements Pimple\ServiceProviderInterface
- {
- public function register(Container $pimple)
- {
- // register some services and parameters
- // on $pimple
- }
- }
-
-Then, register the provider on a Container:
-
-.. code-block:: php
-
- $pimple->register(new FooProvider());
-
-Fetching the Service Creation Function
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-When you access an object, Pimple automatically calls the anonymous function
-that you defined, which creates the service object for you. If you want to get
-raw access to this function, you can use the ``raw()`` method:
-
-.. code-block:: php
-
- $container['session'] = function ($c) {
- return new Session($c['session_storage']);
- };
-
- $sessionFunction = $container->raw('session');
-
-PSR-11 compatibility
---------------------
-
-For historical reasons, the ``Container`` class does not implement the PSR-11
-``ContainerInterface``. However, Pimple provides a helper class that will let
-you decouple your code from the Pimple container class.
-
-The PSR-11 container class
-~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-The ``Pimple\Psr11\Container`` class lets you access the content of an
-underlying Pimple container using ``Psr\Container\ContainerInterface``
-methods:
-
-.. code-block:: php
-
- use Pimple\Container;
- use Pimple\Psr11\Container as PsrContainer;
-
- $container = new Container();
- $container['service'] = function ($c) {
- return new Service();
- };
- $psr11 = new PsrContainer($container);
-
- $controller = function (PsrContainer $container) {
- $service = $container->get('service');
- };
- $controller($psr11);
-
-Using the PSR-11 ServiceLocator
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Sometimes, a service needs access to several other services without being sure
-that all of them will actually be used. In those cases, you may want the
-instantiation of the services to be lazy.
-
-The traditional solution is to inject the entire service container to get only
-the services really needed. However, this is not recommended because it gives
-services a too broad access to the rest of the application and it hides their
-actual dependencies.
-
-The ``ServiceLocator`` is intended to solve this problem by giving access to a
-set of predefined services while instantiating them only when actually needed.
-
-It also allows you to make your services available under a different name than
-the one used to register them. For instance, you may want to use an object
-that expects an instance of ``EventDispatcherInterface`` to be available under
-the name ``event_dispatcher`` while your event dispatcher has been
-registered under the name ``dispatcher``:
-
-.. code-block:: php
-
- use Monolog\Logger;
- use Pimple\Psr11\ServiceLocator;
- use Psr\Container\ContainerInterface;
- use Symfony\Component\EventDispatcher\EventDispatcher;
-
- class MyService
- {
- /**
- * "logger" must be an instance of Psr\Log\LoggerInterface
- * "event_dispatcher" must be an instance of Symfony\Component\EventDispatcher\EventDispatcherInterface
- */
- private $services;
-
- public function __construct(ContainerInterface $services)
- {
- $this->services = $services;
- }
- }
-
- $container['logger'] = function ($c) {
- return new Monolog\Logger();
- };
- $container['dispatcher'] = function () {
- return new EventDispatcher();
- };
-
- $container['service'] = function ($c) {
- $locator = new ServiceLocator($c, array('logger', 'event_dispatcher' => 'dispatcher'));
-
- return new MyService($locator);
- };
-
-Referencing a Collection of Services Lazily
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Passing a collection of services instances in an array may prove inefficient
-if the class that consumes the collection only needs to iterate over it at a
-later stage, when one of its method is called. It can also lead to problems
-if there is a circular dependency between one of the services stored in the
-collection and the class that consumes it.
-
-The ``ServiceIterator`` class helps you solve these issues. It receives a
-list of service names during instantiation and will retrieve the services
-when iterated over:
-
-.. code-block:: php
-
- use Pimple\Container;
- use Pimple\ServiceIterator;
-
- class AuthorizationService
- {
- private $voters;
-
- public function __construct($voters)
- {
- $this->voters = $voters;
- }
-
- public function canAccess($resource)
- {
- foreach ($this->voters as $voter) {
- if (true === $voter->canAccess($resource) {
- return true;
- }
- }
-
- return false;
- }
- }
-
- $container = new Container();
-
- $container['voter1'] = function ($c) {
- return new SomeVoter();
- }
- $container['voter2'] = function ($c) {
- return new SomeOtherVoter($c['auth']);
- }
- $container['auth'] = function ($c) {
- return new AuthorizationService(new ServiceIterator($c, array('voter1', 'voter2'));
- }
-
-.. _Pimple 1.x documentation: https://github.com/silexphp/Pimple/tree/1.1
+++ /dev/null
-{
- "name": "pimple/pimple",
- "type": "library",
- "description": "Pimple, a simple Dependency Injection Container",
- "keywords": ["dependency injection", "container"],
- "homepage": "http://pimple.sensiolabs.org",
- "license": "MIT",
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com"
- }
- ],
- "require": {
- "php": ">=5.3.0",
- "psr/container": "^1.0"
- },
- "require-dev": {
- "symfony/phpunit-bridge": "^3.2"
- },
- "autoload": {
- "psr-0": { "Pimple": "src/" }
- },
- "extra": {
- "branch-alias": {
- "dev-master": "3.2.x-dev"
- }
- }
-}
+++ /dev/null
-*.sw*
-.deps
-Makefile
-Makefile.fragments
-Makefile.global
-Makefile.objects
-acinclude.m4
-aclocal.m4
-build/
-config.cache
-config.guess
-config.h
-config.h.in
-config.log
-config.nice
-config.status
-config.sub
-configure
-configure.in
-install-sh
-libtool
-ltmain.sh
-missing
-mkinstalldirs
-run-tests.php
-*.loT
-.libs/
-modules/
-*.la
-*.lo
+++ /dev/null
-This is Pimple 2 implemented in C
-
-* PHP >= 5.3
-* Not tested under Windows, might work
-
-Install
-=======
-
- > phpize
- > ./configure
- > make
- > make install
+++ /dev/null
-dnl $Id$
-dnl config.m4 for extension pimple
-
-dnl Comments in this file start with the string 'dnl'.
-dnl Remove where necessary. This file will not work
-dnl without editing.
-
-dnl If your extension references something external, use with:
-
-dnl PHP_ARG_WITH(pimple, for pimple support,
-dnl Make sure that the comment is aligned:
-dnl [ --with-pimple Include pimple support])
-
-dnl Otherwise use enable:
-
-PHP_ARG_ENABLE(pimple, whether to enable pimple support,
-dnl Make sure that the comment is aligned:
-[ --enable-pimple Enable pimple support])
-
-if test "$PHP_PIMPLE" != "no"; then
- dnl Write more examples of tests here...
-
- dnl # --with-pimple -> check with-path
- dnl SEARCH_PATH="/usr/local /usr" # you might want to change this
- dnl SEARCH_FOR="/include/pimple.h" # you most likely want to change this
- dnl if test -r $PHP_PIMPLE/$SEARCH_FOR; then # path given as parameter
- dnl PIMPLE_DIR=$PHP_PIMPLE
- dnl else # search default path list
- dnl AC_MSG_CHECKING([for pimple files in default path])
- dnl for i in $SEARCH_PATH ; do
- dnl if test -r $i/$SEARCH_FOR; then
- dnl PIMPLE_DIR=$i
- dnl AC_MSG_RESULT(found in $i)
- dnl fi
- dnl done
- dnl fi
- dnl
- dnl if test -z "$PIMPLE_DIR"; then
- dnl AC_MSG_RESULT([not found])
- dnl AC_MSG_ERROR([Please reinstall the pimple distribution])
- dnl fi
-
- dnl # --with-pimple -> add include path
- dnl PHP_ADD_INCLUDE($PIMPLE_DIR/include)
-
- dnl # --with-pimple -> check for lib and symbol presence
- dnl LIBNAME=pimple # you may want to change this
- dnl LIBSYMBOL=pimple # you most likely want to change this
-
- dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
- dnl [
- dnl PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $PIMPLE_DIR/lib, PIMPLE_SHARED_LIBADD)
- dnl AC_DEFINE(HAVE_PIMPLELIB,1,[ ])
- dnl ],[
- dnl AC_MSG_ERROR([wrong pimple lib version or lib not found])
- dnl ],[
- dnl -L$PIMPLE_DIR/lib -lm
- dnl ])
- dnl
- dnl PHP_SUBST(PIMPLE_SHARED_LIBADD)
-
- PHP_NEW_EXTENSION(pimple, pimple.c, $ext_shared)
-fi
+++ /dev/null
-// $Id$
-// vim:ft=javascript
-
-// If your extension references something external, use ARG_WITH
-// ARG_WITH("pimple", "for pimple support", "no");
-
-// Otherwise, use ARG_ENABLE
-// ARG_ENABLE("pimple", "enable pimple support", "no");
-
-if (PHP_PIMPLE != "no") {
- EXTENSION("pimple", "pimple.c");
-}
-
+++ /dev/null
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2014 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.
- */
-
-#ifndef PHP_PIMPLE_H
-#define PHP_PIMPLE_H
-
-extern zend_module_entry pimple_module_entry;
-#define phpext_pimple_ptr &pimple_module_entry
-
-#ifdef PHP_WIN32
-# define PHP_PIMPLE_API __declspec(dllexport)
-#elif defined(__GNUC__) && __GNUC__ >= 4
-# define PHP_PIMPLE_API __attribute__ ((visibility("default")))
-#else
-# define PHP_PIMPLE_API
-#endif
-
-#ifdef ZTS
-#include "TSRM.h"
-#endif
-
-#define PIMPLE_VERSION "3.2.3-DEV"
-
-#define PIMPLE_NS "Pimple"
-#define PSR_CONTAINER_NS "Psr\\Container"
-#define PIMPLE_EXCEPTION_NS "Pimple\\Exception"
-
-#define PIMPLE_DEFAULT_ZVAL_CACHE_NUM 5
-#define PIMPLE_DEFAULT_ZVAL_VALUES_NUM 10
-
-#define PIMPLE_DEPRECATE do { \
- int er = EG(error_reporting); \
- EG(error_reporting) = 0;\
- php_error(E_DEPRECATED, "The Pimple C extension is deprecated since version 3.1 and will be removed in 4.0."); \
- EG(error_reporting) = er; \
-} while (0);
-
-zend_module_entry *get_module(void);
-
-PHP_MINIT_FUNCTION(pimple);
-PHP_MINFO_FUNCTION(pimple);
-
-PHP_METHOD(FrozenServiceException, __construct);
-PHP_METHOD(InvalidServiceIdentifierException, __construct);
-PHP_METHOD(UnknownIdentifierException, __construct);
-
-PHP_METHOD(Pimple, __construct);
-PHP_METHOD(Pimple, factory);
-PHP_METHOD(Pimple, protect);
-PHP_METHOD(Pimple, raw);
-PHP_METHOD(Pimple, extend);
-PHP_METHOD(Pimple, keys);
-PHP_METHOD(Pimple, register);
-PHP_METHOD(Pimple, offsetSet);
-PHP_METHOD(Pimple, offsetUnset);
-PHP_METHOD(Pimple, offsetGet);
-PHP_METHOD(Pimple, offsetExists);
-
-PHP_METHOD(PimpleClosure, invoker);
-
-typedef struct _pimple_bucket_value {
- zval *value; /* Must be the first element */
- zval *raw;
- zend_object_handle handle_num;
- enum {
- PIMPLE_IS_PARAM = 0,
- PIMPLE_IS_SERVICE = 2
- } type;
- zend_bool initialized;
- zend_fcall_info_cache fcc;
-} pimple_bucket_value;
-
-typedef struct _pimple_object {
- zend_object zobj;
- HashTable values;
- HashTable factories;
- HashTable protected;
-} pimple_object;
-
-typedef struct _pimple_closure_object {
- zend_object zobj;
- zval *callable;
- zval *factory;
-} pimple_closure_object;
-
-static const char sensiolabs_logo[] = "<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHYAAAAUCAMAAABvRTlyAAAAz1BMVEUAAAAAAAAAAAAsThWB5j4AAACD6T8AAACC6D+C6D6C6D+C6D4AAAAAAACC6D4AAAAAAACC6D8AAAAAAAAAAAAAAAAAAAAAAACC6D4AAAAAAAAAAACC6D4AAAAAAAAAAAAAAAAAAAAAAACC6D8AAACC6D4AAAAAAAAAAAAAAAAAAACC6D8AAACC6D6C6D+B6D+C6D+C6D+C6D8AAACC6D6C6D4AAACC6D/K/2KC6D+B6D6C6D6C6D+C6D8sTxUyWRhEeiEAAACC6D+C5z6B6D7drnEVAAAAQXRSTlMAE3oCNSUuDHFHzxaF9UFsu+irX+zlKzYimaJXktyOSFD6BolxqT7QGMMdarMIpuO28r9EolXKgR16OphfXYd4V14GtB4AAAMpSURBVEjHvVSJctowEF1jjME2RziMwUCoMfd9heZqG4n//6buLpJjkmYm03byZmxJa2nf6u2uQcG2bfhqRN4LoTKBzyGDm68M7mAwcOEdjo4zhA/Rf9Go/CVtTgiRhXfIC3EDH8F/eUX1/9KexRo+QgOdtHDsEe/sM7QT32/+K61Z1LFXcXJxN4pTbu1aTQUzuy2PIA0rDo0/0Aa5XFaJvKaVTrubywXvaa1Wq4Vu/Snr3Y7Aojh4VccwykW2N2oQ8wmjyut6+Q1t5ywIG5Npj1sh5E0B7YOzFDjfuRfaOh3O+MbbVNfTWS9COZk3Obd2su5d0a6IU9KLREbw8gEehWSr1r2sPWciXLG38r5NdW0xu9eioU87omjC9yNaMi5GNf6WppVSOqXCFkmCvMB3p9SROLoYQn5pDgQOujA1xjYvqH+plUdkwnmII8VxR/PKYkrfLLomhVlE3b/LhNbNr7hp0H2JaOc4v8dFB58HSsFTSafaqtY1sT3GO8wsy5rhokYPlRJdjPMajyYqTt1EHF/2uqSWQWmAjCUSmQ1MS3g8Btf1XOsy7YIC0CB1b5Xw1Vhba0zbxiCAQLH9TNPmHJXQUtJAN0KcDsoqLxsNvJrJExa7mKIdp2lRE2WexiS4pqWk/0jROlw6K6bV9YOBDGAuqMJ0bnuUKGB0L27bxgRhGEbzihbhxxXaQC88Vkwq8ldCi86RApWUb0Q+4VDosBCc+1s81lUdnBavH4Zp2mm3O44USwOfvSo9oBiwpFg71lMS1VKJLKljS3j9p+fOTvXXlsSNuEv6YPaZda9uRope0VJfKdo7fPiYfSmvFjXQbkhY0d9hCbBWIktRgEDieDhf1N3wbbkmNNgRy8hyl620yGQat/grV3HMpc2HDKTVmOPFz6ylPCKt/nXcAyV260jaAowwIW0YuBzrOgb/KrddZS9OmJaLgpWK4JX2DDuklcLZSDGcn8Vmx9YDNvT6UsjyBApRyFQVX7Vxm9TGxE16nmfRd8/zQoDmggQOTRh5Hv8pMt9Q/L2JmSwkMCE7dA4BuDjHJwfu0Om4QAhOjrN5XkIatglfiN/bUPdCQFjTYgAAAABJRU5ErkJggg==\">";
-
-static void pimple_exception_call_parent_constructor(zval *this_ptr, const char *format, const char *arg1 TSRMLS_DC);
-
-static int pimple_zval_to_pimpleval(zval *_zval, pimple_bucket_value *_pimple_bucket_value TSRMLS_DC);
-static int pimple_zval_is_valid_callback(zval *_zval, pimple_bucket_value *_pimple_bucket_value TSRMLS_DC);
-
-static void pimple_bucket_dtor(pimple_bucket_value *bucket);
-static void pimple_free_bucket(pimple_bucket_value *bucket);
-
-static zval *pimple_object_read_dimension(zval *object, zval *offset, int type TSRMLS_DC);
-static void pimple_object_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC);
-static int pimple_object_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC);
-static void pimple_object_unset_dimension(zval *object, zval *offset TSRMLS_DC);
-static zend_object_value pimple_object_create(zend_class_entry *ce TSRMLS_DC);
-static void pimple_free_object_storage(pimple_object *obj TSRMLS_DC);
-
-static void pimple_closure_free_object_storage(pimple_closure_object *obj TSRMLS_DC);
-static zend_object_value pimple_closure_object_create(zend_class_entry *ce TSRMLS_DC);
-static zend_function *pimple_closure_get_constructor(zval * TSRMLS_DC);
-static int pimple_closure_get_closure(zval *obj, zend_class_entry **ce_ptr, union _zend_function **fptr_ptr, zval **zobj_ptr TSRMLS_DC);
-
-#ifdef ZTS
-#define PIMPLE_G(v) TSRMG(pimple_globals_id, zend_pimple_globals *, v)
-#else
-#define PIMPLE_G(v) (pimple_globals.v)
-#endif
-
-#endif /* PHP_PIMPLE_H */
-
+++ /dev/null
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2014 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.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include "php.h"
-#include "php_ini.h"
-#include "ext/standard/info.h"
-#include "php_pimple.h"
-#include "pimple_compat.h"
-#include "zend_interfaces.h"
-#include "zend.h"
-#include "Zend/zend_closures.h"
-#include "ext/spl/spl_exceptions.h"
-#include "Zend/zend_exceptions.h"
-#include "main/php_output.h"
-#include "SAPI.h"
-
-static zend_class_entry *pimple_ce_PsrContainerInterface;
-static zend_class_entry *pimple_ce_PsrContainerExceptionInterface;
-static zend_class_entry *pimple_ce_PsrNotFoundExceptionInterface;
-
-static zend_class_entry *pimple_ce_ExpectedInvokableException;
-static zend_class_entry *pimple_ce_FrozenServiceException;
-static zend_class_entry *pimple_ce_InvalidServiceIdentifierException;
-static zend_class_entry *pimple_ce_UnknownIdentifierException;
-
-static zend_class_entry *pimple_ce;
-static zend_object_handlers pimple_object_handlers;
-static zend_class_entry *pimple_closure_ce;
-static zend_class_entry *pimple_serviceprovider_ce;
-static zend_object_handlers pimple_closure_object_handlers;
-static zend_internal_function pimple_closure_invoker_function;
-
-#define FETCH_DIM_HANDLERS_VARS pimple_object *pimple_obj = NULL; \
- ulong index; \
- pimple_obj = (pimple_object *)zend_object_store_get_object(object TSRMLS_CC); \
-
-#define PIMPLE_OBJECT_HANDLE_INHERITANCE_OBJECT_HANDLERS do { \
- if (ce != pimple_ce) { \
- zend_hash_find(&ce->function_table, ZEND_STRS("offsetget"), (void **)&function); \
- if (function->common.scope != ce) { /* if the function is not defined in this actual class */ \
- pimple_object_handlers.read_dimension = pimple_object_read_dimension; /* then overwrite the handler to use custom one */ \
- } \
- zend_hash_find(&ce->function_table, ZEND_STRS("offsetset"), (void **)&function); \
- if (function->common.scope != ce) { \
- pimple_object_handlers.write_dimension = pimple_object_write_dimension; \
- } \
- zend_hash_find(&ce->function_table, ZEND_STRS("offsetexists"), (void **)&function); \
- if (function->common.scope != ce) { \
- pimple_object_handlers.has_dimension = pimple_object_has_dimension; \
- } \
- zend_hash_find(&ce->function_table, ZEND_STRS("offsetunset"), (void **)&function); \
- if (function->common.scope != ce) { \
- pimple_object_handlers.unset_dimension = pimple_object_unset_dimension; \
- } \
- } else { \
- pimple_object_handlers.read_dimension = pimple_object_read_dimension; \
- pimple_object_handlers.write_dimension = pimple_object_write_dimension; \
- pimple_object_handlers.has_dimension = pimple_object_has_dimension; \
- pimple_object_handlers.unset_dimension = pimple_object_unset_dimension; \
- }\
- } while(0);
-
-#define PIMPLE_CALL_CB do { \
- zend_fcall_info_argn(&fci TSRMLS_CC, 1, &object); \
- fci.size = sizeof(fci); \
- fci.object_ptr = retval->fcc.object_ptr; \
- fci.function_name = retval->value; \
- fci.no_separation = 1; \
- fci.retval_ptr_ptr = &retval_ptr_ptr; \
-\
- zend_call_function(&fci, &retval->fcc TSRMLS_CC); \
- efree(fci.params); \
- if (EG(exception)) { \
- return EG(uninitialized_zval_ptr); \
- } \
- } while(0);
-
-
-/* Psr\Container\ContainerInterface */
-ZEND_BEGIN_ARG_INFO_EX(arginfo_pimple_PsrContainerInterface_get, 0, 0, 1)
-ZEND_ARG_INFO(0, id)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_pimple_PsrContainerInterface_has, 0, 0, 1)
-ZEND_ARG_INFO(0, id)
-ZEND_END_ARG_INFO()
-
-static const zend_function_entry pimple_ce_PsrContainerInterface_functions[] = {
- PHP_ABSTRACT_ME(ContainerInterface, get, arginfo_pimple_PsrContainerInterface_get)
- PHP_ABSTRACT_ME(ContainerInterface, has, arginfo_pimple_PsrContainerInterface_has)
- PHP_FE_END
-};
-
-/* Psr\Container\ContainerExceptionInterface */
-static const zend_function_entry pimple_ce_PsrContainerExceptionInterface_functions[] = {
- PHP_FE_END
-};
-
-/* Psr\Container\NotFoundExceptionInterface */
-static const zend_function_entry pimple_ce_PsrNotFoundExceptionInterface_functions[] = {
- PHP_FE_END
-};
-
-/* Pimple\Exception\FrozenServiceException */
-ZEND_BEGIN_ARG_INFO_EX(arginfo_FrozenServiceException___construct, 0, 0, 1)
-ZEND_ARG_INFO(0, id)
-ZEND_END_ARG_INFO()
-
-static const zend_function_entry pimple_ce_FrozenServiceException_functions[] = {
- PHP_ME(FrozenServiceException, __construct, arginfo_FrozenServiceException___construct, ZEND_ACC_PUBLIC)
- PHP_FE_END
-};
-
-/* Pimple\Exception\InvalidServiceIdentifierException */
-ZEND_BEGIN_ARG_INFO_EX(arginfo_InvalidServiceIdentifierException___construct, 0, 0, 1)
-ZEND_ARG_INFO(0, id)
-ZEND_END_ARG_INFO()
-
-static const zend_function_entry pimple_ce_InvalidServiceIdentifierException_functions[] = {
- PHP_ME(InvalidServiceIdentifierException, __construct, arginfo_InvalidServiceIdentifierException___construct, ZEND_ACC_PUBLIC)
- PHP_FE_END
-};
-
-/* Pimple\Exception\UnknownIdentifierException */
-ZEND_BEGIN_ARG_INFO_EX(arginfo_UnknownIdentifierException___construct, 0, 0, 1)
-ZEND_ARG_INFO(0, id)
-ZEND_END_ARG_INFO()
-
-static const zend_function_entry pimple_ce_UnknownIdentifierException_functions[] = {
- PHP_ME(UnknownIdentifierException, __construct, arginfo_UnknownIdentifierException___construct, ZEND_ACC_PUBLIC)
- PHP_FE_END
-};
-
-/* Pimple\Container */
-ZEND_BEGIN_ARG_INFO_EX(arginfo___construct, 0, 0, 0)
-ZEND_ARG_ARRAY_INFO(0, value, 0)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetset, 0, 0, 2)
-ZEND_ARG_INFO(0, offset)
-ZEND_ARG_INFO(0, value)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetget, 0, 0, 1)
-ZEND_ARG_INFO(0, offset)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetexists, 0, 0, 1)
-ZEND_ARG_INFO(0, offset)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetunset, 0, 0, 1)
-ZEND_ARG_INFO(0, offset)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_factory, 0, 0, 1)
-ZEND_ARG_INFO(0, callable)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_protect, 0, 0, 1)
-ZEND_ARG_INFO(0, callable)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_raw, 0, 0, 1)
-ZEND_ARG_INFO(0, id)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_extend, 0, 0, 2)
-ZEND_ARG_INFO(0, id)
-ZEND_ARG_INFO(0, callable)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_keys, 0, 0, 0)
-ZEND_END_ARG_INFO()
-
-ZEND_BEGIN_ARG_INFO_EX(arginfo_register, 0, 0, 1)
-ZEND_ARG_OBJ_INFO(0, provider, Pimple\\ServiceProviderInterface, 0)
-ZEND_ARG_ARRAY_INFO(0, values, 1)
-ZEND_END_ARG_INFO()
-
-static const zend_function_entry pimple_ce_functions[] = {
- PHP_ME(Pimple, __construct, arginfo___construct, ZEND_ACC_PUBLIC)
- PHP_ME(Pimple, factory, arginfo_factory, ZEND_ACC_PUBLIC)
- PHP_ME(Pimple, protect, arginfo_protect, ZEND_ACC_PUBLIC)
- PHP_ME(Pimple, raw, arginfo_raw, ZEND_ACC_PUBLIC)
- PHP_ME(Pimple, extend, arginfo_extend, ZEND_ACC_PUBLIC)
- PHP_ME(Pimple, keys, arginfo_keys, ZEND_ACC_PUBLIC)
- PHP_ME(Pimple, register, arginfo_register, ZEND_ACC_PUBLIC)
-
- PHP_ME(Pimple, offsetSet, arginfo_offsetset, ZEND_ACC_PUBLIC)
- PHP_ME(Pimple, offsetGet, arginfo_offsetget, ZEND_ACC_PUBLIC)
- PHP_ME(Pimple, offsetExists, arginfo_offsetexists, ZEND_ACC_PUBLIC)
- PHP_ME(Pimple, offsetUnset, arginfo_offsetunset, ZEND_ACC_PUBLIC)
- PHP_FE_END
-};
-
-/* Pimple\ServiceProviderInterface */
-ZEND_BEGIN_ARG_INFO_EX(arginfo_serviceprovider_register, 0, 0, 1)
-ZEND_ARG_OBJ_INFO(0, pimple, Pimple\\Container, 0)
-ZEND_END_ARG_INFO()
-
-static const zend_function_entry pimple_serviceprovider_iface_ce_functions[] = {
- PHP_ABSTRACT_ME(ServiceProviderInterface, register, arginfo_serviceprovider_register)
- PHP_FE_END
-};
-
-/* parent::__construct(sprintf("Something with %s", $arg1)) */
-static void pimple_exception_call_parent_constructor(zval *this_ptr, const char *format, const char *arg1 TSRMLS_DC)
-{
- zend_class_entry *ce = Z_OBJCE_P(this_ptr);
- char *message = NULL;
- int message_len;
- zval *constructor_arg;
-
- message_len = spprintf(&message, 0, format, arg1);
- ALLOC_INIT_ZVAL(constructor_arg);
- ZVAL_STRINGL(constructor_arg, message, message_len, 1);
-
- zend_call_method_with_1_params(&this_ptr, ce, &ce->parent->constructor, "__construct", NULL, constructor_arg);
-
- efree(message);
- zval_ptr_dtor(&constructor_arg);
-}
-
-/**
- * Pass a single string parameter to exception constructor and throw
- */
-static void pimple_throw_exception_string(zend_class_entry *ce, const char *message, zend_uint message_len TSRMLS_DC)
-{
- zval *exception, *param;
-
- ALLOC_INIT_ZVAL(exception);
- object_init_ex(exception, ce);
-
- ALLOC_INIT_ZVAL(param);
- ZVAL_STRINGL(param, message, message_len, 1);
-
- zend_call_method_with_1_params(&exception, ce, &ce->constructor, "__construct", NULL, param);
-
- zend_throw_exception_object(exception TSRMLS_CC);
-
- zval_ptr_dtor(¶m);
-}
-
-static void pimple_closure_free_object_storage(pimple_closure_object *obj TSRMLS_DC)
-{
- zend_object_std_dtor(&obj->zobj TSRMLS_CC);
- if (obj->factory) {
- zval_ptr_dtor(&obj->factory);
- }
- if (obj->callable) {
- zval_ptr_dtor(&obj->callable);
- }
- efree(obj);
-}
-
-static void pimple_free_object_storage(pimple_object *obj TSRMLS_DC)
-{
- zend_hash_destroy(&obj->factories);
- zend_hash_destroy(&obj->protected);
- zend_hash_destroy(&obj->values);
- zend_object_std_dtor(&obj->zobj TSRMLS_CC);
- efree(obj);
-}
-
-static void pimple_free_bucket(pimple_bucket_value *bucket)
-{
- if (bucket->raw) {
- zval_ptr_dtor(&bucket->raw);
- }
-}
-
-static zend_object_value pimple_closure_object_create(zend_class_entry *ce TSRMLS_DC)
-{
- zend_object_value retval;
- pimple_closure_object *pimple_closure_obj = NULL;
-
- pimple_closure_obj = ecalloc(1, sizeof(pimple_closure_object));
- ZEND_OBJ_INIT(&pimple_closure_obj->zobj, ce);
-
- pimple_closure_object_handlers.get_constructor = pimple_closure_get_constructor;
- retval.handlers = &pimple_closure_object_handlers;
- retval.handle = zend_objects_store_put(pimple_closure_obj, (zend_objects_store_dtor_t) zend_objects_destroy_object, (zend_objects_free_object_storage_t) pimple_closure_free_object_storage, NULL TSRMLS_CC);
-
- return retval;
-}
-
-static zend_function *pimple_closure_get_constructor(zval *obj TSRMLS_DC)
-{
- zend_error(E_ERROR, "Pimple\\ContainerClosure is an internal class and cannot be instantiated");
-
- return NULL;
-}
-
-static int pimple_closure_get_closure(zval *obj, zend_class_entry **ce_ptr, union _zend_function **fptr_ptr, zval **zobj_ptr TSRMLS_DC)
-{
- *zobj_ptr = obj;
- *ce_ptr = Z_OBJCE_P(obj);
- *fptr_ptr = (zend_function *)&pimple_closure_invoker_function;
-
- return SUCCESS;
-}
-
-static zend_object_value pimple_object_create(zend_class_entry *ce TSRMLS_DC)
-{
- zend_object_value retval;
- pimple_object *pimple_obj = NULL;
- zend_function *function = NULL;
-
- pimple_obj = emalloc(sizeof(pimple_object));
- ZEND_OBJ_INIT(&pimple_obj->zobj, ce);
-
- PIMPLE_OBJECT_HANDLE_INHERITANCE_OBJECT_HANDLERS
-
- retval.handlers = &pimple_object_handlers;
- retval.handle = zend_objects_store_put(pimple_obj, (zend_objects_store_dtor_t) zend_objects_destroy_object, (zend_objects_free_object_storage_t) pimple_free_object_storage, NULL TSRMLS_CC);
-
- zend_hash_init(&pimple_obj->factories, PIMPLE_DEFAULT_ZVAL_CACHE_NUM, NULL, (dtor_func_t)pimple_bucket_dtor, 0);
- zend_hash_init(&pimple_obj->protected, PIMPLE_DEFAULT_ZVAL_CACHE_NUM, NULL, (dtor_func_t)pimple_bucket_dtor, 0);
- zend_hash_init(&pimple_obj->values, PIMPLE_DEFAULT_ZVAL_VALUES_NUM, NULL, (dtor_func_t)pimple_bucket_dtor, 0);
-
- return retval;
-}
-
-static void pimple_object_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC)
-{
- FETCH_DIM_HANDLERS_VARS
-
- pimple_bucket_value pimple_value = {0}, *found_value = NULL;
- ulong hash;
-
- pimple_zval_to_pimpleval(value, &pimple_value TSRMLS_CC);
-
- if (!offset) {/* $p[] = 'foo' when not overloaded */
- zend_hash_next_index_insert(&pimple_obj->values, (void *)&pimple_value, sizeof(pimple_bucket_value), NULL);
- Z_ADDREF_P(value);
- return;
- }
-
- switch (Z_TYPE_P(offset)) {
- case IS_STRING:
- hash = zend_hash_func(Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1);
- zend_hash_quick_find(&pimple_obj->values, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, hash, (void **)&found_value);
- if (found_value && found_value->type == PIMPLE_IS_SERVICE && found_value->initialized == 1) {
- pimple_free_bucket(&pimple_value);
- pimple_throw_exception_string(pimple_ce_FrozenServiceException, Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC);
- return;
- }
- if (zend_hash_quick_update(&pimple_obj->values, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, hash, (void *)&pimple_value, sizeof(pimple_bucket_value), NULL) == FAILURE) {
- pimple_free_bucket(&pimple_value);
- return;
- }
- Z_ADDREF_P(value);
- break;
- case IS_DOUBLE:
- case IS_BOOL:
- case IS_LONG:
- if (Z_TYPE_P(offset) == IS_DOUBLE) {
- index = (ulong)Z_DVAL_P(offset);
- } else {
- index = Z_LVAL_P(offset);
- }
- zend_hash_index_find(&pimple_obj->values, index, (void **)&found_value);
- if (found_value && found_value->type == PIMPLE_IS_SERVICE && found_value->initialized == 1) {
- pimple_free_bucket(&pimple_value);
- convert_to_string(offset);
- pimple_throw_exception_string(pimple_ce_FrozenServiceException, Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC);
- return;
- }
- if (zend_hash_index_update(&pimple_obj->values, index, (void *)&pimple_value, sizeof(pimple_bucket_value), NULL) == FAILURE) {
- pimple_free_bucket(&pimple_value);
- return;
- }
- Z_ADDREF_P(value);
- break;
- case IS_NULL: /* $p[] = 'foo' when overloaded */
- zend_hash_next_index_insert(&pimple_obj->values, (void *)&pimple_value, sizeof(pimple_bucket_value), NULL);
- Z_ADDREF_P(value);
- break;
- default:
- pimple_free_bucket(&pimple_value);
- zend_error(E_WARNING, "Unsupported offset type");
- }
-}
-
-static void pimple_object_unset_dimension(zval *object, zval *offset TSRMLS_DC)
-{
- FETCH_DIM_HANDLERS_VARS
-
- switch (Z_TYPE_P(offset)) {
- case IS_STRING:
- zend_symtable_del(&pimple_obj->values, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1);
- zend_symtable_del(&pimple_obj->factories, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1);
- zend_symtable_del(&pimple_obj->protected, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1);
- break;
- case IS_DOUBLE:
- case IS_BOOL:
- case IS_LONG:
- if (Z_TYPE_P(offset) == IS_DOUBLE) {
- index = (ulong)Z_DVAL_P(offset);
- } else {
- index = Z_LVAL_P(offset);
- }
- zend_hash_index_del(&pimple_obj->values, index);
- zend_hash_index_del(&pimple_obj->factories, index);
- zend_hash_index_del(&pimple_obj->protected, index);
- break;
- default:
- zend_error(E_WARNING, "Unsupported offset type");
- }
-}
-
-static int pimple_object_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC)
-{
- FETCH_DIM_HANDLERS_VARS
-
- pimple_bucket_value *retval = NULL;
-
- switch (Z_TYPE_P(offset)) {
- case IS_STRING:
- if (zend_symtable_find(&pimple_obj->values, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **)&retval) == SUCCESS) {
- switch (check_empty) {
- case 0: /* isset */
- return 1; /* Differs from PHP behavior (Z_TYPE_P(retval->value) != IS_NULL;) */
- case 1: /* empty */
- default:
- return zend_is_true(retval->value);
- }
- }
- return 0;
- break;
- case IS_DOUBLE:
- case IS_BOOL:
- case IS_LONG:
- if (Z_TYPE_P(offset) == IS_DOUBLE) {
- index = (ulong)Z_DVAL_P(offset);
- } else {
- index = Z_LVAL_P(offset);
- }
- if (zend_hash_index_find(&pimple_obj->values, index, (void **)&retval) == SUCCESS) {
- switch (check_empty) {
- case 0: /* isset */
- return 1; /* Differs from PHP behavior (Z_TYPE_P(retval->value) != IS_NULL;)*/
- case 1: /* empty */
- default:
- return zend_is_true(retval->value);
- }
- }
- return 0;
- break;
- default:
- zend_error(E_WARNING, "Unsupported offset type");
- return 0;
- }
-}
-
-static zval *pimple_object_read_dimension(zval *object, zval *offset, int type TSRMLS_DC)
-{
- FETCH_DIM_HANDLERS_VARS
-
- pimple_bucket_value *retval = NULL;
- zend_fcall_info fci = {0};
- zval *retval_ptr_ptr = NULL;
-
- switch (Z_TYPE_P(offset)) {
- case IS_STRING:
- if (zend_symtable_find(&pimple_obj->values, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **)&retval) == FAILURE) {
- pimple_throw_exception_string(pimple_ce_UnknownIdentifierException, Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC);
-
- return EG(uninitialized_zval_ptr);
- }
- break;
- case IS_DOUBLE:
- case IS_BOOL:
- case IS_LONG:
- if (Z_TYPE_P(offset) == IS_DOUBLE) {
- index = (ulong)Z_DVAL_P(offset);
- } else {
- index = Z_LVAL_P(offset);
- }
- if (zend_hash_index_find(&pimple_obj->values, index, (void **)&retval) == FAILURE) {
- return EG(uninitialized_zval_ptr);
- }
- break;
- case IS_NULL: /* $p[][3] = 'foo' first dim access */
- return EG(uninitialized_zval_ptr);
- break;
- default:
- zend_error(E_WARNING, "Unsupported offset type");
- return EG(uninitialized_zval_ptr);
- }
-
- if(retval->type == PIMPLE_IS_PARAM) {
- return retval->value;
- }
-
- if (zend_hash_index_exists(&pimple_obj->protected, retval->handle_num)) {
- /* Service is protected, return the value every time */
- return retval->value;
- }
-
- if (zend_hash_index_exists(&pimple_obj->factories, retval->handle_num)) {
- /* Service is a factory, call it every time and never cache its result */
- PIMPLE_CALL_CB
- Z_DELREF_P(retval_ptr_ptr); /* fetch dim addr will increment refcount */
- return retval_ptr_ptr;
- }
-
- if (retval->initialized == 1) {
- /* Service has already been called, return its cached value */
- return retval->value;
- }
-
- ALLOC_INIT_ZVAL(retval->raw);
- MAKE_COPY_ZVAL(&retval->value, retval->raw);
-
- PIMPLE_CALL_CB
-
- retval->initialized = 1;
- zval_ptr_dtor(&retval->value);
- retval->value = retval_ptr_ptr;
-
- return retval->value;
-}
-
-static int pimple_zval_is_valid_callback(zval *_zval, pimple_bucket_value *_pimple_bucket_value TSRMLS_DC)
-{
- if (Z_TYPE_P(_zval) != IS_OBJECT) {
- return FAILURE;
- }
-
- if (_pimple_bucket_value->fcc.called_scope) {
- return SUCCESS;
- }
-
- if (Z_OBJ_HANDLER_P(_zval, get_closure) && Z_OBJ_HANDLER_P(_zval, get_closure)(_zval, &_pimple_bucket_value->fcc.calling_scope, &_pimple_bucket_value->fcc.function_handler, &_pimple_bucket_value->fcc.object_ptr TSRMLS_CC) == SUCCESS) {
- _pimple_bucket_value->fcc.called_scope = _pimple_bucket_value->fcc.calling_scope;
- return SUCCESS;
- } else {
- return FAILURE;
- }
-}
-
-static int pimple_zval_to_pimpleval(zval *_zval, pimple_bucket_value *_pimple_bucket_value TSRMLS_DC)
-{
- _pimple_bucket_value->value = _zval;
-
- if (Z_TYPE_P(_zval) != IS_OBJECT) {
- return PIMPLE_IS_PARAM;
- }
-
- if (pimple_zval_is_valid_callback(_zval, _pimple_bucket_value TSRMLS_CC) == SUCCESS) {
- _pimple_bucket_value->type = PIMPLE_IS_SERVICE;
- _pimple_bucket_value->handle_num = Z_OBJ_HANDLE_P(_zval);
- }
-
- return PIMPLE_IS_SERVICE;
-}
-
-static void pimple_bucket_dtor(pimple_bucket_value *bucket)
-{
- zval_ptr_dtor(&bucket->value);
- pimple_free_bucket(bucket);
-}
-
-PHP_METHOD(FrozenServiceException, __construct)
-{
- char *id = NULL;
- int id_len;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &id, &id_len) == FAILURE) {
- return;
- }
- pimple_exception_call_parent_constructor(getThis(), "Cannot override frozen service \"%s\".", id TSRMLS_CC);
-}
-
-PHP_METHOD(InvalidServiceIdentifierException, __construct)
-{
- char *id = NULL;
- int id_len;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &id, &id_len) == FAILURE) {
- return;
- }
- pimple_exception_call_parent_constructor(getThis(), "Identifier \"%s\" does not contain an object definition.", id TSRMLS_CC);
-}
-
-PHP_METHOD(UnknownIdentifierException, __construct)
-{
- char *id = NULL;
- int id_len;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &id, &id_len) == FAILURE) {
- return;
- }
- pimple_exception_call_parent_constructor(getThis(), "Identifier \"%s\" is not defined.", id TSRMLS_CC);
-}
-
-PHP_METHOD(Pimple, protect)
-{
- zval *protected = NULL;
- pimple_object *pobj = NULL;
- pimple_bucket_value bucket = {0};
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &protected) == FAILURE) {
- return;
- }
-
- if (pimple_zval_is_valid_callback(protected, &bucket TSRMLS_CC) == FAILURE) {
- pimple_free_bucket(&bucket);
- zend_throw_exception(pimple_ce_ExpectedInvokableException, "Callable is not a Closure or invokable object.", 0 TSRMLS_CC);
- return;
- }
-
- pimple_zval_to_pimpleval(protected, &bucket TSRMLS_CC);
- pobj = (pimple_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
-
- if (zend_hash_index_update(&pobj->protected, bucket.handle_num, (void *)&bucket, sizeof(pimple_bucket_value), NULL) == SUCCESS) {
- Z_ADDREF_P(protected);
- RETURN_ZVAL(protected, 1 , 0);
- } else {
- pimple_free_bucket(&bucket);
- }
- RETURN_FALSE;
-}
-
-PHP_METHOD(Pimple, raw)
-{
- zval *offset = NULL;
- pimple_object *pobj = NULL;
- pimple_bucket_value *value = NULL;
- ulong index;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &offset) == FAILURE) {
- return;
- }
-
- pobj = zend_object_store_get_object(getThis() TSRMLS_CC);
-
- switch (Z_TYPE_P(offset)) {
- case IS_STRING:
- if (zend_symtable_find(&pobj->values, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void *)&value) == FAILURE) {
- pimple_throw_exception_string(pimple_ce_UnknownIdentifierException, Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC);
- RETURN_NULL();
- }
- break;
- case IS_DOUBLE:
- case IS_BOOL:
- case IS_LONG:
- if (Z_TYPE_P(offset) == IS_DOUBLE) {
- index = (ulong)Z_DVAL_P(offset);
- } else {
- index = Z_LVAL_P(offset);
- }
- if (zend_hash_index_find(&pobj->values, index, (void *)&value) == FAILURE) {
- RETURN_NULL();
- }
- break;
- case IS_NULL:
- default:
- zend_error(E_WARNING, "Unsupported offset type");
- }
-
- if (value->raw) {
- RETVAL_ZVAL(value->raw, 1, 0);
- } else {
- RETVAL_ZVAL(value->value, 1, 0);
- }
-}
-
-PHP_METHOD(Pimple, extend)
-{
- zval *offset = NULL, *callable = NULL, *pimple_closure_obj = NULL;
- pimple_bucket_value bucket = {0}, *value = NULL;
- pimple_object *pobj = NULL;
- pimple_closure_object *pcobj = NULL;
- ulong index;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &offset, &callable) == FAILURE) {
- return;
- }
-
- pobj = zend_object_store_get_object(getThis() TSRMLS_CC);
-
- switch (Z_TYPE_P(offset)) {
- case IS_STRING:
- if (zend_symtable_find(&pobj->values, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void *)&value) == FAILURE) {
- pimple_throw_exception_string(pimple_ce_UnknownIdentifierException, Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC);
- RETURN_NULL();
- }
-
- if (value->type != PIMPLE_IS_SERVICE) {
- pimple_throw_exception_string(pimple_ce_InvalidServiceIdentifierException, Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC);
- RETURN_NULL();
- }
- if (zend_hash_index_exists(&pobj->protected, value->handle_num)) {
- int er = EG(error_reporting);
- EG(error_reporting) = 0;
- php_error(E_DEPRECATED, "How Pimple behaves when extending protected closures will be fixed in Pimple 4. Are you sure \"%s\" should be protected?", Z_STRVAL_P(offset));
- EG(error_reporting) = er;
- }
- break;
- case IS_DOUBLE:
- case IS_BOOL:
- case IS_LONG:
- if (Z_TYPE_P(offset) == IS_DOUBLE) {
- index = (ulong)Z_DVAL_P(offset);
- } else {
- index = Z_LVAL_P(offset);
- }
- if (zend_hash_index_find(&pobj->values, index, (void *)&value) == FAILURE) {
- convert_to_string(offset);
- pimple_throw_exception_string(pimple_ce_UnknownIdentifierException, Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC);
- RETURN_NULL();
- }
- if (value->type != PIMPLE_IS_SERVICE) {
- convert_to_string(offset);
- pimple_throw_exception_string(pimple_ce_InvalidServiceIdentifierException, Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC);
- RETURN_NULL();
- }
- if (zend_hash_index_exists(&pobj->protected, value->handle_num)) {
- int er = EG(error_reporting);
- EG(error_reporting) = 0;
- php_error(E_DEPRECATED, "How Pimple behaves when extending protected closures will be fixed in Pimple 4. Are you sure \"%ld\" should be protected?", index);
- EG(error_reporting) = er;
- }
- break;
- case IS_NULL:
- default:
- zend_error(E_WARNING, "Unsupported offset type");
- }
-
- if (pimple_zval_is_valid_callback(callable, &bucket TSRMLS_CC) == FAILURE) {
- pimple_free_bucket(&bucket);
- zend_throw_exception(pimple_ce_ExpectedInvokableException, "Extension service definition is not a Closure or invokable object.", 0 TSRMLS_CC);
- RETURN_NULL();
- }
- pimple_free_bucket(&bucket);
-
- ALLOC_INIT_ZVAL(pimple_closure_obj);
- object_init_ex(pimple_closure_obj, pimple_closure_ce);
-
- pcobj = zend_object_store_get_object(pimple_closure_obj TSRMLS_CC);
- pcobj->callable = callable;
- pcobj->factory = value->value;
- Z_ADDREF_P(callable);
- Z_ADDREF_P(value->value);
-
- if (zend_hash_index_exists(&pobj->factories, value->handle_num)) {
- pimple_zval_to_pimpleval(pimple_closure_obj, &bucket TSRMLS_CC);
- zend_hash_index_del(&pobj->factories, value->handle_num);
- zend_hash_index_update(&pobj->factories, bucket.handle_num, (void *)&bucket, sizeof(pimple_bucket_value), NULL);
- Z_ADDREF_P(pimple_closure_obj);
- }
-
- pimple_object_write_dimension(getThis(), offset, pimple_closure_obj TSRMLS_CC);
-
- RETVAL_ZVAL(pimple_closure_obj, 1, 1);
-}
-
-PHP_METHOD(Pimple, keys)
-{
- HashPosition pos;
- pimple_object *pobj = NULL;
- zval **value = NULL;
- zval *endval = NULL;
- char *str_index = NULL;
- int str_len;
- ulong num_index;
-
- if (zend_parse_parameters_none() == FAILURE) {
- return;
- }
-
- pobj = zend_object_store_get_object(getThis() TSRMLS_CC);
- array_init_size(return_value, zend_hash_num_elements(&pobj->values));
-
- zend_hash_internal_pointer_reset_ex(&pobj->values, &pos);
-
- while(zend_hash_get_current_data_ex(&pobj->values, (void **)&value, &pos) == SUCCESS) {
- MAKE_STD_ZVAL(endval);
- switch (zend_hash_get_current_key_ex(&pobj->values, &str_index, (uint *)&str_len, &num_index, 0, &pos)) {
- case HASH_KEY_IS_STRING:
- ZVAL_STRINGL(endval, str_index, str_len - 1, 1);
- zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &endval, sizeof(zval *), NULL);
- break;
- case HASH_KEY_IS_LONG:
- ZVAL_LONG(endval, num_index);
- zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &endval, sizeof(zval *), NULL);
- break;
- }
- zend_hash_move_forward_ex(&pobj->values, &pos);
- }
-}
-
-PHP_METHOD(Pimple, factory)
-{
- zval *factory = NULL;
- pimple_object *pobj = NULL;
- pimple_bucket_value bucket = {0};
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &factory) == FAILURE) {
- return;
- }
-
- if (pimple_zval_is_valid_callback(factory, &bucket TSRMLS_CC) == FAILURE) {
- pimple_free_bucket(&bucket);
- zend_throw_exception(pimple_ce_ExpectedInvokableException, "Service definition is not a Closure or invokable object.", 0 TSRMLS_CC);
- return;
- }
-
- pimple_zval_to_pimpleval(factory, &bucket TSRMLS_CC);
- pobj = (pimple_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
-
- if (zend_hash_index_update(&pobj->factories, bucket.handle_num, (void *)&bucket, sizeof(pimple_bucket_value), NULL) == SUCCESS) {
- Z_ADDREF_P(factory);
- RETURN_ZVAL(factory, 1 , 0);
- } else {
- pimple_free_bucket(&bucket);
- }
-
- RETURN_FALSE;
-}
-
-PHP_METHOD(Pimple, offsetSet)
-{
- zval *offset = NULL, *value = NULL;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &offset, &value) == FAILURE) {
- return;
- }
-
- pimple_object_write_dimension(getThis(), offset, value TSRMLS_CC);
-}
-
-PHP_METHOD(Pimple, offsetGet)
-{
- zval *offset = NULL, *retval = NULL;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &offset) == FAILURE) {
- return;
- }
-
- retval = pimple_object_read_dimension(getThis(), offset, 0 TSRMLS_CC);
-
- RETVAL_ZVAL(retval, 1, 0);
-}
-
-PHP_METHOD(Pimple, offsetUnset)
-{
- zval *offset = NULL;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &offset) == FAILURE) {
- return;
- }
-
- pimple_object_unset_dimension(getThis(), offset TSRMLS_CC);
-}
-
-PHP_METHOD(Pimple, offsetExists)
-{
- zval *offset = NULL;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &offset) == FAILURE) {
- return;
- }
-
- RETVAL_BOOL(pimple_object_has_dimension(getThis(), offset, 1 TSRMLS_CC));
-}
-
-PHP_METHOD(Pimple, register)
-{
- zval *provider;
- zval **data;
- zval *retval = NULL;
- zval key;
-
- HashTable *array = NULL;
- HashPosition pos;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|h", &provider, pimple_serviceprovider_ce, &array) == FAILURE) {
- return;
- }
-
- RETVAL_ZVAL(getThis(), 1, 0);
-
- zend_call_method_with_1_params(&provider, Z_OBJCE_P(provider), NULL, "register", &retval, getThis());
-
- if (retval) {
- zval_ptr_dtor(&retval);
- }
-
- if (!array) {
- return;
- }
-
- zend_hash_internal_pointer_reset_ex(array, &pos);
-
- while(zend_hash_get_current_data_ex(array, (void **)&data, &pos) == SUCCESS) {
- zend_hash_get_current_key_zval_ex(array, &key, &pos);
- pimple_object_write_dimension(getThis(), &key, *data TSRMLS_CC);
- zend_hash_move_forward_ex(array, &pos);
- }
-}
-
-PHP_METHOD(Pimple, __construct)
-{
- zval *values = NULL, **pData = NULL, offset;
- HashPosition pos;
- char *str_index = NULL;
- zend_uint str_length;
- ulong num_index;
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a!", &values) == FAILURE) {
- return;
- }
-
- PIMPLE_DEPRECATE
-
- if (!values) {
- return;
- }
-
- zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(values), &pos);
- while (zend_hash_has_more_elements_ex(Z_ARRVAL_P(values), &pos) == SUCCESS) {
- zend_hash_get_current_data_ex(Z_ARRVAL_P(values), (void **)&pData, &pos);
- zend_hash_get_current_key_ex(Z_ARRVAL_P(values), &str_index, &str_length, &num_index, 0, &pos);
- INIT_ZVAL(offset);
- if (zend_hash_get_current_key_type_ex(Z_ARRVAL_P(values), &pos) == HASH_KEY_IS_LONG) {
- ZVAL_LONG(&offset, num_index);
- } else {
- ZVAL_STRINGL(&offset, str_index, (str_length - 1), 0);
- }
- pimple_object_write_dimension(getThis(), &offset, *pData TSRMLS_CC);
- zend_hash_move_forward_ex(Z_ARRVAL_P(values), &pos);
- }
-}
-
-/*
- * This is PHP code snippet handling extend()s calls :
-
- $extended = function ($c) use ($callable, $factory) {
- return $callable($factory($c), $c);
- };
-
- */
-PHP_METHOD(PimpleClosure, invoker)
-{
- pimple_closure_object *pcobj = NULL;
- zval *arg = NULL, *retval = NULL, *newretval = NULL;
- zend_fcall_info fci = {0};
- zval **args[2];
-
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &arg) == FAILURE) {
- return;
- }
-
- pcobj = zend_object_store_get_object(getThis() TSRMLS_CC);
-
- fci.function_name = pcobj->factory;
- args[0] = &arg;
- zend_fcall_info_argp(&fci TSRMLS_CC, 1, args);
- fci.retval_ptr_ptr = &retval;
- fci.size = sizeof(fci);
-
- if (zend_call_function(&fci, NULL TSRMLS_CC) == FAILURE || EG(exception)) {
- efree(fci.params);
- return; /* Should here return default zval */
- }
-
- efree(fci.params);
- memset(&fci, 0, sizeof(fci));
- fci.size = sizeof(fci);
-
- fci.function_name = pcobj->callable;
- args[0] = &retval;
- args[1] = &arg;
- zend_fcall_info_argp(&fci TSRMLS_CC, 2, args);
- fci.retval_ptr_ptr = &newretval;
-
- if (zend_call_function(&fci, NULL TSRMLS_CC) == FAILURE || EG(exception)) {
- efree(fci.params);
- zval_ptr_dtor(&retval);
- return;
- }
-
- efree(fci.params);
- zval_ptr_dtor(&retval);
-
- RETVAL_ZVAL(newretval, 1 ,1);
-}
-
-PHP_MINIT_FUNCTION(pimple)
-{
- zend_class_entry tmp_ce_PsrContainerInterface, tmp_ce_PsrContainerExceptionInterface, tmp_ce_PsrNotFoundExceptionInterface;
- zend_class_entry tmp_ce_ExpectedInvokableException, tmp_ce_FrozenServiceException, tmp_ce_InvalidServiceIdentifierException, tmp_ce_UnknownIdentifierException;
- zend_class_entry tmp_pimple_ce, tmp_pimple_closure_ce, tmp_pimple_serviceprovider_iface_ce;
-
- /* Psr\Container namespace */
- INIT_NS_CLASS_ENTRY(tmp_ce_PsrContainerInterface, PSR_CONTAINER_NS, "ContainerInterface", pimple_ce_PsrContainerInterface_functions);
- INIT_NS_CLASS_ENTRY(tmp_ce_PsrContainerExceptionInterface, PSR_CONTAINER_NS, "ContainerExceptionInterface", pimple_ce_PsrContainerExceptionInterface_functions);
- INIT_NS_CLASS_ENTRY(tmp_ce_PsrNotFoundExceptionInterface, PSR_CONTAINER_NS, "NotFoundExceptionInterface", pimple_ce_PsrNotFoundExceptionInterface_functions);
-
- pimple_ce_PsrContainerInterface = zend_register_internal_interface(&tmp_ce_PsrContainerInterface TSRMLS_CC);
- pimple_ce_PsrContainerExceptionInterface = zend_register_internal_interface(&tmp_ce_PsrContainerExceptionInterface TSRMLS_CC);
- pimple_ce_PsrNotFoundExceptionInterface = zend_register_internal_interface(&tmp_ce_PsrNotFoundExceptionInterface TSRMLS_CC);
-
- zend_class_implements(pimple_ce_PsrNotFoundExceptionInterface TSRMLS_CC, 1, pimple_ce_PsrContainerExceptionInterface);
-
- /* Pimple\Exception namespace */
- INIT_NS_CLASS_ENTRY(tmp_ce_ExpectedInvokableException, PIMPLE_EXCEPTION_NS, "ExpectedInvokableException", NULL);
- INIT_NS_CLASS_ENTRY(tmp_ce_FrozenServiceException, PIMPLE_EXCEPTION_NS, "FrozenServiceException", pimple_ce_FrozenServiceException_functions);
- INIT_NS_CLASS_ENTRY(tmp_ce_InvalidServiceIdentifierException, PIMPLE_EXCEPTION_NS, "InvalidServiceIdentifierException", pimple_ce_InvalidServiceIdentifierException_functions);
- INIT_NS_CLASS_ENTRY(tmp_ce_UnknownIdentifierException, PIMPLE_EXCEPTION_NS, "UnknownIdentifierException", pimple_ce_UnknownIdentifierException_functions);
-
- pimple_ce_ExpectedInvokableException = zend_register_internal_class_ex(&tmp_ce_ExpectedInvokableException, spl_ce_InvalidArgumentException, NULL TSRMLS_CC);
- pimple_ce_FrozenServiceException = zend_register_internal_class_ex(&tmp_ce_FrozenServiceException, spl_ce_RuntimeException, NULL TSRMLS_CC);
- pimple_ce_InvalidServiceIdentifierException = zend_register_internal_class_ex(&tmp_ce_InvalidServiceIdentifierException, spl_ce_InvalidArgumentException, NULL TSRMLS_CC);
- pimple_ce_UnknownIdentifierException = zend_register_internal_class_ex(&tmp_ce_UnknownIdentifierException, spl_ce_InvalidArgumentException, NULL TSRMLS_CC);
-
- zend_class_implements(pimple_ce_ExpectedInvokableException TSRMLS_CC, 1, pimple_ce_PsrContainerExceptionInterface);
- zend_class_implements(pimple_ce_FrozenServiceException TSRMLS_CC, 1, pimple_ce_PsrContainerExceptionInterface);
- zend_class_implements(pimple_ce_InvalidServiceIdentifierException TSRMLS_CC, 1, pimple_ce_PsrContainerExceptionInterface);
- zend_class_implements(pimple_ce_UnknownIdentifierException TSRMLS_CC, 1, pimple_ce_PsrNotFoundExceptionInterface);
-
- /* Pimple namespace */
- INIT_NS_CLASS_ENTRY(tmp_pimple_ce, PIMPLE_NS, "Container", pimple_ce_functions);
- INIT_NS_CLASS_ENTRY(tmp_pimple_closure_ce, PIMPLE_NS, "ContainerClosure", NULL);
- INIT_NS_CLASS_ENTRY(tmp_pimple_serviceprovider_iface_ce, PIMPLE_NS, "ServiceProviderInterface", pimple_serviceprovider_iface_ce_functions);
-
- tmp_pimple_ce.create_object = pimple_object_create;
- tmp_pimple_closure_ce.create_object = pimple_closure_object_create;
-
- pimple_ce = zend_register_internal_class(&tmp_pimple_ce TSRMLS_CC);
- zend_class_implements(pimple_ce TSRMLS_CC, 1, zend_ce_arrayaccess);
-
- pimple_closure_ce = zend_register_internal_class(&tmp_pimple_closure_ce TSRMLS_CC);
- pimple_closure_ce->ce_flags |= ZEND_ACC_FINAL_CLASS;
-
- pimple_serviceprovider_ce = zend_register_internal_interface(&tmp_pimple_serviceprovider_iface_ce TSRMLS_CC);
-
- memcpy(&pimple_closure_object_handlers, zend_get_std_object_handlers(), sizeof(*zend_get_std_object_handlers()));
- pimple_object_handlers = std_object_handlers;
- pimple_closure_object_handlers.get_closure = pimple_closure_get_closure;
-
- pimple_closure_invoker_function.function_name = "Pimple closure internal invoker";
- pimple_closure_invoker_function.fn_flags |= ZEND_ACC_CLOSURE;
- pimple_closure_invoker_function.handler = ZEND_MN(PimpleClosure_invoker);
- pimple_closure_invoker_function.num_args = 1;
- pimple_closure_invoker_function.required_num_args = 1;
- pimple_closure_invoker_function.scope = pimple_closure_ce;
- pimple_closure_invoker_function.type = ZEND_INTERNAL_FUNCTION;
- pimple_closure_invoker_function.module = &pimple_module_entry;
-
- return SUCCESS;
-}
-
-PHP_MINFO_FUNCTION(pimple)
-{
- php_info_print_table_start();
- php_info_print_table_header(2, "SensioLabs Pimple C support", "enabled");
- php_info_print_table_row(2, "Pimple supported version", PIMPLE_VERSION);
- php_info_print_table_end();
-
- php_info_print_box_start(0);
- php_write((void *)ZEND_STRL("SensioLabs Pimple C support developed by Julien Pauli") TSRMLS_CC);
- if (!sapi_module.phpinfo_as_text) {
- php_write((void *)ZEND_STRL(sensiolabs_logo) TSRMLS_CC);
- }
- php_info_print_box_end();
-}
-
-zend_module_entry pimple_module_entry = {
- STANDARD_MODULE_HEADER,
- "pimple",
- NULL,
- PHP_MINIT(pimple),
- NULL,
- NULL,
- NULL,
- PHP_MINFO(pimple),
- PIMPLE_VERSION,
- STANDARD_MODULE_PROPERTIES
-};
-
-#ifdef COMPILE_DL_PIMPLE
-ZEND_GET_MODULE(pimple)
-#endif
+++ /dev/null
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2014 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.
- */
-
-#ifndef PIMPLE_COMPAT_H_
-#define PIMPLE_COMPAT_H_
-
-#include "Zend/zend_extensions.h" /* for ZEND_EXTENSION_API_NO */
-
-#define PHP_5_0_X_API_NO 220040412
-#define PHP_5_1_X_API_NO 220051025
-#define PHP_5_2_X_API_NO 220060519
-#define PHP_5_3_X_API_NO 220090626
-#define PHP_5_4_X_API_NO 220100525
-#define PHP_5_5_X_API_NO 220121212
-#define PHP_5_6_X_API_NO 220131226
-
-#define IS_PHP_56 ZEND_EXTENSION_API_NO == PHP_5_6_X_API_NO
-#define IS_AT_LEAST_PHP_56 ZEND_EXTENSION_API_NO >= PHP_5_6_X_API_NO
-
-#define IS_PHP_55 ZEND_EXTENSION_API_NO == PHP_5_5_X_API_NO
-#define IS_AT_LEAST_PHP_55 ZEND_EXTENSION_API_NO >= PHP_5_5_X_API_NO
-
-#define IS_PHP_54 ZEND_EXTENSION_API_NO == PHP_5_4_X_API_NO
-#define IS_AT_LEAST_PHP_54 ZEND_EXTENSION_API_NO >= PHP_5_4_X_API_NO
-
-#define IS_PHP_53 ZEND_EXTENSION_API_NO == PHP_5_3_X_API_NO
-#define IS_AT_LEAST_PHP_53 ZEND_EXTENSION_API_NO >= PHP_5_3_X_API_NO
-
-#if IS_PHP_53
-#define object_properties_init(obj, ce) do { \
- zend_hash_copy(obj->properties, &ce->default_properties, zval_copy_property_ctor(ce), NULL, sizeof(zval *)); \
- } while (0);
-#endif
-
-#define ZEND_OBJ_INIT(obj, ce) do { \
- zend_object_std_init(obj, ce TSRMLS_CC); \
- object_properties_init((obj), (ce)); \
- } while(0);
-
-#if IS_PHP_53 || IS_PHP_54
-static void zend_hash_get_current_key_zval_ex(const HashTable *ht, zval *key, HashPosition *pos) {
- Bucket *p;
-
- p = pos ? (*pos) : ht->pInternalPointer;
-
- if (!p) {
- Z_TYPE_P(key) = IS_NULL;
- } else if (p->nKeyLength) {
- Z_TYPE_P(key) = IS_STRING;
- Z_STRVAL_P(key) = estrndup(p->arKey, p->nKeyLength - 1);
- Z_STRLEN_P(key) = p->nKeyLength - 1;
- } else {
- Z_TYPE_P(key) = IS_LONG;
- Z_LVAL_P(key) = p->h;
- }
-}
-#endif
-
-#endif /* PIMPLE_COMPAT_H_ */
+++ /dev/null
---TEST--
-Test for read_dim/write_dim handlers
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-$p = new Pimple\Container();
-$p[42] = 'foo';
-$p['foo'] = 42;
-
-echo $p[42];
-echo "\n";
-echo $p['foo'];
-echo "\n";
-try {
- var_dump($p['nonexistant']);
- echo "Exception excpected";
-} catch (InvalidArgumentException $e) { }
-
-$p[54.2] = 'foo2';
-echo $p[54];
-echo "\n";
-$p[242.99] = 'foo99';
-echo $p[242];
-
-echo "\n";
-
-$p[5] = 'bar';
-$p[5] = 'baz';
-echo $p[5];
-
-echo "\n";
-
-$p['str'] = 'str';
-$p['str'] = 'strstr';
-echo $p['str'];
-?>
-
---EXPECTF--
-foo
-42
-foo2
-foo99
-baz
-strstr
\ No newline at end of file
+++ /dev/null
---TEST--
-Test for constructor
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-$p = new Pimple\Container();
-var_dump($p[42]);
-
-$p = new Pimple\Container(array(42=>'foo'));
-var_dump($p[42]);
-?>
---EXPECT--
-NULL
-string(3) "foo"
+++ /dev/null
---TEST--
-Test empty dimensions
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-$p = new Pimple\Container();
-$p[] = 42;
-var_dump($p[0]);
-$p[41] = 'foo';
-$p[] = 'bar';
-var_dump($p[42]);
-?>
---EXPECT--
-int(42)
-string(3) "bar"
\ No newline at end of file
+++ /dev/null
---TEST--
-Test has/unset dim handlers
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-$p = new Pimple\Container();
-$p[] = 42;
-var_dump($p[0]);
-unset($p[0]);
-var_dump($p[0]);
-$p['foo'] = 'bar';
-var_dump(isset($p['foo']));
-unset($p['foo']);
-try {
- var_dump($p['foo']);
- echo "Excpected exception";
-} catch (InvalidArgumentException $e) { }
-var_dump(isset($p['bar']));
-$p['bar'] = NULL;
-var_dump(isset($p['bar']));
-var_dump(empty($p['bar']));
-?>
---EXPECT--
-int(42)
-NULL
-bool(true)
-bool(false)
-bool(true)
-bool(true)
\ No newline at end of file
+++ /dev/null
---TEST--
-Test simple class inheritance
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-class MyPimple extends Pimple\Container
-{
- public $someAttr = 'fooAttr';
-
- public function offsetget($o)
- {
- var_dump("hit");
- return parent::offsetget($o);
- }
-}
-
-$p = new MyPimple;
-$p[42] = 'foo';
-echo $p[42];
-echo "\n";
-echo $p->someAttr;
-?>
---EXPECT--
-string(3) "hit"
-foo
-fooAttr
\ No newline at end of file
+++ /dev/null
---TEST--
-Test complex class inheritance
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-class MyPimple extends Pimple\Container
-{
- public function offsetget($o)
- {
- var_dump("hit offsetget in " . __CLASS__);
- return parent::offsetget($o);
- }
-}
-
-class TestPimple extends MyPimple
-{
- public function __construct($values)
- {
- array_shift($values);
- parent::__construct($values);
- }
-
- public function offsetget($o)
- {
- var_dump('hit offsetget in ' . __CLASS__);
- return parent::offsetget($o);
- }
-
- public function offsetset($o, $v)
- {
- var_dump('hit offsetset');
- return parent::offsetset($o, $v);
- }
-}
-
-$defaultValues = array('foo' => 'bar', 88 => 'baz');
-
-$p = new TestPimple($defaultValues);
-$p[42] = 'foo';
-var_dump($p[42]);
-var_dump($p[0]);
-?>
---EXPECT--
-string(13) "hit offsetset"
-string(27) "hit offsetget in TestPimple"
-string(25) "hit offsetget in MyPimple"
-string(3) "foo"
-string(27) "hit offsetget in TestPimple"
-string(25) "hit offsetget in MyPimple"
-string(3) "baz"
\ No newline at end of file
+++ /dev/null
---TEST--
-Test for read_dim/write_dim handlers
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-$p = new Pimple\Container();
-$p[42] = 'foo';
-$p['foo'] = 42;
-
-echo $p[42];
-echo "\n";
-echo $p['foo'];
-echo "\n";
-try {
- var_dump($p['nonexistant']);
- echo "Exception excpected";
-} catch (InvalidArgumentException $e) { }
-?>
---EXPECTF--
-foo
-42
\ No newline at end of file
+++ /dev/null
---TEST--
-Test frozen services
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-$p = new Pimple\Container();
-$p[42] = 'foo';
-$p[42] = 'bar';
-
-$p['foo'] = function () { };
-$p['foo'] = function () { };
-
-$a = $p['foo'];
-
-try {
- $p['foo'] = function () { };
- echo "Exception excpected";
-} catch (RuntimeException $e) { }
-
-$p[42] = function() { };
-$a = $p[42];
-
-try {
- $p[42] = function () { };
- echo "Exception excpected";
-} catch (RuntimeException $e) { }
-?>
---EXPECTF--
+++ /dev/null
---TEST--
-Test service is called as callback, and only once
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-$p = new Pimple\Container();
-$p['foo'] = function($arg) use ($p) { var_dump($p === $arg); };
-$a = $p['foo'];
-$b = $p['foo']; /* should return not calling the callback */
-?>
---EXPECTF--
-bool(true)
\ No newline at end of file
+++ /dev/null
---TEST--
-Test service is called as callback for every callback type
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-function callme()
-{
- return 'called';
-}
-
-$a = function() { return 'called'; };
-
-class Foo
-{
- public static function bar()
- {
- return 'called';
- }
-}
-
-$p = new Pimple\Container();
-$p['foo'] = 'callme';
-echo $p['foo'] . "\n";
-
-$p['bar'] = $a;
-echo $p['bar'] . "\n";
-
-$p['baz'] = "Foo::bar";
-echo $p['baz'] . "\n";
-
-$p['foobar'] = array('Foo', 'bar');
-var_dump($p['foobar']);
-
-?>
---EXPECTF--
-callme
-called
-Foo::bar
-array(2) {
- [0]=>
- string(3) "Foo"
- [1]=>
- string(3) "bar"
-}
\ No newline at end of file
+++ /dev/null
---TEST--
-Test service callback throwing an exception
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-class CallBackException extends RuntimeException { }
-
-$p = new Pimple\Container();
-$p['foo'] = function () { throw new CallBackException; };
-try {
- echo $p['foo'] . "\n";
- echo "should not come here";
-} catch (CallBackException $e) {
- echo "all right!";
-}
-?>
---EXPECTF--
-all right!
\ No newline at end of file
+++ /dev/null
---TEST--
-Test service factory
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-
-$p = new Pimple\Container();
-
-$p->factory($f = function() { var_dump('called-1'); return 'ret-1';});
-
-$p[] = $f;
-
-$p[] = function () { var_dump('called-2'); return 'ret-2'; };
-
-var_dump($p[0]);
-var_dump($p[0]);
-var_dump($p[1]);
-var_dump($p[1]);
-?>
---EXPECTF--
-string(8) "called-1"
-string(5) "ret-1"
-string(8) "called-1"
-string(5) "ret-1"
-string(8) "called-2"
-string(5) "ret-2"
-string(5) "ret-2"
\ No newline at end of file
+++ /dev/null
---TEST--
-Test keys()
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-
-$p = new Pimple\Container();
-
-var_dump($p->keys());
-
-$p['foo'] = 'bar';
-$p[] = 'foo';
-
-var_dump($p->keys());
-
-unset($p['foo']);
-
-var_dump($p->keys());
-?>
---EXPECTF--
-array(0) {
-}
-array(2) {
- [0]=>
- string(3) "foo"
- [1]=>
- int(0)
-}
-array(1) {
- [0]=>
- int(0)
-}
\ No newline at end of file
+++ /dev/null
---TEST--
-Test raw()
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-
-$p = new Pimple\Container();
-$f = function () { var_dump('called-2'); return 'ret-2'; };
-
-$p['foo'] = $f;
-$p[42] = $f;
-
-var_dump($p['foo']);
-var_dump($p->raw('foo'));
-var_dump($p[42]);
-
-unset($p['foo']);
-
-try {
- $p->raw('foo');
- echo "expected exception";
-} catch (InvalidArgumentException $e) { }
---EXPECTF--
-string(8) "called-2"
-string(5) "ret-2"
-object(Closure)#%i (0) {
-}
-string(8) "called-2"
-string(5) "ret-2"
\ No newline at end of file
+++ /dev/null
---TEST--
-Test protect()
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-
-$p = new Pimple\Container();
-$f = function () { return 'foo'; };
-$p['foo'] = $f;
-
-$p->protect($f);
-
-var_dump($p['foo']);
---EXPECTF--
-object(Closure)#%i (0) {
-}
\ No newline at end of file
+++ /dev/null
---TEST--
-Test extend()
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-/*
- This is part of Pimple::extend() code :
-
- $extended = function ($c) use ($callable, $factory) {
- return $callable($factory($c), $c);
- };
-*/
-
-$p = new Pimple\Container();
-$p[12] = function ($v) { var_dump($v); return 'foo';}; /* $factory in code above */
-
-$c = $p->extend(12, function ($w) { var_dump($w); return 'bar'; }); /* $callable in code above */
-
-var_dump($c('param'));
---EXPECTF--
-string(5) "param"
-string(3) "foo"
-string(3) "bar"
\ No newline at end of file
+++ /dev/null
---TEST--
-Test extend() with exception in service extension
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-
-$p = new Pimple\Container();
-$p[12] = function ($v) { return 'foo';};
-
-$c = $p->extend(12, function ($w) { throw new BadMethodCallException; });
-
-try {
- $p[12];
- echo "Exception expected";
-} catch (BadMethodCallException $e) { }
---EXPECTF--
+++ /dev/null
---TEST--
-Test extend() with exception in service factory
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-
-$p = new Pimple\Container();
-$p[12] = function ($v) { throw new BadMethodCallException; };
-
-$c = $p->extend(12, function ($w) { return 'foobar'; });
-
-try {
- $p[12];
- echo "Exception expected";
-} catch (BadMethodCallException $e) { }
---EXPECTF--
+++ /dev/null
---TEST--
-Test register()
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-
-class Foo implements Pimple\ServiceProviderInterface
-{
- public function register(Pimple\Container $p)
- {
- var_dump($p);
- }
-}
-
-$p = new Pimple\Container();
-$p->register(new Foo, array(42 => 'bar'));
-
-var_dump($p[42]);
---EXPECTF--
-object(Pimple\Container)#1 (0) {
-}
-string(3) "bar"
\ No newline at end of file
+++ /dev/null
---TEST--
-Test register() returns static and is a fluent interface
---SKIPIF--
-<?php if (!extension_loaded("pimple")) print "skip"; ?>
---FILE--
-<?php
-
-class Foo implements Pimple\ServiceProviderInterface
-{
- public function register(Pimple\Container $p)
- {
- }
-}
-
-$p = new Pimple\Container();
-var_dump($p === $p->register(new Foo));
---EXPECTF--
-bool(true)
+++ /dev/null
-<?php
-
-if (!class_exists('Pimple\Container')) {
- require_once __DIR__ . '/../../../src/Pimple/Container.php';
-} else {
- echo "pimple-c extension detected, using...\n\n";
-}
-
-$time = microtime(true);
-
-function foo() { }
-$factory = function () { };
-
-for ($i=0; $i<10000; $i++) {
-
-$p = new Pimple\Container;
-
-$p['foo'] = 'bar';
-
-if (!isset($p[3])) {
- $p[3] = $p['foo'];
- $p[] = 'bar';
-}
-
-$p[2] = 42;
-
-if (isset($p[2])) {
- unset($p[2]);
-}
-
-$p[42] = $p['foo'];
-
-$p['cb'] = function($arg) { };
-
-$p[] = $p['cb'];
-
-echo $p['cb'];
-echo $p['cb'];
-echo $p['cb'];
-
-//$p->factory($factory);
-
-$p['factory'] = $factory;
-
-echo $p['factory'];
-echo $p['factory'];
-echo $p['factory'];
-
-}
-
-echo microtime(true) - $time;
+++ /dev/null
-<?php
-
-if (!class_exists('Pimple\Container')) {
- require_once __DIR__ . '/../../../src/Pimple/Container.php';
-} else {
- echo "pimple-c extension detected, using...\n\n";
-}
-
-$time = microtime(true);
-
-
-$service = function ($arg) { return "I'm a service"; };
-
-for ($i=0; $i<10000; $i++) {
-
-$p = new Pimple\Container;
-$p['my_service'] = $service;
-
-$a = $p['my_service'];
-$b = $p['my_service'];
-
-}
-
-echo microtime(true) - $time;
-?>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-
-<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
- backupGlobals="false"
- colors="true"
- bootstrap="vendor/autoload.php"
->
- <testsuites>
- <testsuite name="Pimple Test Suite">
- <directory>./src/Pimple/Tests</directory>
- </testsuite>
- </testsuites>
-</phpunit>
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple;
-
-use Pimple\Exception\ExpectedInvokableException;
-use Pimple\Exception\FrozenServiceException;
-use Pimple\Exception\InvalidServiceIdentifierException;
-use Pimple\Exception\UnknownIdentifierException;
-
-/**
- * Container main class.
- *
- * @author Fabien Potencier
- */
-class Container implements \ArrayAccess
-{
- private $values = array();
- private $factories;
- private $protected;
- private $frozen = array();
- private $raw = array();
- private $keys = array();
-
- /**
- * Instantiates the container.
- *
- * Objects and parameters can be passed as argument to the constructor.
- *
- * @param array $values The parameters or objects
- */
- public function __construct(array $values = array())
- {
- $this->factories = new \SplObjectStorage();
- $this->protected = new \SplObjectStorage();
-
- foreach ($values as $key => $value) {
- $this->offsetSet($key, $value);
- }
- }
-
- /**
- * Sets a parameter or an object.
- *
- * Objects must be defined as Closures.
- *
- * Allowing any PHP callable leads to difficult to debug problems
- * as function names (strings) are callable (creating a function with
- * the same name as an existing parameter would break your container).
- *
- * @param string $id The unique identifier for the parameter or object
- * @param mixed $value The value of the parameter or a closure to define an object
- *
- * @throws FrozenServiceException Prevent override of a frozen service
- */
- public function offsetSet($id, $value)
- {
- if (isset($this->frozen[$id])) {
- throw new FrozenServiceException($id);
- }
-
- $this->values[$id] = $value;
- $this->keys[$id] = true;
- }
-
- /**
- * Gets a parameter or an object.
- *
- * @param string $id The unique identifier for the parameter or object
- *
- * @return mixed The value of the parameter or an object
- *
- * @throws UnknownIdentifierException If the identifier is not defined
- */
- public function offsetGet($id)
- {
- if (!isset($this->keys[$id])) {
- throw new UnknownIdentifierException($id);
- }
-
- if (
- isset($this->raw[$id])
- || !\is_object($this->values[$id])
- || isset($this->protected[$this->values[$id]])
- || !\method_exists($this->values[$id], '__invoke')
- ) {
- return $this->values[$id];
- }
-
- if (isset($this->factories[$this->values[$id]])) {
- return $this->values[$id]($this);
- }
-
- $raw = $this->values[$id];
- $val = $this->values[$id] = $raw($this);
- $this->raw[$id] = $raw;
-
- $this->frozen[$id] = true;
-
- return $val;
- }
-
- /**
- * Checks if a parameter or an object is set.
- *
- * @param string $id The unique identifier for the parameter or object
- *
- * @return bool
- */
- public function offsetExists($id)
- {
- return isset($this->keys[$id]);
- }
-
- /**
- * Unsets a parameter or an object.
- *
- * @param string $id The unique identifier for the parameter or object
- */
- public function offsetUnset($id)
- {
- if (isset($this->keys[$id])) {
- if (\is_object($this->values[$id])) {
- unset($this->factories[$this->values[$id]], $this->protected[$this->values[$id]]);
- }
-
- unset($this->values[$id], $this->frozen[$id], $this->raw[$id], $this->keys[$id]);
- }
- }
-
- /**
- * Marks a callable as being a factory service.
- *
- * @param callable $callable A service definition to be used as a factory
- *
- * @return callable The passed callable
- *
- * @throws ExpectedInvokableException Service definition has to be a closure or an invokable object
- */
- public function factory($callable)
- {
- if (!\method_exists($callable, '__invoke')) {
- throw new ExpectedInvokableException('Service definition is not a Closure or invokable object.');
- }
-
- $this->factories->attach($callable);
-
- return $callable;
- }
-
- /**
- * Protects a callable from being interpreted as a service.
- *
- * This is useful when you want to store a callable as a parameter.
- *
- * @param callable $callable A callable to protect from being evaluated
- *
- * @return callable The passed callable
- *
- * @throws ExpectedInvokableException Service definition has to be a closure or an invokable object
- */
- public function protect($callable)
- {
- if (!\method_exists($callable, '__invoke')) {
- throw new ExpectedInvokableException('Callable is not a Closure or invokable object.');
- }
-
- $this->protected->attach($callable);
-
- return $callable;
- }
-
- /**
- * Gets a parameter or the closure defining an object.
- *
- * @param string $id The unique identifier for the parameter or object
- *
- * @return mixed The value of the parameter or the closure defining an object
- *
- * @throws UnknownIdentifierException If the identifier is not defined
- */
- public function raw($id)
- {
- if (!isset($this->keys[$id])) {
- throw new UnknownIdentifierException($id);
- }
-
- if (isset($this->raw[$id])) {
- return $this->raw[$id];
- }
-
- return $this->values[$id];
- }
-
- /**
- * Extends an object definition.
- *
- * Useful when you want to extend an existing object definition,
- * without necessarily loading that object.
- *
- * @param string $id The unique identifier for the object
- * @param callable $callable A service definition to extend the original
- *
- * @return callable The wrapped callable
- *
- * @throws UnknownIdentifierException If the identifier is not defined
- * @throws FrozenServiceException If the service is frozen
- * @throws InvalidServiceIdentifierException If the identifier belongs to a parameter
- * @throws ExpectedInvokableException If the extension callable is not a closure or an invokable object
- */
- public function extend($id, $callable)
- {
- if (!isset($this->keys[$id])) {
- throw new UnknownIdentifierException($id);
- }
-
- if (isset($this->frozen[$id])) {
- throw new FrozenServiceException($id);
- }
-
- if (!\is_object($this->values[$id]) || !\method_exists($this->values[$id], '__invoke')) {
- throw new InvalidServiceIdentifierException($id);
- }
-
- if (isset($this->protected[$this->values[$id]])) {
- @\trigger_error(\sprintf('How Pimple behaves when extending protected closures will be fixed in Pimple 4. Are you sure "%s" should be protected?', $id), \E_USER_DEPRECATED);
- }
-
- if (!\is_object($callable) || !\method_exists($callable, '__invoke')) {
- throw new ExpectedInvokableException('Extension service definition is not a Closure or invokable object.');
- }
-
- $factory = $this->values[$id];
-
- $extended = function ($c) use ($callable, $factory) {
- return $callable($factory($c), $c);
- };
-
- if (isset($this->factories[$factory])) {
- $this->factories->detach($factory);
- $this->factories->attach($extended);
- }
-
- return $this[$id] = $extended;
- }
-
- /**
- * Returns all defined value names.
- *
- * @return array An array of value names
- */
- public function keys()
- {
- return \array_keys($this->values);
- }
-
- /**
- * Registers a service provider.
- *
- * @param ServiceProviderInterface $provider A ServiceProviderInterface instance
- * @param array $values An array of values that customizes the provider
- *
- * @return static
- */
- public function register(ServiceProviderInterface $provider, array $values = array())
- {
- $provider->register($this);
-
- foreach ($values as $key => $value) {
- $this[$key] = $value;
- }
-
- return $this;
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Exception;
-
-use Psr\Container\ContainerExceptionInterface;
-
-/**
- * A closure or invokable object was expected.
- *
- * @author Pascal Luna <skalpa@zetareticuli.org>
- */
-class ExpectedInvokableException extends \InvalidArgumentException implements ContainerExceptionInterface
-{
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Exception;
-
-use Psr\Container\ContainerExceptionInterface;
-
-/**
- * An attempt to modify a frozen service was made.
- *
- * @author Pascal Luna <skalpa@zetareticuli.org>
- */
-class FrozenServiceException extends \RuntimeException implements ContainerExceptionInterface
-{
- /**
- * @param string $id Identifier of the frozen service
- */
- public function __construct($id)
- {
- parent::__construct(\sprintf('Cannot override frozen service "%s".', $id));
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Exception;
-
-use Psr\Container\NotFoundExceptionInterface;
-
-/**
- * An attempt to perform an operation that requires a service identifier was made.
- *
- * @author Pascal Luna <skalpa@zetareticuli.org>
- */
-class InvalidServiceIdentifierException extends \InvalidArgumentException implements NotFoundExceptionInterface
-{
- /**
- * @param string $id The invalid identifier
- */
- public function __construct($id)
- {
- parent::__construct(\sprintf('Identifier "%s" does not contain an object definition.', $id));
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Exception;
-
-use Psr\Container\NotFoundExceptionInterface;
-
-/**
- * The identifier of a valid service or parameter was expected.
- *
- * @author Pascal Luna <skalpa@zetareticuli.org>
- */
-class UnknownIdentifierException extends \InvalidArgumentException implements NotFoundExceptionInterface
-{
- /**
- * @param string $id The unknown identifier
- */
- public function __construct($id)
- {
- parent::__construct(\sprintf('Identifier "%s" is not defined.', $id));
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009-2017 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.
- */
-
-namespace Pimple\Psr11;
-
-use Pimple\Container as PimpleContainer;
-use Psr\Container\ContainerInterface;
-
-/**
- * PSR-11 compliant wrapper.
- *
- * @author Pascal Luna <skalpa@zetareticuli.org>
- */
-final class Container implements ContainerInterface
-{
- private $pimple;
-
- public function __construct(PimpleContainer $pimple)
- {
- $this->pimple = $pimple;
- }
-
- public function get($id)
- {
- return $this->pimple[$id];
- }
-
- public function has($id)
- {
- return isset($this->pimple[$id]);
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Psr11;
-
-use Pimple\Container as PimpleContainer;
-use Pimple\Exception\UnknownIdentifierException;
-use Psr\Container\ContainerInterface;
-
-/**
- * Pimple PSR-11 service locator.
- *
- * @author Pascal Luna <skalpa@zetareticuli.org>
- */
-class ServiceLocator implements ContainerInterface
-{
- private $container;
- private $aliases = array();
-
- /**
- * @param PimpleContainer $container The Container instance used to locate services
- * @param array $ids Array of service ids that can be located. String keys can be used to define aliases
- */
- public function __construct(PimpleContainer $container, array $ids)
- {
- $this->container = $container;
-
- foreach ($ids as $key => $id) {
- $this->aliases[\is_int($key) ? $id : $key] = $id;
- }
- }
-
- /**
- * {@inheritdoc}
- */
- public function get($id)
- {
- if (!isset($this->aliases[$id])) {
- throw new UnknownIdentifierException($id);
- }
-
- return $this->container[$this->aliases[$id]];
- }
-
- /**
- * {@inheritdoc}
- */
- public function has($id)
- {
- return isset($this->aliases[$id]) && isset($this->container[$this->aliases[$id]]);
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple;
-
-/**
- * Lazy service iterator.
- *
- * @author Pascal Luna <skalpa@zetareticuli.org>
- */
-final class ServiceIterator implements \Iterator
-{
- private $container;
- private $ids;
-
- public function __construct(Container $container, array $ids)
- {
- $this->container = $container;
- $this->ids = $ids;
- }
-
- public function rewind()
- {
- \reset($this->ids);
- }
-
- public function current()
- {
- return $this->container[\current($this->ids)];
- }
-
- public function key()
- {
- return \current($this->ids);
- }
-
- public function next()
- {
- \next($this->ids);
- }
-
- public function valid()
- {
- return null !== \key($this->ids);
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple;
-
-/**
- * Pimple service provider interface.
- *
- * @author Fabien Potencier
- * @author Dominik Zogg
- */
-interface ServiceProviderInterface
-{
- /**
- * Registers services on the given container.
- *
- * This method should only be used to configure services and parameters.
- * It should not get services.
- *
- * @param Container $pimple A container instance
- */
- public function register(Container $pimple);
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Tests\Fixtures;
-
-class Invokable
-{
- public function __invoke($value = null)
- {
- $service = new Service();
- $service->value = $value;
-
- return $service;
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Tests\Fixtures;
-
-class NonInvokable
-{
- public function __call($a, $b)
- {
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Tests\Fixtures;
-
-use Pimple\Container;
-use Pimple\ServiceProviderInterface;
-
-class PimpleServiceProvider implements ServiceProviderInterface
-{
- /**
- * Registers services on the given container.
- *
- * This method should only be used to configure services and parameters.
- * It should not get services.
- *
- * @param Container $pimple An Container instance
- */
- public function register(Container $pimple)
- {
- $pimple['param'] = 'value';
-
- $pimple['service'] = function () {
- return new Service();
- };
-
- $pimple['factory'] = $pimple->factory(function () {
- return new Service();
- });
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Tests\Fixtures;
-
-/**
- * @author Igor Wiedler <igor@wiedler.ch>
- */
-class Service
-{
- public $value;
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Tests;
-
-use Pimple\Container;
-
-/**
- * @author Dominik Zogg <dominik.zogg@gmail.com>
- */
-class PimpleServiceProviderInterfaceTest extends \PHPUnit_Framework_TestCase
-{
- public function testProvider()
- {
- $pimple = new Container();
-
- $pimpleServiceProvider = new Fixtures\PimpleServiceProvider();
- $pimpleServiceProvider->register($pimple);
-
- $this->assertEquals('value', $pimple['param']);
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $pimple['service']);
-
- $serviceOne = $pimple['factory'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceOne);
-
- $serviceTwo = $pimple['factory'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceTwo);
-
- $this->assertNotSame($serviceOne, $serviceTwo);
- }
-
- public function testProviderWithRegisterMethod()
- {
- $pimple = new Container();
-
- $pimple->register(new Fixtures\PimpleServiceProvider(), array(
- 'anotherParameter' => 'anotherValue',
- ));
-
- $this->assertEquals('value', $pimple['param']);
- $this->assertEquals('anotherValue', $pimple['anotherParameter']);
-
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $pimple['service']);
-
- $serviceOne = $pimple['factory'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceOne);
-
- $serviceTwo = $pimple['factory'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceTwo);
-
- $this->assertNotSame($serviceOne, $serviceTwo);
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Tests;
-
-use Pimple\Container;
-
-/**
- * @author Igor Wiedler <igor@wiedler.ch>
- */
-class PimpleTest extends \PHPUnit_Framework_TestCase
-{
- public function testWithString()
- {
- $pimple = new Container();
- $pimple['param'] = 'value';
-
- $this->assertEquals('value', $pimple['param']);
- }
-
- public function testWithClosure()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
-
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $pimple['service']);
- }
-
- public function testServicesShouldBeDifferent()
- {
- $pimple = new Container();
- $pimple['service'] = $pimple->factory(function () {
- return new Fixtures\Service();
- });
-
- $serviceOne = $pimple['service'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceOne);
-
- $serviceTwo = $pimple['service'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceTwo);
-
- $this->assertNotSame($serviceOne, $serviceTwo);
- }
-
- public function testShouldPassContainerAsParameter()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
- $pimple['container'] = function ($container) {
- return $container;
- };
-
- $this->assertNotSame($pimple, $pimple['service']);
- $this->assertSame($pimple, $pimple['container']);
- }
-
- public function testIsset()
- {
- $pimple = new Container();
- $pimple['param'] = 'value';
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
-
- $pimple['null'] = null;
-
- $this->assertTrue(isset($pimple['param']));
- $this->assertTrue(isset($pimple['service']));
- $this->assertTrue(isset($pimple['null']));
- $this->assertFalse(isset($pimple['non_existent']));
- }
-
- public function testConstructorInjection()
- {
- $params = array('param' => 'value');
- $pimple = new Container($params);
-
- $this->assertSame($params['param'], $pimple['param']);
- }
-
- /**
- * @expectedException \Pimple\Exception\UnknownIdentifierException
- * @expectedExceptionMessage Identifier "foo" is not defined.
- */
- public function testOffsetGetValidatesKeyIsPresent()
- {
- $pimple = new Container();
- echo $pimple['foo'];
- }
-
- /**
- * @group legacy
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage Identifier "foo" is not defined.
- */
- public function testLegacyOffsetGetValidatesKeyIsPresent()
- {
- $pimple = new Container();
- echo $pimple['foo'];
- }
-
- public function testOffsetGetHonorsNullValues()
- {
- $pimple = new Container();
- $pimple['foo'] = null;
- $this->assertNull($pimple['foo']);
- }
-
- public function testUnset()
- {
- $pimple = new Container();
- $pimple['param'] = 'value';
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
-
- unset($pimple['param'], $pimple['service']);
- $this->assertFalse(isset($pimple['param']));
- $this->assertFalse(isset($pimple['service']));
- }
-
- /**
- * @dataProvider serviceDefinitionProvider
- */
- public function testShare($service)
- {
- $pimple = new Container();
- $pimple['shared_service'] = $service;
-
- $serviceOne = $pimple['shared_service'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceOne);
-
- $serviceTwo = $pimple['shared_service'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceTwo);
-
- $this->assertSame($serviceOne, $serviceTwo);
- }
-
- /**
- * @dataProvider serviceDefinitionProvider
- */
- public function testProtect($service)
- {
- $pimple = new Container();
- $pimple['protected'] = $pimple->protect($service);
-
- $this->assertSame($service, $pimple['protected']);
- }
-
- public function testGlobalFunctionNameAsParameterValue()
- {
- $pimple = new Container();
- $pimple['global_function'] = 'strlen';
- $this->assertSame('strlen', $pimple['global_function']);
- }
-
- public function testRaw()
- {
- $pimple = new Container();
- $pimple['service'] = $definition = $pimple->factory(function () { return 'foo'; });
- $this->assertSame($definition, $pimple->raw('service'));
- }
-
- public function testRawHonorsNullValues()
- {
- $pimple = new Container();
- $pimple['foo'] = null;
- $this->assertNull($pimple->raw('foo'));
- }
-
- public function testFluentRegister()
- {
- $pimple = new Container();
- $this->assertSame($pimple, $pimple->register($this->getMockBuilder('Pimple\ServiceProviderInterface')->getMock()));
- }
-
- /**
- * @expectedException \Pimple\Exception\UnknownIdentifierException
- * @expectedExceptionMessage Identifier "foo" is not defined.
- */
- public function testRawValidatesKeyIsPresent()
- {
- $pimple = new Container();
- $pimple->raw('foo');
- }
-
- /**
- * @group legacy
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage Identifier "foo" is not defined.
- */
- public function testLegacyRawValidatesKeyIsPresent()
- {
- $pimple = new Container();
- $pimple->raw('foo');
- }
-
- /**
- * @dataProvider serviceDefinitionProvider
- */
- public function testExtend($service)
- {
- $pimple = new Container();
- $pimple['shared_service'] = function () {
- return new Fixtures\Service();
- };
- $pimple['factory_service'] = $pimple->factory(function () {
- return new Fixtures\Service();
- });
-
- $pimple->extend('shared_service', $service);
- $serviceOne = $pimple['shared_service'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceOne);
- $serviceTwo = $pimple['shared_service'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceTwo);
- $this->assertSame($serviceOne, $serviceTwo);
- $this->assertSame($serviceOne->value, $serviceTwo->value);
-
- $pimple->extend('factory_service', $service);
- $serviceOne = $pimple['factory_service'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceOne);
- $serviceTwo = $pimple['factory_service'];
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $serviceTwo);
- $this->assertNotSame($serviceOne, $serviceTwo);
- $this->assertNotSame($serviceOne->value, $serviceTwo->value);
- }
-
- public function testExtendDoesNotLeakWithFactories()
- {
- if (extension_loaded('pimple')) {
- $this->markTestSkipped('Pimple extension does not support this test');
- }
- $pimple = new Container();
-
- $pimple['foo'] = $pimple->factory(function () { return; });
- $pimple['foo'] = $pimple->extend('foo', function ($foo, $pimple) { return; });
- unset($pimple['foo']);
-
- $p = new \ReflectionProperty($pimple, 'values');
- $p->setAccessible(true);
- $this->assertEmpty($p->getValue($pimple));
-
- $p = new \ReflectionProperty($pimple, 'factories');
- $p->setAccessible(true);
- $this->assertCount(0, $p->getValue($pimple));
- }
-
- /**
- * @expectedException \Pimple\Exception\UnknownIdentifierException
- * @expectedExceptionMessage Identifier "foo" is not defined.
- */
- public function testExtendValidatesKeyIsPresent()
- {
- $pimple = new Container();
- $pimple->extend('foo', function () {});
- }
-
- /**
- * @group legacy
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage Identifier "foo" is not defined.
- */
- public function testLegacyExtendValidatesKeyIsPresent()
- {
- $pimple = new Container();
- $pimple->extend('foo', function () {});
- }
-
- public function testKeys()
- {
- $pimple = new Container();
- $pimple['foo'] = 123;
- $pimple['bar'] = 123;
-
- $this->assertEquals(array('foo', 'bar'), $pimple->keys());
- }
-
- /** @test */
- public function settingAnInvokableObjectShouldTreatItAsFactory()
- {
- $pimple = new Container();
- $pimple['invokable'] = new Fixtures\Invokable();
-
- $this->assertInstanceOf('Pimple\Tests\Fixtures\Service', $pimple['invokable']);
- }
-
- /** @test */
- public function settingNonInvokableObjectShouldTreatItAsParameter()
- {
- $pimple = new Container();
- $pimple['non_invokable'] = new Fixtures\NonInvokable();
-
- $this->assertInstanceOf('Pimple\Tests\Fixtures\NonInvokable', $pimple['non_invokable']);
- }
-
- /**
- * @dataProvider badServiceDefinitionProvider
- * @expectedException \Pimple\Exception\ExpectedInvokableException
- * @expectedExceptionMessage Service definition is not a Closure or invokable object.
- */
- public function testFactoryFailsForInvalidServiceDefinitions($service)
- {
- $pimple = new Container();
- $pimple->factory($service);
- }
-
- /**
- * @group legacy
- * @dataProvider badServiceDefinitionProvider
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage Service definition is not a Closure or invokable object.
- */
- public function testLegacyFactoryFailsForInvalidServiceDefinitions($service)
- {
- $pimple = new Container();
- $pimple->factory($service);
- }
-
- /**
- * @dataProvider badServiceDefinitionProvider
- * @expectedException \Pimple\Exception\ExpectedInvokableException
- * @expectedExceptionMessage Callable is not a Closure or invokable object.
- */
- public function testProtectFailsForInvalidServiceDefinitions($service)
- {
- $pimple = new Container();
- $pimple->protect($service);
- }
-
- /**
- * @group legacy
- * @dataProvider badServiceDefinitionProvider
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage Callable is not a Closure or invokable object.
- */
- public function testLegacyProtectFailsForInvalidServiceDefinitions($service)
- {
- $pimple = new Container();
- $pimple->protect($service);
- }
-
- /**
- * @dataProvider badServiceDefinitionProvider
- * @expectedException \Pimple\Exception\InvalidServiceIdentifierException
- * @expectedExceptionMessage Identifier "foo" does not contain an object definition.
- */
- public function testExtendFailsForKeysNotContainingServiceDefinitions($service)
- {
- $pimple = new Container();
- $pimple['foo'] = $service;
- $pimple->extend('foo', function () {});
- }
-
- /**
- * @group legacy
- * @dataProvider badServiceDefinitionProvider
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage Identifier "foo" does not contain an object definition.
- */
- public function testLegacyExtendFailsForKeysNotContainingServiceDefinitions($service)
- {
- $pimple = new Container();
- $pimple['foo'] = $service;
- $pimple->extend('foo', function () {});
- }
-
- /**
- * @group legacy
- * @expectedDeprecation How Pimple behaves when extending protected closures will be fixed in Pimple 4. Are you sure "foo" should be protected?
- */
- public function testExtendingProtectedClosureDeprecation()
- {
- $pimple = new Container();
- $pimple['foo'] = $pimple->protect(function () {
- return 'bar';
- });
-
- $pimple->extend('foo', function ($value) {
- return $value.'-baz';
- });
-
- $this->assertSame('bar-baz', $pimple['foo']);
- }
-
- /**
- * @dataProvider badServiceDefinitionProvider
- * @expectedException \Pimple\Exception\ExpectedInvokableException
- * @expectedExceptionMessage Extension service definition is not a Closure or invokable object.
- */
- public function testExtendFailsForInvalidServiceDefinitions($service)
- {
- $pimple = new Container();
- $pimple['foo'] = function () {};
- $pimple->extend('foo', $service);
- }
-
- /**
- * @group legacy
- * @dataProvider badServiceDefinitionProvider
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage Extension service definition is not a Closure or invokable object.
- */
- public function testLegacyExtendFailsForInvalidServiceDefinitions($service)
- {
- $pimple = new Container();
- $pimple['foo'] = function () {};
- $pimple->extend('foo', $service);
- }
-
- /**
- * @expectedException \Pimple\Exception\FrozenServiceException
- * @expectedExceptionMessage Cannot override frozen service "foo".
- */
- public function testExtendFailsIfFrozenServiceIsNonInvokable()
- {
- $pimple = new Container();
- $pimple['foo'] = function () {
- return new Fixtures\NonInvokable();
- };
- $foo = $pimple['foo'];
-
- $pimple->extend('foo', function () {});
- }
-
- /**
- * @expectedException \Pimple\Exception\FrozenServiceException
- * @expectedExceptionMessage Cannot override frozen service "foo".
- */
- public function testExtendFailsIfFrozenServiceIsInvokable()
- {
- $pimple = new Container();
- $pimple['foo'] = function () {
- return new Fixtures\Invokable();
- };
- $foo = $pimple['foo'];
-
- $pimple->extend('foo', function () {});
- }
-
- /**
- * Provider for invalid service definitions.
- */
- public function badServiceDefinitionProvider()
- {
- return array(
- array(123),
- array(new Fixtures\NonInvokable()),
- );
- }
-
- /**
- * Provider for service definitions.
- */
- public function serviceDefinitionProvider()
- {
- return array(
- array(function ($value) {
- $service = new Fixtures\Service();
- $service->value = $value;
-
- return $service;
- }),
- array(new Fixtures\Invokable()),
- );
- }
-
- public function testDefiningNewServiceAfterFreeze()
- {
- $pimple = new Container();
- $pimple['foo'] = function () {
- return 'foo';
- };
- $foo = $pimple['foo'];
-
- $pimple['bar'] = function () {
- return 'bar';
- };
- $this->assertSame('bar', $pimple['bar']);
- }
-
- /**
- * @expectedException \Pimple\Exception\FrozenServiceException
- * @expectedExceptionMessage Cannot override frozen service "foo".
- */
- public function testOverridingServiceAfterFreeze()
- {
- $pimple = new Container();
- $pimple['foo'] = function () {
- return 'foo';
- };
- $foo = $pimple['foo'];
-
- $pimple['foo'] = function () {
- return 'bar';
- };
- }
-
- /**
- * @group legacy
- * @expectedException \RuntimeException
- * @expectedExceptionMessage Cannot override frozen service "foo".
- */
- public function testLegacyOverridingServiceAfterFreeze()
- {
- $pimple = new Container();
- $pimple['foo'] = function () {
- return 'foo';
- };
- $foo = $pimple['foo'];
-
- $pimple['foo'] = function () {
- return 'bar';
- };
- }
-
- public function testRemovingServiceAfterFreeze()
- {
- $pimple = new Container();
- $pimple['foo'] = function () {
- return 'foo';
- };
- $foo = $pimple['foo'];
-
- unset($pimple['foo']);
- $pimple['foo'] = function () {
- return 'bar';
- };
- $this->assertSame('bar', $pimple['foo']);
- }
-
- public function testExtendingService()
- {
- $pimple = new Container();
- $pimple['foo'] = function () {
- return 'foo';
- };
- $pimple['foo'] = $pimple->extend('foo', function ($foo, $app) {
- return "$foo.bar";
- });
- $pimple['foo'] = $pimple->extend('foo', function ($foo, $app) {
- return "$foo.baz";
- });
- $this->assertSame('foo.bar.baz', $pimple['foo']);
- }
-
- public function testExtendingServiceAfterOtherServiceFreeze()
- {
- $pimple = new Container();
- $pimple['foo'] = function () {
- return 'foo';
- };
- $pimple['bar'] = function () {
- return 'bar';
- };
- $foo = $pimple['foo'];
-
- $pimple['bar'] = $pimple->extend('bar', function ($bar, $app) {
- return "$bar.baz";
- });
- $this->assertSame('bar.baz', $pimple['bar']);
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009-2017 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.
- */
-
-namespace Pimple\Tests\Psr11;
-
-use PHPUnit\Framework\TestCase;
-use Pimple\Container;
-use Pimple\Psr11\Container as PsrContainer;
-use Pimple\Tests\Fixtures\Service;
-
-class ContainerTest extends TestCase
-{
- public function testGetReturnsExistingService()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Service();
- };
- $psr = new PsrContainer($pimple);
-
- $this->assertSame($pimple['service'], $psr->get('service'));
- }
-
- /**
- * @expectedException \Psr\Container\NotFoundExceptionInterface
- * @expectedExceptionMessage Identifier "service" is not defined.
- */
- public function testGetThrowsExceptionIfServiceIsNotFound()
- {
- $pimple = new Container();
- $psr = new PsrContainer($pimple);
-
- $psr->get('service');
- }
-
- public function testHasReturnsTrueIfServiceExists()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Service();
- };
- $psr = new PsrContainer($pimple);
-
- $this->assertTrue($psr->has('service'));
- }
-
- public function testHasReturnsFalseIfServiceDoesNotExist()
- {
- $pimple = new Container();
- $psr = new PsrContainer($pimple);
-
- $this->assertFalse($psr->has('service'));
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Tests\Psr11;
-
-use PHPUnit\Framework\TestCase;
-use Pimple\Container;
-use Pimple\Psr11\ServiceLocator;
-use Pimple\Tests\Fixtures;
-
-/**
- * ServiceLocator test case.
- *
- * @author Pascal Luna <skalpa@zetareticuli.org>
- */
-class ServiceLocatorTest extends TestCase
-{
- public function testCanAccessServices()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
- $locator = new ServiceLocator($pimple, array('service'));
-
- $this->assertSame($pimple['service'], $locator->get('service'));
- }
-
- public function testCanAccessAliasedServices()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
- $locator = new ServiceLocator($pimple, array('alias' => 'service'));
-
- $this->assertSame($pimple['service'], $locator->get('alias'));
- }
-
- /**
- * @expectedException \Pimple\Exception\UnknownIdentifierException
- * @expectedExceptionMessage Identifier "service" is not defined.
- */
- public function testCannotAccessAliasedServiceUsingRealIdentifier()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
- $locator = new ServiceLocator($pimple, array('alias' => 'service'));
-
- $service = $locator->get('service');
- }
-
- /**
- * @expectedException \Pimple\Exception\UnknownIdentifierException
- * @expectedExceptionMessage Identifier "foo" is not defined.
- */
- public function testGetValidatesServiceCanBeLocated()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
- $locator = new ServiceLocator($pimple, array('alias' => 'service'));
-
- $service = $locator->get('foo');
- }
-
- /**
- * @expectedException \Pimple\Exception\UnknownIdentifierException
- * @expectedExceptionMessage Identifier "invalid" is not defined.
- */
- public function testGetValidatesTargetServiceExists()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
- $locator = new ServiceLocator($pimple, array('alias' => 'invalid'));
-
- $service = $locator->get('alias');
- }
-
- public function testHasValidatesServiceCanBeLocated()
- {
- $pimple = new Container();
- $pimple['service1'] = function () {
- return new Fixtures\Service();
- };
- $pimple['service2'] = function () {
- return new Fixtures\Service();
- };
- $locator = new ServiceLocator($pimple, array('service1'));
-
- $this->assertTrue($locator->has('service1'));
- $this->assertFalse($locator->has('service2'));
- }
-
- public function testHasChecksIfTargetServiceExists()
- {
- $pimple = new Container();
- $pimple['service'] = function () {
- return new Fixtures\Service();
- };
- $locator = new ServiceLocator($pimple, array('foo' => 'service', 'bar' => 'invalid'));
-
- $this->assertTrue($locator->has('foo'));
- $this->assertFalse($locator->has('bar'));
- }
-}
+++ /dev/null
-<?php
-
-/*
- * This file is part of Pimple.
- *
- * Copyright (c) 2009 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.
- */
-
-namespace Pimple\Tests;
-
-use PHPUnit\Framework\TestCase;
-use Pimple\Container;
-use Pimple\ServiceIterator;
-use Pimple\Tests\Fixtures\Service;
-
-class ServiceIteratorTest extends TestCase
-{
- public function testIsIterable()
- {
- $pimple = new Container();
- $pimple['service1'] = function () {
- return new Service();
- };
- $pimple['service2'] = function () {
- return new Service();
- };
- $pimple['service3'] = function () {
- return new Service();
- };
- $iterator = new ServiceIterator($pimple, array('service1', 'service2'));
-
- $this->assertSame(array('service1' => $pimple['service1'], 'service2' => $pimple['service2']), iterator_to_array($iterator));
- }
-}
-# PSR Container
+Container interface
+==============
-This repository holds all interfaces/classes/traits related to [PSR-11](https://github.com/container-interop/fig-standards/blob/master/proposed/container.md).
+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
-Note that this is not a container implementation of its own. See the specification for more details.
"authors": [
{
"name": "PHP-FIG",
- "homepage": "http://www.php-fig.org/"
+ "homepage": "https://www.php-fig.org/"
}
],
"require": {
- "php": ">=5.3.0"
+ "php": ">=7.4.0"
},
"autoload": {
"psr-4": {
},
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-master": "2.0.x-dev"
}
}
}
<?php
-/**
- * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
- */
namespace Psr\Container;
+use Throwable;
+
/**
* Base interface representing a generic exception in a container.
*/
-interface ContainerExceptionInterface
+interface ContainerExceptionInterface extends Throwable
{
}
<?php
-/**
- * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
- */
+
+declare(strict_types=1);
namespace Psr\Container;
*
* @return mixed Entry.
*/
- public function get($id);
+ public function get(string $id);
/**
* Returns true if the container can return an entry for the given identifier.
*
* @return bool
*/
- public function has($id);
+ public function has(string $id): bool;
}
<?php
-/**
- * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
- */
namespace Psr\Container;
--- /dev/null
+MIT License
+
+Copyright (c) 2018 PHP-FIG
+
+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.
--- /dev/null
+HTTP Factories
+==============
+
+This repository holds all interfaces related to [PSR-17 (HTTP Factories)][psr-url].
+
+Note that this is not a HTTP Factory implementation of its own. It is merely interfaces that describe the components of a HTTP Factory.
+
+The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist.
+
+[psr-url]: https://www.php-fig.org/psr/psr-17/
+[package-url]: https://packagist.org/packages/psr/http-factory
+[implementation-url]: https://packagist.org/providers/psr/http-factory-implementation
--- /dev/null
+{
+ "name": "psr/http-factory",
+ "description": "Common interfaces for PSR-7 HTTP message factories",
+ "keywords": [
+ "psr",
+ "psr-7",
+ "psr-17",
+ "http",
+ "factory",
+ "message",
+ "request",
+ "response"
+ ],
+ "license": "MIT",
+ "authors": [
+ {
+ "name": "PHP-FIG",
+ "homepage": "https://www.php-fig.org/"
+ }
+ ],
+ "require": {
+ "php": ">=7.0.0",
+ "psr/http-message": "^1.0 || ^2.0"
+ },
+ "autoload": {
+ "psr-4": {
+ "Psr\\Http\\Message\\": "src/"
+ }
+ },
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.0.x-dev"
+ }
+ }
+}
--- /dev/null
+<?php
+
+namespace Psr\Http\Message;
+
+interface RequestFactoryInterface
+{
+ /**
+ * Create a new request.
+ *
+ * @param string $method The HTTP method associated with the request.
+ * @param UriInterface|string $uri The URI associated with the request. If
+ * the value is a string, the factory MUST create a UriInterface
+ * instance based on it.
+ *
+ * @return RequestInterface
+ */
+ public function createRequest(string $method, $uri): RequestInterface;
+}
--- /dev/null
+<?php
+
+namespace Psr\Http\Message;
+
+interface ResponseFactoryInterface
+{
+ /**
+ * Create a new response.
+ *
+ * @param int $code HTTP status code; defaults to 200
+ * @param string $reasonPhrase Reason phrase to associate with status code
+ * in generated response; if none is provided implementations MAY use
+ * the defaults as suggested in the HTTP specification.
+ *
+ * @return ResponseInterface
+ */
+ public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface;
+}
--- /dev/null
+<?php
+
+namespace Psr\Http\Message;
+
+interface ServerRequestFactoryInterface
+{
+ /**
+ * Create a new server request.
+ *
+ * Note that server-params are taken precisely as given - no parsing/processing
+ * of the given values is performed, and, in particular, no attempt is made to
+ * determine the HTTP method or URI, which must be provided explicitly.
+ *
+ * @param string $method The HTTP method associated with the request.
+ * @param UriInterface|string $uri The URI associated with the request. If
+ * the value is a string, the factory MUST create a UriInterface
+ * instance based on it.
+ * @param array $serverParams Array of SAPI parameters with which to seed
+ * the generated request instance.
+ *
+ * @return ServerRequestInterface
+ */
+ public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface;
+}
--- /dev/null
+<?php
+
+namespace Psr\Http\Message;
+
+interface StreamFactoryInterface
+{
+ /**
+ * Create a new stream from a string.
+ *
+ * The stream SHOULD be created with a temporary resource.
+ *
+ * @param string $content String content with which to populate the stream.
+ *
+ * @return StreamInterface
+ */
+ public function createStream(string $content = ''): StreamInterface;
+
+ /**
+ * Create a stream from an existing file.
+ *
+ * The file MUST be opened using the given mode, which may be any mode
+ * supported by the `fopen` function.
+ *
+ * The `$filename` MAY be any string supported by `fopen()`.
+ *
+ * @param string $filename Filename or stream URI to use as basis of stream.
+ * @param string $mode Mode with which to open the underlying filename/stream.
+ *
+ * @return StreamInterface
+ * @throws \RuntimeException If the file cannot be opened.
+ * @throws \InvalidArgumentException If the mode is invalid.
+ */
+ public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface;
+
+ /**
+ * Create a new stream from an existing resource.
+ *
+ * The stream MUST be readable and may be writable.
+ *
+ * @param resource $resource PHP resource to use as basis of stream.
+ *
+ * @return StreamInterface
+ */
+ public function createStreamFromResource($resource): StreamInterface;
+}
--- /dev/null
+<?php
+
+namespace Psr\Http\Message;
+
+interface UploadedFileFactoryInterface
+{
+ /**
+ * Create a new uploaded file.
+ *
+ * If a size is not provided it will be determined by checking the size of
+ * the file.
+ *
+ * @see http://php.net/manual/features.file-upload.post-method.php
+ * @see http://php.net/manual/features.file-upload.errors.php
+ *
+ * @param StreamInterface $stream Underlying stream representing the
+ * uploaded file content.
+ * @param int $size in bytes
+ * @param int $error PHP file upload error
+ * @param string $clientFilename Filename as provided by the client, if any.
+ * @param string $clientMediaType Media type as provided by the client, if any.
+ *
+ * @return UploadedFileInterface
+ *
+ * @throws \InvalidArgumentException If the file resource is not readable.
+ */
+ public function createUploadedFile(
+ StreamInterface $stream,
+ int $size = null,
+ int $error = \UPLOAD_ERR_OK,
+ string $clientFilename = null,
+ string $clientMediaType = null
+ ): UploadedFileInterface;
+}
--- /dev/null
+<?php
+
+namespace Psr\Http\Message;
+
+interface UriFactoryInterface
+{
+ /**
+ * Create a new URI.
+ *
+ * @param string $uri
+ *
+ * @return UriInterface
+ *
+ * @throws \InvalidArgumentException If the given URI cannot be parsed.
+ */
+ public function createUri(string $uri = ''): UriInterface;
+}
Usage
-----
-We'll certainly need some stuff in here.
\ No newline at end of file
+Before reading the usage guide we recommend reading the PSR-7 interfaces method list:
+
+* [`PSR-7 Interfaces Method List`](docs/PSR7-Interfaces.md)
+* [`PSR-7 Usage Guide`](docs/PSR7-Usage.md)
\ No newline at end of file
}
],
"require": {
- "php": ">=5.3.0"
+ "php": "^7.2 || ^8.0"
},
"autoload": {
"psr-4": {
},
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-master": "1.1.x-dev"
}
}
}
--- /dev/null
+# Interfaces
+
+The purpose of this list is to help in finding the methods when working with PSR-7. This can be considered as a cheatsheet for PSR-7 interfaces.
+
+The interfaces defined in PSR-7 are the following:
+
+| Class Name | Description |
+|---|---|
+| [Psr\Http\Message\MessageInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagemessageinterface) | Representation of a HTTP message |
+| [Psr\Http\Message\RequestInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagerequestinterface) | Representation of an outgoing, client-side request. |
+| [Psr\Http\Message\ServerRequestInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageserverrequestinterface) | Representation of an incoming, server-side HTTP request. |
+| [Psr\Http\Message\ResponseInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageresponseinterface) | Representation of an outgoing, server-side response. |
+| [Psr\Http\Message\StreamInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagestreaminterface) | Describes a data stream |
+| [Psr\Http\Message\UriInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageuriinterface) | Value object representing a URI. |
+| [Psr\Http\Message\UploadedFileInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageuploadedfileinterface) | Value object representing a file uploaded through an HTTP request. |
+
+## `Psr\Http\Message\MessageInterface` Methods
+
+| Method Name | Description | Notes |
+|------------------------------------| ----------- | ----- |
+| `getProtocolVersion()` | Retrieve HTTP protocol version | 1.0 or 1.1 |
+| `withProtocolVersion($version)` | Returns new message instance with given HTTP protocol version | |
+| `getHeaders()` | Retrieve all HTTP Headers | [Request Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields), [Response Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Response_fields) |
+| `hasHeader($name)` | Checks if HTTP Header with given name exists | |
+| `getHeader($name)` | Retrieves a array with the values for a single header | |
+| `getHeaderLine($name)` | Retrieves a comma-separated string of the values for a single header | |
+| `withHeader($name, $value)` | Returns new message instance with given HTTP Header | if the header existed in the original instance, replaces the header value from the original message with the value provided when creating the new instance. |
+| `withAddedHeader($name, $value)` | Returns new message instance with appended value to given header | If header already exists value will be appended, if not a new header will be created |
+| `withoutHeader($name)` | Removes HTTP Header with given name| |
+| `getBody()` | Retrieves the HTTP Message Body | Returns object implementing `StreamInterface`|
+| `withBody(StreamInterface $body)` | Returns new message instance with given HTTP Message Body | |
+
+
+## `Psr\Http\Message\RequestInterface` Methods
+
+Same methods as `Psr\Http\Message\MessageInterface` + the following methods:
+
+| Method Name | Description | Notes |
+|------------------------------------| ----------- | ----- |
+| `getRequestTarget()` | Retrieves the message's request target | origin-form, absolute-form, authority-form, asterisk-form ([RFC7230](https://www.rfc-editor.org/rfc/rfc7230.txt)) |
+| `withRequestTarget($requestTarget)` | Return a new message instance with the specific request-target | |
+| `getMethod()` | Retrieves the HTTP method of the request. | GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE (defined in [RFC7231](https://tools.ietf.org/html/rfc7231)), PATCH (defined in [RFC5789](https://tools.ietf.org/html/rfc5789)) |
+| `withMethod($method)` | Returns a new message instance with the provided HTTP method | |
+| `getUri()` | Retrieves the URI instance | |
+| `withUri(UriInterface $uri, $preserveHost = false)` | Returns a new message instance with the provided URI | |
+
+
+## `Psr\Http\Message\ServerRequestInterface` Methods
+
+Same methods as `Psr\Http\Message\RequestInterface` + the following methods:
+
+| Method Name | Description | Notes |
+|------------------------------------| ----------- | ----- |
+| `getServerParams() ` | Retrieve server parameters | Typically derived from `$_SERVER` |
+| `getCookieParams()` | Retrieves cookies sent by the client to the server. | Typically derived from `$_COOKIES` |
+| `withCookieParams(array $cookies)` | Returns a new request instance with the specified cookies | |
+| `withQueryParams(array $query)` | Returns a new request instance with the specified query string arguments | |
+| `getUploadedFiles()` | Retrieve normalized file upload data | |
+| `withUploadedFiles(array $uploadedFiles)` | Returns a new request instance with the specified uploaded files | |
+| `getParsedBody()` | Retrieve any parameters provided in the request body | |
+| `withParsedBody($data)` | Returns a new request instance with the specified body parameters | |
+| `getAttributes()` | Retrieve attributes derived from the request | |
+| `getAttribute($name, $default = null)` | Retrieve a single derived request attribute | |
+| `withAttribute($name, $value)` | Returns a new request instance with the specified derived request attribute | |
+| `withoutAttribute($name)` | Returns a new request instance that without the specified derived request attribute | |
+
+## `Psr\Http\Message\ResponseInterface` Methods:
+
+Same methods as `Psr\Http\Message\MessageInterface` + the following methods:
+
+| Method Name | Description | Notes |
+|------------------------------------| ----------- | ----- |
+| `getStatusCode()` | Gets the response status code. | |
+| `withStatus($code, $reasonPhrase = '')` | Returns a new response instance with the specified status code and, optionally, reason phrase. | |
+| `getReasonPhrase()` | Gets the response reason phrase associated with the status code. | |
+
+## `Psr\Http\Message\StreamInterface` Methods
+
+| Method Name | Description | Notes |
+|------------------------------------| ----------- | ----- |
+| `__toString()` | Reads all data from the stream into a string, from the beginning to end. | |
+| `close()` | Closes the stream and any underlying resources. | |
+| `detach()` | Separates any underlying resources from the stream. | |
+| `getSize()` | Get the size of the stream if known. | |
+| `eof()` | Returns true if the stream is at the end of the stream.| |
+| `isSeekable()` | Returns whether or not the stream is seekable. | |
+| `seek($offset, $whence = SEEK_SET)` | Seek to a position in the stream. | |
+| `rewind()` | Seek to the beginning of the stream. | |
+| `isWritable()` | Returns whether or not the stream is writable. | |
+| `write($string)` | Write data to the stream. | |
+| `isReadable()` | Returns whether or not the stream is readable. | |
+| `read($length)` | Read data from the stream. | |
+| `getContents()` | Returns the remaining contents in a string | |
+| `getMetadata($key = null)()` | Get stream metadata as an associative array or retrieve a specific key. | |
+
+## `Psr\Http\Message\UriInterface` Methods
+
+| Method Name | Description | Notes |
+|------------------------------------| ----------- | ----- |
+| `getScheme()` | Retrieve the scheme component of the URI. | |
+| `getAuthority()` | Retrieve the authority component of the URI. | |
+| `getUserInfo()` | Retrieve the user information component of the URI. | |
+| `getHost()` | Retrieve the host component of the URI. | |
+| `getPort()` | Retrieve the port component of the URI. | |
+| `getPath()` | Retrieve the path component of the URI. | |
+| `getQuery()` | Retrieve the query string of the URI. | |
+| `getFragment()` | Retrieve the fragment component of the URI. | |
+| `withScheme($scheme)` | Return an instance with the specified scheme. | |
+| `withUserInfo($user, $password = null)` | Return an instance with the specified user information. | |
+| `withHost($host)` | Return an instance with the specified host. | |
+| `withPort($port)` | Return an instance with the specified port. | |
+| `withPath($path)` | Return an instance with the specified path. | |
+| `withQuery($query)` | Return an instance with the specified query string. | |
+| `withFragment($fragment)` | Return an instance with the specified URI fragment. | |
+| `__toString()` | Return the string representation as a URI reference. | |
+
+## `Psr\Http\Message\UploadedFileInterface` Methods
+
+| Method Name | Description | Notes |
+|------------------------------------| ----------- | ----- |
+| `getStream()` | Retrieve a stream representing the uploaded file. | |
+| `moveTo($targetPath)` | Move the uploaded file to a new location. | |
+| `getSize()` | Retrieve the file size. | |
+| `getError()` | Retrieve the error associated with the uploaded file. | |
+| `getClientFilename()` | Retrieve the filename sent by the client. | |
+| `getClientMediaType()` | Retrieve the media type sent by the client. | |
+
+> `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.
+
--- /dev/null
+### 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);
+```
<?php
+declare(strict_types=1);
+
namespace Psr\Http\Message;
/**
* @param string $version HTTP protocol version
* @return static
*/
- public function withProtocolVersion($version);
+ public function withProtocolVersion(string $version);
/**
* Retrieves all message header values.
* name using a case-insensitive string comparison. Returns false if
* no matching header name is found in the message.
*/
- public function hasHeader($name);
+ public function hasHeader(string $name);
/**
* Retrieves a message header value by the given case-insensitive name.
* header. If the header does not appear in the message, this method MUST
* return an empty array.
*/
- public function getHeader($name);
+ public function getHeader(string $name);
/**
* Retrieves a comma-separated string of the values for a single 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($name);
+ public function getHeaderLine(string $name);
/**
* Return an instance with the provided value replacing the specified header.
* @return static
* @throws \InvalidArgumentException for invalid header names or values.
*/
- public function withHeader($name, $value);
+ public function withHeader(string $name, $value);
/**
* Return an instance with the specified header appended with the given value.
* @return static
* @throws \InvalidArgumentException for invalid header names or values.
*/
- public function withAddedHeader($name, $value);
+ public function withAddedHeader(string $name, $value);
/**
* Return an instance without the specified header.
* @param string $name Case-insensitive header field name to remove.
* @return static
*/
- public function withoutHeader($name);
+ public function withoutHeader(string $name);
/**
* Gets the body of the message.
<?php
+declare(strict_types=1);
+
namespace Psr\Http\Message;
/**
*
* @link http://tools.ietf.org/html/rfc7230#section-5.3 (for the various
* request-target forms allowed in request messages)
- * @param mixed $requestTarget
+ * @param string $requestTarget
* @return static
*/
- public function withRequestTarget($requestTarget);
+ public function withRequestTarget(string $requestTarget);
/**
* Retrieves the HTTP method of the request.
* @return static
* @throws \InvalidArgumentException for invalid HTTP methods.
*/
- public function withMethod($method);
+ public function withMethod(string $method);
/**
* Retrieves the URI instance.
* @param bool $preserveHost Preserve the original state of the Host header.
* @return static
*/
- public function withUri(UriInterface $uri, $preserveHost = false);
+ public function withUri(UriInterface $uri, bool $preserveHost = false);
}
<?php
+declare(strict_types=1);
+
namespace Psr\Http\Message;
/**
* @return static
* @throws \InvalidArgumentException For invalid status code arguments.
*/
- public function withStatus($code, $reasonPhrase = '');
+ public function withStatus(int $code, string $reasonPhrase = '');
/**
* Gets the response reason phrase associated with the status code.
<?php
+declare(strict_types=1);
+
namespace Psr\Http\Message;
/**
* @param mixed $default Default value to return if the attribute does not exist.
* @return mixed
*/
- public function getAttribute($name, $default = null);
+ public function getAttribute(string $name, $default = null);
/**
* Return an instance with the specified derived request attribute.
* @param mixed $value The value of the attribute.
* @return static
*/
- public function withAttribute($name, $value);
+ public function withAttribute(string $name, $value);
/**
* Return an instance that removes the specified derived request attribute.
* @param string $name The attribute name.
* @return static
*/
- public function withoutAttribute($name);
+ public function withoutAttribute(string $name);
}
<?php
+declare(strict_types=1);
+
namespace Psr\Http\Message;
/**
* SEEK_END: Set position to end-of-stream plus offset.
* @throws \RuntimeException on failure.
*/
- public function seek($offset, $whence = SEEK_SET);
+ public function seek(int $offset, int $whence = SEEK_SET);
/**
* Seek to the beginning of the stream.
* @return int Returns the number of bytes written to the stream.
* @throws \RuntimeException on failure.
*/
- public function write($string);
+ public function write(string $string);
/**
* Returns whether or not the stream is readable.
* if no bytes are available.
* @throws \RuntimeException if an error occurs.
*/
- public function read($length);
+ public function read(int $length);
/**
* Returns the remaining contents in a string
* stream_get_meta_data() function.
*
* @link http://php.net/manual/en/function.stream-get-meta-data.php
- * @param string $key Specific metadata to retrieve.
+ * @param string|null $key Specific metadata to retrieve.
* @return array|mixed|null Returns an associative array if no key is
* provided. Returns a specific key value if a key is provided and the
* value is found, or null if the key is not found.
*/
- public function getMetadata($key = null);
+ public function getMetadata(?string $key = null);
}
<?php
+declare(strict_types=1);
+
namespace Psr\Http\Message;
/**
* @throws \RuntimeException on any error during the move operation, or on
* the second or subsequent call to the method.
*/
- public function moveTo($targetPath);
+ public function moveTo(string $targetPath);
/**
* Retrieve the file size.
<?php
+
+declare(strict_types=1);
+
namespace Psr\Http\Message;
/**
* @return static A new instance with the specified scheme.
* @throws \InvalidArgumentException for invalid or unsupported schemes.
*/
- public function withScheme($scheme);
+ public function withScheme(string $scheme);
/**
* Return an instance with the specified user information.
* @param null|string $password The password associated with $user.
* @return static A new instance with the specified user information.
*/
- public function withUserInfo($user, $password = null);
+ public function withUserInfo(string $user, ?string $password = null);
/**
* Return an instance with the specified host.
* @return static A new instance with the specified host.
* @throws \InvalidArgumentException for invalid hostnames.
*/
- public function withHost($host);
+ public function withHost(string $host);
/**
* Return an instance with the specified port.
* @return static A new instance with the specified port.
* @throws \InvalidArgumentException for invalid ports.
*/
- public function withPort($port);
+ public function withPort(?int $port);
/**
* Return an instance with the specified path.
* @return static A new instance with the specified path.
* @throws \InvalidArgumentException for invalid paths.
*/
- public function withPath($path);
+ public function withPath(string $path);
/**
* Return an instance with the specified query string.
* @return static A new instance with the specified query string.
* @throws \InvalidArgumentException for invalid query strings.
*/
- public function withQuery($query);
+ public function withQuery(string $query);
/**
* Return an instance with the specified URI fragment.
* @param string $fragment The fragment to use with the new instance.
* @return static A new instance with the specified fragment.
*/
- public function withFragment($fragment);
+ public function withFragment(string $fragment);
/**
* Return the string representation as a URI reference.
--- /dev/null
+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.
--- /dev/null
+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
--- /dev/null
+{
+ "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"
+ }
+ }
+}
--- /dev/null
+<?php
+
+namespace Psr\Http\Server;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+
+/**
+ * Handles a server request and produces a response.
+ *
+ * An HTTP request handler process an HTTP request in order to produce an
+ * HTTP response.
+ */
+interface RequestHandlerInterface
+{
+ /**
+ * Handles a request and produces a response.
+ *
+ * May call other collaborating code to generate the response.
+ */
+ public function handle(ServerRequestInterface $request): ResponseInterface;
+}
--- /dev/null
+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.
--- /dev/null
+HTTP Server Middleware
+==============
+
+This repository holds the `MiddlewareInterface` related to [PSR-15 (HTTP Server Request Handlers)][psr-url].
+
+Note that this is not a Middleware implementation of its own. It is merely the interface that describe a Middleware.
+
+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-middleware
+[implementation-url]: https://packagist.org/providers/psr/http-server-middleware-implementation
--- /dev/null
+{
+ "name": "psr/http-server-middleware",
+ "description": "Common interface for HTTP server-side middleware",
+ "keywords": [
+ "psr",
+ "psr-7",
+ "psr-15",
+ "http-interop",
+ "http",
+ "middleware",
+ "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",
+ "psr/http-server-handler": "^1.0"
+ },
+ "autoload": {
+ "psr-4": {
+ "Psr\\Http\\Server\\": "src/"
+ }
+ },
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.0.x-dev"
+ }
+ }
+}
--- /dev/null
+<?php
+
+namespace Psr\Http\Server;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+
+/**
+ * Participant in processing a server request and response.
+ *
+ * An HTTP middleware component participates in processing an HTTP message:
+ * by acting on the request, generating the response, or forwarding the
+ * request to a subsequent middleware and possibly acting on its response.
+ */
+interface MiddlewareInterface
+{
+ /**
+ * Process an incoming server request.
+ *
+ * Processes an incoming server request in order to produce a response.
+ * If unable to produce the response itself, it may delegate to the provided
+ * request handler to do so.
+ */
+ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;
+}
/**
* System is unusable.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
*
* Example: Application component unavailable, unexpected exception.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
/**
* Normal but significant events.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
*
* Example: User logs in, SQL logs.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
/**
* Detailed debug information.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
/**
* The logger instance.
*
- * @var LoggerInterface
+ * @var LoggerInterface|null
*/
protected $logger;
/**
* System is unusable.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
*
* Example: Application component unavailable, unexpected exception.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
/**
* Normal but significant events.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
*
* Example: User logs in, SQL logs.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
/**
* Detailed debug information.
*
- * @param string $message
- * @param array $context
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
*/
/**
* Logs with an arbitrary level.
*
- * @param mixed $level
- * @param string $message
- * @param array $context
+ * @param mixed $level
+ * @param string $message
+ * @param mixed[] $context
*
* @return void
+ *
+ * @throws \Psr\Log\InvalidArgumentException
*/
public function log($level, $message, array $context = array());
}
* @param array $context
*
* @return void
+ *
+ * @throws \Psr\Log\InvalidArgumentException
*/
abstract public function log($level, $message, array $context = array());
}
* @param array $context
*
* @return void
+ *
+ * @throws \Psr\Log\InvalidArgumentException
*/
public function log($level, $message, array $context = array())
{
--- /dev/null
+<?php
+
+namespace Psr\Log\Test;
+
+/**
+ * This class is internal and does not follow the BC promise.
+ *
+ * Do NOT use this class in any way.
+ *
+ * @internal
+ */
+class DummyTest
+{
+ public function __toString()
+ {
+ return 'DummyTest';
+ }
+}
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
+use PHPUnit\Framework\TestCase;
/**
* Provides a base test class for ensuring compliance with the LoggerInterface.
* Implementors can extend the class and implement abstract methods to run this
* as part of their test suite.
*/
-abstract class LoggerInterfaceTest extends \PHPUnit_Framework_TestCase
+abstract class LoggerInterfaceTest extends TestCase
{
/**
* @return LoggerInterface
public function testContextCanContainAnything()
{
+ $closed = fopen('php://memory', 'r');
+ fclose($closed);
+
$context = array(
'bool' => true,
'null' => null,
'nested' => array('with object' => new DummyTest),
'object' => new \DateTime,
'resource' => fopen('php://memory', 'r'),
+ 'closed' => $closed,
);
$this->getLogger()->warning('Crazy context data', $context);
$this->assertEquals($expected, $this->getLogs());
}
}
-
-class DummyTest
-{
- public function __toString()
- {
- }
-}
--- /dev/null
+<?php
+
+namespace Psr\Log\Test;
+
+use Psr\Log\AbstractLogger;
+
+/**
+ * Used for testing purposes.
+ *
+ * It records all records and gives you access to them for verification.
+ *
+ * @method bool hasEmergency($record)
+ * @method bool hasAlert($record)
+ * @method bool hasCritical($record)
+ * @method bool hasError($record)
+ * @method bool hasWarning($record)
+ * @method bool hasNotice($record)
+ * @method bool hasInfo($record)
+ * @method bool hasDebug($record)
+ *
+ * @method bool hasEmergencyRecords()
+ * @method bool hasAlertRecords()
+ * @method bool hasCriticalRecords()
+ * @method bool hasErrorRecords()
+ * @method bool hasWarningRecords()
+ * @method bool hasNoticeRecords()
+ * @method bool hasInfoRecords()
+ * @method bool hasDebugRecords()
+ *
+ * @method bool hasEmergencyThatContains($message)
+ * @method bool hasAlertThatContains($message)
+ * @method bool hasCriticalThatContains($message)
+ * @method bool hasErrorThatContains($message)
+ * @method bool hasWarningThatContains($message)
+ * @method bool hasNoticeThatContains($message)
+ * @method bool hasInfoThatContains($message)
+ * @method bool hasDebugThatContains($message)
+ *
+ * @method bool hasEmergencyThatMatches($message)
+ * @method bool hasAlertThatMatches($message)
+ * @method bool hasCriticalThatMatches($message)
+ * @method bool hasErrorThatMatches($message)
+ * @method bool hasWarningThatMatches($message)
+ * @method bool hasNoticeThatMatches($message)
+ * @method bool hasInfoThatMatches($message)
+ * @method bool hasDebugThatMatches($message)
+ *
+ * @method bool hasEmergencyThatPasses($message)
+ * @method bool hasAlertThatPasses($message)
+ * @method bool hasCriticalThatPasses($message)
+ * @method bool hasErrorThatPasses($message)
+ * @method bool hasWarningThatPasses($message)
+ * @method bool hasNoticeThatPasses($message)
+ * @method bool hasInfoThatPasses($message)
+ * @method bool hasDebugThatPasses($message)
+ */
+class TestLogger extends AbstractLogger
+{
+ /**
+ * @var array
+ */
+ public $records = [];
+
+ public $recordsByLevel = [];
+
+ /**
+ * @inheritdoc
+ */
+ public function log($level, $message, array $context = [])
+ {
+ $record = [
+ 'level' => $level,
+ 'message' => $message,
+ 'context' => $context,
+ ];
+
+ $this->recordsByLevel[$record['level']][] = $record;
+ $this->records[] = $record;
+ }
+
+ public function hasRecords($level)
+ {
+ return isset($this->recordsByLevel[$level]);
+ }
+
+ public function hasRecord($record, $level)
+ {
+ if (is_string($record)) {
+ $record = ['message' => $record];
+ }
+ return $this->hasRecordThatPasses(function ($rec) use ($record) {
+ if ($rec['message'] !== $record['message']) {
+ return false;
+ }
+ if (isset($record['context']) && $rec['context'] !== $record['context']) {
+ return false;
+ }
+ return true;
+ }, $level);
+ }
+
+ public function hasRecordThatContains($message, $level)
+ {
+ return $this->hasRecordThatPasses(function ($rec) use ($message) {
+ return strpos($rec['message'], $message) !== false;
+ }, $level);
+ }
+
+ public function hasRecordThatMatches($regex, $level)
+ {
+ return $this->hasRecordThatPasses(function ($rec) use ($regex) {
+ return preg_match($regex, $rec['message']) > 0;
+ }, $level);
+ }
+
+ public function hasRecordThatPasses(callable $predicate, $level)
+ {
+ if (!isset($this->recordsByLevel[$level])) {
+ return false;
+ }
+ foreach ($this->recordsByLevel[$level] as $i => $rec) {
+ if (call_user_func($predicate, $rec, $i)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public function __call($method, $args)
+ {
+ if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) {
+ $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3];
+ $level = strtolower($matches[2]);
+ if (method_exists($this, $genericMethod)) {
+ $args[] = $level;
+ return call_user_func_array([$this, $genericMethod], $args);
+ }
+ }
+ throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()');
+ }
+
+ public function reset()
+ {
+ $this->records = [];
+ $this->recordsByLevel = [];
+ }
+}
Note that this is not a logger of its own. It is merely an interface that
describes a logger. See the specification for more details.
+Installation
+------------
+
+```bash
+composer require psr/log
+```
+
Usage
-----
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
}
"authors": [
{
"name": "PHP-FIG",
- "homepage": "http://www.php-fig.org/"
+ "homepage": "https://www.php-fig.org/"
}
],
"require": {
},
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-master": "1.1.x-dev"
}
}
}
--- /dev/null
+# 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
-Copyright (c) 2011-2017 Josh Lockhart
+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
--- /dev/null
+# 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.
--- /dev/null
+# 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
<?php
+
/**
* Slim Framework (https://slimframework.com)
*
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/
+
+declare(strict_types=1);
+
namespace Slim;
-use Exception;
-use Slim\Exception\InvalidMethodException;
-use Slim\Http\Response;
-use Throwable;
-use Closure;
-use InvalidArgumentException;
-use Psr\Http\Message\RequestInterface;
-use Psr\Http\Message\ServerRequestInterface;
-use Psr\Http\Message\ResponseInterface;
use Psr\Container\ContainerInterface;
-use FastRoute\Dispatcher;
-use Slim\Exception\SlimException;
-use Slim\Exception\MethodNotAllowedException;
-use Slim\Exception\NotFoundException;
-use Slim\Http\Uri;
-use Slim\Http\Headers;
-use Slim\Http\Body;
-use Slim\Http\Request;
-use Slim\Interfaces\Http\EnvironmentInterface;
-use Slim\Interfaces\RouteGroupInterface;
-use Slim\Interfaces\RouteInterface;
-use Slim\Interfaces\RouterInterface;
-
-/**
- * App
- *
- * This is the primary class with which you instantiate,
- * configure, and run a Slim Framework application.
- * The \Slim\App class also accepts Slim Framework middleware.
- *
- * @property-read callable $errorHandler
- * @property-read callable $phpErrorHandler
- * @property-read callable $notFoundHandler function($request, $response)
- * @property-read callable $notAllowedHandler function($request, $response, $allowedHttpMethods)
- */
-class App
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use Psr\Log\LoggerInterface;
+use Slim\Factory\ServerRequestCreatorFactory;
+use Slim\Interfaces\CallableResolverInterface;
+use Slim\Interfaces\MiddlewareDispatcherInterface;
+use Slim\Interfaces\RouteCollectorInterface;
+use Slim\Interfaces\RouteResolverInterface;
+use Slim\Middleware\BodyParsingMiddleware;
+use Slim\Middleware\ErrorMiddleware;
+use Slim\Middleware\RoutingMiddleware;
+use Slim\Routing\RouteCollectorProxy;
+use Slim\Routing\RouteResolver;
+use Slim\Routing\RouteRunner;
+
+use function strtoupper;
+
+class App extends RouteCollectorProxy implements RequestHandlerInterface
{
- use MiddlewareAwareTrait;
-
/**
* Current version
*
* @var string
*/
- const VERSION = '3.9.2';
+ public const VERSION = '4.12.0';
- /**
- * Container
- *
- * @var ContainerInterface
- */
- private $container;
+ protected RouteResolverInterface $routeResolver;
- /********************************************************************************
- * Constructor
- *******************************************************************************/
+ protected MiddlewareDispatcherInterface $middlewareDispatcher;
- /**
- * Create new application
- *
- * @param ContainerInterface|array $container Either a ContainerInterface or an associative array of app settings
- * @throws InvalidArgumentException when no container is provided that implements ContainerInterface
- */
- public function __construct($container = [])
- {
- if (is_array($container)) {
- $container = new Container($container);
- }
- if (!$container instanceof ContainerInterface) {
- throw new InvalidArgumentException('Expected a ContainerInterface');
- }
- $this->container = $container;
- }
-
- /**
- * Enable access to the DI container by consumers of $app
- *
- * @return ContainerInterface
- */
- public function getContainer()
- {
- return $this->container;
- }
-
- /**
- * Add middleware
- *
- * This method prepends new middleware to the app's middleware stack.
- *
- * @param callable|string $callable The callback routine
- *
- * @return static
- */
- public function add($callable)
- {
- return $this->addMiddleware(new DeferredCallable($callable, $this->container));
- }
-
- /**
- * Calling a non-existant method on App checks to see if there's an item
- * in the container that is callable and if so, calls it.
- *
- * @param string $method
- * @param array $args
- * @return mixed
- */
- public function __call($method, $args)
- {
- if ($this->container->has($method)) {
- $obj = $this->container->get($method);
- if (is_callable($obj)) {
- return call_user_func_array($obj, $args);
- }
+ 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);
}
- throw new \BadMethodCallException("Method $method is not a valid method");
- }
-
- /********************************************************************************
- * Router proxy methods
- *******************************************************************************/
-
- /**
- * Add GET route
- *
- * @param string $pattern The route URI pattern
- * @param callable|string $callable The route callback routine
- *
- * @return \Slim\Interfaces\RouteInterface
- */
- public function get($pattern, $callable)
- {
- return $this->map(['GET'], $pattern, $callable);
- }
-
- /**
- * Add POST route
- *
- * @param string $pattern The route URI pattern
- * @param callable|string $callable The route callback routine
- *
- * @return \Slim\Interfaces\RouteInterface
- */
- public function post($pattern, $callable)
- {
- return $this->map(['POST'], $pattern, $callable);
+ $this->middlewareDispatcher = $middlewareDispatcher;
}
/**
- * Add PUT route
- *
- * @param string $pattern The route URI pattern
- * @param callable|string $callable The route callback routine
- *
- * @return \Slim\Interfaces\RouteInterface
+ * @return RouteResolverInterface
*/
- public function put($pattern, $callable)
+ public function getRouteResolver(): RouteResolverInterface
{
- return $this->map(['PUT'], $pattern, $callable);
+ return $this->routeResolver;
}
/**
- * Add PATCH route
- *
- * @param string $pattern The route URI pattern
- * @param callable|string $callable The route callback routine
- *
- * @return \Slim\Interfaces\RouteInterface
+ * @return MiddlewareDispatcherInterface
*/
- public function patch($pattern, $callable)
+ public function getMiddlewareDispatcher(): MiddlewareDispatcherInterface
{
- return $this->map(['PATCH'], $pattern, $callable);
+ return $this->middlewareDispatcher;
}
/**
- * Add DELETE route
- *
- * @param string $pattern The route URI pattern
- * @param callable|string $callable The route callback routine
- *
- * @return \Slim\Interfaces\RouteInterface
+ * @param MiddlewareInterface|string|callable $middleware
*/
- public function delete($pattern, $callable)
+ public function add($middleware): self
{
- return $this->map(['DELETE'], $pattern, $callable);
+ $this->middlewareDispatcher->add($middleware);
+ return $this;
}
/**
- * Add OPTIONS route
- *
- * @param string $pattern The route URI pattern
- * @param callable|string $callable The route callback routine
- *
- * @return \Slim\Interfaces\RouteInterface
+ * @param MiddlewareInterface $middleware
*/
- public function options($pattern, $callable)
+ public function addMiddleware(MiddlewareInterface $middleware): self
{
- return $this->map(['OPTIONS'], $pattern, $callable);
+ $this->middlewareDispatcher->addMiddleware($middleware);
+ return $this;
}
/**
- * Add route for any HTTP method
+ * Add the Slim built-in routing middleware to the app middleware stack
*
- * @param string $pattern The route URI pattern
- * @param callable|string $callable The route callback routine
+ * This method can be used to control middleware order and is not required for default routing operation.
*
- * @return \Slim\Interfaces\RouteInterface
+ * @return RoutingMiddleware
*/
- public function any($pattern, $callable)
+ public function addRoutingMiddleware(): RoutingMiddleware
{
- return $this->map(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], $pattern, $callable);
+ $routingMiddleware = new RoutingMiddleware(
+ $this->getRouteResolver(),
+ $this->getRouteCollector()->getRouteParser()
+ );
+ $this->add($routingMiddleware);
+ return $routingMiddleware;
}
/**
- * Add route with multiple methods
+ * Add the Slim built-in error middleware to the app middleware stack
*
- * @param string[] $methods Numeric array of HTTP method names
- * @param string $pattern The route URI pattern
- * @param callable|string $callable The route callback routine
+ * @param bool $displayErrorDetails
+ * @param bool $logErrors
+ * @param bool $logErrorDetails
+ * @param LoggerInterface|null $logger
*
- * @return RouteInterface
+ * @return ErrorMiddleware
*/
- public function map(array $methods, $pattern, $callable)
- {
- if ($callable instanceof Closure) {
- $callable = $callable->bindTo($this->container);
- }
-
- $route = $this->container->get('router')->map($methods, $pattern, $callable);
- if (is_callable([$route, 'setContainer'])) {
- $route->setContainer($this->container);
- }
-
- if (is_callable([$route, 'setOutputBuffering'])) {
- $route->setOutputBuffering($this->container->get('settings')['outputBuffering']);
- }
-
- return $route;
+ 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;
}
/**
- * Route Groups
+ * Add the Slim body parsing middleware to the app middleware stack
*
- * 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 callable[] $bodyParsers
*
- * @param string $pattern
- * @param callable $callable
- *
- * @return RouteGroupInterface
+ * @return BodyParsingMiddleware
*/
- public function group($pattern, $callable)
+ public function addBodyParsingMiddleware(array $bodyParsers = []): BodyParsingMiddleware
{
- /** @var RouteGroup $group */
- $group = $this->container->get('router')->pushGroup($pattern, $callable);
- $group->setContainer($this->container);
- $group($this);
- $this->container->get('router')->popGroup();
- return $group;
+ $bodyParsingMiddleware = new BodyParsingMiddleware($bodyParsers);
+ $this->add($bodyParsingMiddleware);
+ return $bodyParsingMiddleware;
}
- /********************************************************************************
- * Runner
- *******************************************************************************/
-
/**
* Run application
*
* This method traverses the application middleware stack and then sends the
* resultant Response object to the HTTP client.
*
- * @param bool|false $silent
- * @return ResponseInterface
- *
- * @throws Exception
- * @throws MethodNotAllowedException
- * @throws NotFoundException
+ * @param ServerRequestInterface|null $request
+ * @return void
*/
- public function run($silent = false)
+ public function run(?ServerRequestInterface $request = null): void
{
- $response = $this->container->get('response');
-
- try {
- ob_start();
- $response = $this->process($this->container->get('request'), $response);
- } catch (InvalidMethodException $e) {
- $response = $this->processInvalidMethod($e->getRequest(), $response);
- } finally {
- $output = ob_get_clean();
- }
-
- if (!empty($output) && $response->getBody()->isWritable()) {
- $outputBuffering = $this->container->get('settings')['outputBuffering'];
- if ($outputBuffering === 'prepend') {
- // prepend output buffer content
- $body = new Http\Body(fopen('php://temp', 'r+'));
- $body->write($output . $response->getBody());
- $response = $response->withBody($body);
- } elseif ($outputBuffering === 'append') {
- // append output buffer content
- $response->getBody()->write($output);
- }
- }
-
- $response = $this->finalize($response);
-
- if (!$silent) {
- $this->respond($response);
+ if (!$request) {
+ $serverRequestCreator = ServerRequestCreatorFactory::create();
+ $request = $serverRequestCreator->createServerRequestFromGlobals();
}
- return $response;
+ $response = $this->handle($request);
+ $responseEmitter = new ResponseEmitter();
+ $responseEmitter->emit($response);
}
/**
- * Pull route info for a request with a bad method to decide whether to
- * return a not-found error (default) or a bad-method error, then run
- * the handler for that error, returning the resulting response.
- *
- * Used for cases where an incoming request has an unrecognized method,
- * rather than throwing an exception and not catching it all the way up.
- *
- * @param ServerRequestInterface $request
- * @param ResponseInterface $response
- * @return ResponseInterface
- */
- protected function processInvalidMethod(ServerRequestInterface $request, ResponseInterface $response)
- {
- $router = $this->container->get('router');
- if (is_callable([$request->getUri(), 'getBasePath']) && is_callable([$router, 'setBasePath'])) {
- $router->setBasePath($request->getUri()->getBasePath());
- }
-
- $request = $this->dispatchRouterAndPrepareRoute($request, $router);
- $routeInfo = $request->getAttribute('routeInfo', [RouterInterface::DISPATCH_STATUS => Dispatcher::NOT_FOUND]);
-
- if ($routeInfo[RouterInterface::DISPATCH_STATUS] === Dispatcher::METHOD_NOT_ALLOWED) {
- return $this->handleException(
- new MethodNotAllowedException($request, $response, $routeInfo[RouterInterface::ALLOWED_METHODS]),
- $request,
- $response
- );
- }
-
- return $this->handleException(new NotFoundException($request, $response), $request, $response);
- }
-
- /**
- * Process a request
+ * Handle a request
*
* This method traverses the application middleware stack and then returns the
* resultant Response object.
*
* @param ServerRequestInterface $request
- * @param ResponseInterface $response
- * @return ResponseInterface
- *
- * @throws Exception
- * @throws MethodNotAllowedException
- * @throws NotFoundException
- */
- public function process(ServerRequestInterface $request, ResponseInterface $response)
- {
- // Ensure basePath is set
- $router = $this->container->get('router');
- if (is_callable([$request->getUri(), 'getBasePath']) && is_callable([$router, 'setBasePath'])) {
- $router->setBasePath($request->getUri()->getBasePath());
- }
-
- // Dispatch the Router first if the setting for this is on
- if ($this->container->get('settings')['determineRouteBeforeAppMiddleware'] === true) {
- // Dispatch router (note: you won't be able to alter routes after this)
- $request = $this->dispatchRouterAndPrepareRoute($request, $router);
- }
-
- // Traverse middleware stack
- try {
- $response = $this->callMiddlewareStack($request, $response);
- } catch (Exception $e) {
- $response = $this->handleException($e, $request, $response);
- } catch (Throwable $e) {
- $response = $this->handlePhpError($e, $request, $response);
- }
-
- return $response;
- }
-
- /**
- * Send the response to the client
- *
- * @param ResponseInterface $response
- */
- public function respond(ResponseInterface $response)
- {
- // Send response
- if (!headers_sent()) {
- // Headers
- foreach ($response->getHeaders() as $name => $values) {
- foreach ($values as $value) {
- header(sprintf('%s: %s', $name, $value), false);
- }
- }
-
- // Set the status _after_ the headers, because of PHP's "helpful" behavior with location headers.
- // See https://github.com/slimphp/Slim/issues/1730
-
- // Status
- header(sprintf(
- 'HTTP/%s %s %s',
- $response->getProtocolVersion(),
- $response->getStatusCode(),
- $response->getReasonPhrase()
- ));
- }
-
- // Body
- if (!$this->isEmptyResponse($response)) {
- $body = $response->getBody();
- if ($body->isSeekable()) {
- $body->rewind();
- }
- $settings = $this->container->get('settings');
- $chunkSize = $settings['responseChunkSize'];
-
- $contentLength = $response->getHeaderLine('Content-Length');
- if (!$contentLength) {
- $contentLength = $body->getSize();
- }
-
-
- if (isset($contentLength)) {
- $amountToRead = $contentLength;
- while ($amountToRead > 0 && !$body->eof()) {
- $data = $body->read(min($chunkSize, $amountToRead));
- echo $data;
-
- $amountToRead -= strlen($data);
-
- if (connection_status() != CONNECTION_NORMAL) {
- break;
- }
- }
- } else {
- while (!$body->eof()) {
- echo $body->read($chunkSize);
- if (connection_status() != CONNECTION_NORMAL) {
- break;
- }
- }
- }
- }
- }
-
- /**
- * Invoke application
- *
- * This method implements the middleware interface. It receives
- * Request and Response objects, and it returns a Response object
- * after compiling the routes registered in the Router and dispatching
- * the Request object to the appropriate Route callback routine.
- *
- * @param ServerRequestInterface $request The most recent Request object
- * @param ResponseInterface $response The most recent Response object
- *
- * @return ResponseInterface
- * @throws MethodNotAllowedException
- * @throws NotFoundException
- */
- public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
- {
- // Get the route info
- $routeInfo = $request->getAttribute('routeInfo');
-
- /** @var \Slim\Interfaces\RouterInterface $router */
- $router = $this->container->get('router');
-
- // If router hasn't been dispatched or the URI changed then dispatch
- if (null === $routeInfo || ($routeInfo['request'] !== [$request->getMethod(), (string) $request->getUri()])) {
- $request = $this->dispatchRouterAndPrepareRoute($request, $router);
- $routeInfo = $request->getAttribute('routeInfo');
- }
-
- if ($routeInfo[0] === Dispatcher::FOUND) {
- $route = $router->lookupRoute($routeInfo[1]);
- return $route->run($request, $response);
- } elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
- if (!$this->container->has('notAllowedHandler')) {
- throw new MethodNotAllowedException($request, $response, $routeInfo[1]);
- }
- /** @var callable $notAllowedHandler */
- $notAllowedHandler = $this->container->get('notAllowedHandler');
- return $notAllowedHandler($request, $response, $routeInfo[1]);
- }
-
- if (!$this->container->has('notFoundHandler')) {
- throw new NotFoundException($request, $response);
- }
- /** @var callable $notFoundHandler */
- $notFoundHandler = $this->container->get('notFoundHandler');
- return $notFoundHandler($request, $response);
- }
-
- /**
- * Perform a sub-request from within an application route
- *
- * This method allows you to prepare and initiate a sub-request, run within
- * the context of the current request. This WILL NOT issue a remote HTTP
- * request. Instead, it will route the provided URL, method, headers,
- * cookies, body, and server variables against the set of registered
- * application routes. The result response object is returned.
- *
- * @param string $method The request method (e.g., GET, POST, PUT, etc.)
- * @param string $path The request URI path
- * @param string $query The request URI query string
- * @param array $headers The request headers (key-value array)
- * @param array $cookies The request cookies (key-value array)
- * @param string $bodyContent The request body
- * @param ResponseInterface $response The response object (optional)
- * @return ResponseInterface
- */
- public function subRequest(
- $method,
- $path,
- $query = '',
- array $headers = [],
- array $cookies = [],
- $bodyContent = '',
- ResponseInterface $response = null
- ) {
- $env = $this->container->get('environment');
- $uri = Uri::createFromEnvironment($env)->withPath($path)->withQuery($query);
- $headers = new Headers($headers);
- $serverParams = $env->all();
- $body = new Body(fopen('php://temp', 'r+'));
- $body->write($bodyContent);
- $body->rewind();
- $request = new Request($method, $uri, $headers, $cookies, $serverParams, $body);
-
- if (!$response) {
- $response = $this->container->get('response');
- }
-
- return $this($request, $response);
- }
-
- /**
- * Dispatch the router to find the route. Prepare the route for use.
- *
- * @param ServerRequestInterface $request
- * @param RouterInterface $router
- * @return ServerRequestInterface
- */
- protected function dispatchRouterAndPrepareRoute(ServerRequestInterface $request, RouterInterface $router)
- {
- $routeInfo = $router->dispatch($request);
-
- if ($routeInfo[0] === Dispatcher::FOUND) {
- $routeArguments = [];
- foreach ($routeInfo[2] as $k => $v) {
- $routeArguments[$k] = urldecode($v);
- }
-
- $route = $router->lookupRoute($routeInfo[1]);
- $route->prepare($request, $routeArguments);
-
- // add route to the request's attributes in case a middleware or handler needs access to the route
- $request = $request->withAttribute('route', $route);
- }
-
- $routeInfo['request'] = [$request->getMethod(), (string) $request->getUri()];
-
- return $request->withAttribute('routeInfo', $routeInfo);
- }
-
- /**
- * Finalize response
- *
- * @param ResponseInterface $response
* @return ResponseInterface
*/
- protected function finalize(ResponseInterface $response)
+ public function handle(ServerRequestInterface $request): ResponseInterface
{
- // stop PHP sending a Content-Type automatically
- ini_set('default_mimetype', '');
+ $response = $this->middlewareDispatcher->handle($request);
- if ($this->isEmptyResponse($response)) {
- return $response->withoutHeader('Content-Type')->withoutHeader('Content-Length');
- }
-
- // Add Content-Length header if `addContentLengthHeader` setting is set
- if (isset($this->container->get('settings')['addContentLengthHeader']) &&
- $this->container->get('settings')['addContentLengthHeader'] == true) {
- if (ob_get_length() > 0) {
- throw new \RuntimeException("Unexpected data in output buffer. " .
- "Maybe you have characters before an opening <?php tag?");
- }
- $size = $response->getBody()->getSize();
- if ($size !== null && !$response->hasHeader('Content-Length')) {
- $response = $response->withHeader('Content-Length', (string) $size);
- }
+ /**
+ * 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;
}
-
- /**
- * Helper method, which returns true if the provided response must not output a body and false
- * if the response could have a body.
- *
- * @see https://tools.ietf.org/html/rfc7231
- *
- * @param ResponseInterface $response
- * @return bool
- */
- protected function isEmptyResponse(ResponseInterface $response)
- {
- if (method_exists($response, 'isEmpty')) {
- return $response->isEmpty();
- }
-
- return in_array($response->getStatusCode(), [204, 205, 304]);
- }
-
- /**
- * Call relevant handler from the Container if needed. If it doesn't exist,
- * then just re-throw.
- *
- * @param Exception $e
- * @param ServerRequestInterface $request
- * @param ResponseInterface $response
- *
- * @return ResponseInterface
- * @throws Exception if a handler is needed and not found
- */
- protected function handleException(Exception $e, ServerRequestInterface $request, ResponseInterface $response)
- {
- if ($e instanceof MethodNotAllowedException) {
- $handler = 'notAllowedHandler';
- $params = [$e->getRequest(), $e->getResponse(), $e->getAllowedMethods()];
- } elseif ($e instanceof NotFoundException) {
- $handler = 'notFoundHandler';
- $params = [$e->getRequest(), $e->getResponse(), $e];
- } elseif ($e instanceof SlimException) {
- // This is a Stop exception and contains the response
- return $e->getResponse();
- } else {
- // Other exception, use $request and $response params
- $handler = 'errorHandler';
- $params = [$request, $response, $e];
- }
-
- if ($this->container->has($handler)) {
- $callable = $this->container->get($handler);
- // Call the registered handler
- return call_user_func_array($callable, $params);
- }
-
- // No handlers found, so just throw the exception
- throw $e;
- }
-
- /**
- * Call relevant handler from the Container if needed. If it doesn't exist,
- * then just re-throw.
- *
- * @param Throwable $e
- * @param ServerRequestInterface $request
- * @param ResponseInterface $response
- * @return ResponseInterface
- * @throws Throwable
- */
- protected function handlePhpError(Throwable $e, ServerRequestInterface $request, ResponseInterface $response)
- {
- $handler = 'phpErrorHandler';
- $params = [$request, $response, $e];
-
- if ($this->container->has($handler)) {
- $callable = $this->container->get($handler);
- // Call the registered handler
- return call_user_func_array($callable, $params);
- }
-
- // No handlers found, so just throw the exception
- throw $e;
- }
}
<?php
+
/**
* Slim Framework (https://slimframework.com)
*
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/
+
+declare(strict_types=1);
+
namespace Slim;
-use RuntimeException;
+use Closure;
use Psr\Container\ContainerInterface;
-use Slim\Interfaces\CallableResolverInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use RuntimeException;
+use Slim\Interfaces\AdvancedCallableResolverInterface;
-/**
- * This class resolves a string of the format 'class:method' into a closure
- * that can be dispatched.
- */
-final class CallableResolver implements CallableResolverInterface
+use function class_exists;
+use function is_array;
+use function is_callable;
+use function is_object;
+use function is_string;
+use function json_encode;
+use function preg_match;
+use function sprintf;
+
+final class CallableResolver implements AdvancedCallableResolverInterface
{
- const CALLABLE_PATTERN = '!^([^\:]+)\:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$!';
+ public static string $callablePattern = '!^([^\:]+)\:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$!';
+
+ private ?ContainerInterface $container;
+
+ public function __construct(?ContainerInterface $container = null)
+ {
+ $this->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);
+ }
/**
- * @var ContainerInterface
+ * {@inheritdoc}
*/
- private $container;
+ public function resolveRoute($toResolve): callable
+ {
+ return $this->resolveByPredicate($toResolve, [$this, 'isRoute'], 'handle');
+ }
/**
- * @param ContainerInterface $container
+ * {@inheritdoc}
*/
- public function __construct(ContainerInterface $container)
+ public function resolveMiddleware($toResolve): callable
{
- $this->container = $container;
+ return $this->resolveByPredicate($toResolve, [$this, 'isMiddleware'], 'process');
}
/**
- * Resolve toResolve into a closure so that the router can dispatch.
- *
- * If toResolve is of the format 'class:method', then try to extract 'class'
- * from the container otherwise instantiate it and then dispatch 'method'.
- *
- * @param mixed $toResolve
+ * @param string|callable $toResolve
*
- * @return callable
- *
- * @throws RuntimeException if the callable does not exist
- * @throws RuntimeException if the callable is not resolvable
+ * @throws RuntimeException
*/
- public function resolve($toResolve)
+ private function resolveByPredicate($toResolve, callable $predicate, string $defaultMethod): callable
{
+ $toResolve = $this->prepareToResolve($toResolve);
if (is_callable($toResolve)) {
- return $toResolve;
+ return $this->bindToContainer($toResolve);
}
-
- if (!is_string($toResolve)) {
- $this->assertCallable($toResolve);
+ $resolved = $toResolve;
+ if ($predicate($toResolve)) {
+ $resolved = [$toResolve, $defaultMethod];
}
-
- // check for slim callable as "class:method"
- if (preg_match(self::CALLABLE_PATTERN, $toResolve, $matches)) {
- $resolved = $this->resolveCallable($matches[1], $matches[2]);
- $this->assertCallable($resolved);
-
- return $resolved;
+ 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);
+ }
- $resolved = $this->resolveCallable($toResolve);
- $this->assertCallable($resolved);
+ /**
+ * @param mixed $toResolve
+ */
+ private function isRoute($toResolve): bool
+ {
+ return $toResolve instanceof RequestHandlerInterface;
+ }
- return $resolved;
+ /**
+ * @param mixed $toResolve
+ */
+ private function isMiddleware($toResolve): bool
+ {
+ return $toResolve instanceof MiddlewareInterface;
}
/**
- * Check if string is something in the DIC
- * that's callable or is a class name which has an __invoke() method.
- *
- * @param string $class
- * @param string $method
- * @return callable
+ * @throws RuntimeException
*
- * @throws \RuntimeException if the callable does not exist
+ * @return array{object, string|null} [Instance, Method Name]
*/
- protected function resolveCallable($class, $method = '__invoke')
+ private function resolveSlimNotation(string $toResolve): array
{
- if ($this->container->has($class)) {
- return [$this->container->get($class), $method];
+ preg_match(CallableResolver::$callablePattern, $toResolve, $matches);
+ [$class, $method] = $matches ? [$matches[1], $matches[2]] : [$toResolve, null];
+
+ /** @var string $class */
+ /** @var string|null $method */
+ 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];
+ }
- if (!class_exists($class)) {
- throw new RuntimeException(sprintf('Callable %s does not exist', $class));
+ /**
+ * @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;
+ }
- return [new $class($this->container), $method];
+ 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 Callable $callable
- *
- * @throws \RuntimeException if the callable is not resolvable
+ * @param string|callable $toResolve
+ * @return string|callable
*/
- protected function assertCallable($callable)
+ private function prepareToResolve($toResolve)
{
- if (!is_callable($callable)) {
- throw new RuntimeException(sprintf(
- '%s is not resolvable',
- is_array($callable) || is_object($callable) ? json_encode($callable) : $callable
- ));
+ 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;
}
}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim;
-
-use RuntimeException;
-use Psr\Container\ContainerInterface;
-use Slim\Interfaces\CallableResolverInterface;
-
-/**
- * ResolveCallable
- *
- * This is an internal class that enables resolution of 'class:method' strings
- * into a closure. This class is an implementation detail and is used only inside
- * of the Slim application.
- *
- * @property ContainerInterface $container
- */
-trait CallableResolverAwareTrait
-{
- /**
- * Resolve a string of the format 'class:method' into a closure that the
- * router can dispatch.
- *
- * @param callable|string $callable
- *
- * @return \Closure
- *
- * @throws RuntimeException If the string cannot be resolved as a callable
- */
- protected function resolveCallable($callable)
- {
- if (!$this->container instanceof ContainerInterface) {
- return $callable;
- }
-
- /** @var CallableResolverInterface $resolver */
- $resolver = $this->container->get('callableResolver');
-
- return $resolver->resolve($callable);
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim;
-
-use ArrayIterator;
-use Slim\Interfaces\CollectionInterface;
-
-/**
- * Collection
- *
- * This class provides a common interface used by many other
- * classes in a Slim application that manage "collections"
- * of data that must be inspected and/or manipulated
- */
-class Collection implements CollectionInterface
-{
- /**
- * The source data
- *
- * @var array
- */
- protected $data = [];
-
- /**
- * Create new collection
- *
- * @param array $items Pre-populate collection with this key-value array
- */
- public function __construct(array $items = [])
- {
- $this->replace($items);
- }
-
- /********************************************************************************
- * Collection interface
- *******************************************************************************/
-
- /**
- * Set collection item
- *
- * @param string $key The data key
- * @param mixed $value The data value
- */
- public function set($key, $value)
- {
- $this->data[$key] = $value;
- }
-
- /**
- * Get collection item for key
- *
- * @param string $key The data key
- * @param mixed $default The default value to return if data key does not exist
- *
- * @return mixed The key's value, or the default value
- */
- public function get($key, $default = null)
- {
- return $this->has($key) ? $this->data[$key] : $default;
- }
-
- /**
- * Add item to collection, replacing existing items with the same data key
- *
- * @param array $items Key-value array of data to append to this collection
- */
- public function replace(array $items)
- {
- foreach ($items as $key => $value) {
- $this->set($key, $value);
- }
- }
-
- /**
- * Get all items in collection
- *
- * @return array The collection's source data
- */
- public function all()
- {
- return $this->data;
- }
-
- /**
- * Get collection keys
- *
- * @return array The collection's source data keys
- */
- public function keys()
- {
- return array_keys($this->data);
- }
-
- /**
- * Does this collection have a given key?
- *
- * @param string $key The data key
- *
- * @return bool
- */
- public function has($key)
- {
- return array_key_exists($key, $this->data);
- }
-
- /**
- * Remove item from collection
- *
- * @param string $key The data key
- */
- public function remove($key)
- {
- unset($this->data[$key]);
- }
-
- /**
- * Remove all items from collection
- */
- public function clear()
- {
- $this->data = [];
- }
-
- /********************************************************************************
- * ArrayAccess interface
- *******************************************************************************/
-
- /**
- * Does this collection have a given key?
- *
- * @param string $key The data key
- *
- * @return bool
- */
- public function offsetExists($key)
- {
- return $this->has($key);
- }
-
- /**
- * Get collection item for key
- *
- * @param string $key The data key
- *
- * @return mixed The key's value, or the default value
- */
- public function offsetGet($key)
- {
- return $this->get($key);
- }
-
- /**
- * Set collection item
- *
- * @param string $key The data key
- * @param mixed $value The data value
- */
- public function offsetSet($key, $value)
- {
- $this->set($key, $value);
- }
-
- /**
- * Remove item from collection
- *
- * @param string $key The data key
- */
- public function offsetUnset($key)
- {
- $this->remove($key);
- }
-
- /**
- * Get number of items in collection
- *
- * @return int
- */
- public function count()
- {
- return count($this->data);
- }
-
- /********************************************************************************
- * IteratorAggregate interface
- *******************************************************************************/
-
- /**
- * Get collection iterator
- *
- * @return \ArrayIterator
- */
- public function getIterator()
- {
- return new ArrayIterator($this->data);
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim;
-
-use Interop\Container\ContainerInterface;
-use Interop\Container\Exception\ContainerException;
-use Pimple\Container as PimpleContainer;
-use Slim\Exception\ContainerValueNotFoundException;
-use Slim\Exception\ContainerException as SlimContainerException;
-
-/**
- * Slim's default DI container is Pimple.
- *
- * Slim\App expects a container that implements Psr\Container\ContainerInterface
- * with these service keys configured and ready for use:
- *
- * - settings: an array or instance of \ArrayAccess
- * - environment: an instance of \Slim\Interfaces\Http\EnvironmentInterface
- * - request: an instance of \Psr\Http\Message\ServerRequestInterface
- * - response: an instance of \Psr\Http\Message\ResponseInterface
- * - router: an instance of \Slim\Interfaces\RouterInterface
- * - foundHandler: an instance of \Slim\Interfaces\InvocationStrategyInterface
- * - errorHandler: a callable with the signature: function($request, $response, $exception)
- * - notFoundHandler: a callable with the signature: function($request, $response)
- * - notAllowedHandler: a callable with the signature: function($request, $response, $allowedHttpMethods)
- * - callableResolver: an instance of \Slim\Interfaces\CallableResolverInterface
- *
- * @property-read array settings
- * @property-read \Slim\Interfaces\Http\EnvironmentInterface environment
- * @property-read \Psr\Http\Message\ServerRequestInterface request
- * @property-read \Psr\Http\Message\ResponseInterface response
- * @property-read \Slim\Interfaces\RouterInterface router
- * @property-read \Slim\Interfaces\InvocationStrategyInterface foundHandler
- * @property-read callable errorHandler
- * @property-read callable notFoundHandler
- * @property-read callable notAllowedHandler
- * @property-read \Slim\Interfaces\CallableResolverInterface callableResolver
- */
-class Container extends PimpleContainer implements ContainerInterface
-{
- /**
- * Default settings
- *
- * @var array
- */
- private $defaultSettings = [
- 'httpVersion' => '1.1',
- 'responseChunkSize' => 4096,
- 'outputBuffering' => 'append',
- 'determineRouteBeforeAppMiddleware' => false,
- 'displayErrorDetails' => false,
- 'addContentLengthHeader' => true,
- 'routerCacheFile' => false,
- ];
-
- /**
- * Create new container
- *
- * @param array $values The parameters or objects.
- */
- public function __construct(array $values = [])
- {
- parent::__construct($values);
-
- $userSettings = isset($values['settings']) ? $values['settings'] : [];
- $this->registerDefaultServices($userSettings);
- }
-
- /**
- * This function registers the default services that Slim needs to work.
- *
- * All services are shared - that is, they are registered such that the
- * same instance is returned on subsequent calls.
- *
- * @param array $userSettings Associative array of application settings
- *
- * @return void
- */
- private function registerDefaultServices($userSettings)
- {
- $defaultSettings = $this->defaultSettings;
-
- /**
- * This service MUST return an array or an
- * instance of \ArrayAccess.
- *
- * @return array|\ArrayAccess
- */
- $this['settings'] = function () use ($userSettings, $defaultSettings) {
- return new Collection(array_merge($defaultSettings, $userSettings));
- };
-
- $defaultProvider = new DefaultServicesProvider();
- $defaultProvider->register($this);
- }
-
- /********************************************************************************
- * Methods to satisfy Psr\Container\ContainerInterface
- *******************************************************************************/
-
- /**
- * Finds an entry of the container by its identifier and returns it.
- *
- * @param string $id Identifier of the entry to look for.
- *
- * @throws ContainerValueNotFoundException No entry was found for this identifier.
- * @throws ContainerException Error while retrieving the entry.
- *
- * @return mixed Entry.
- */
- public function get($id)
- {
- if (!$this->offsetExists($id)) {
- throw new ContainerValueNotFoundException(sprintf('Identifier "%s" is not defined.', $id));
- }
- try {
- return $this->offsetGet($id);
- } catch (\InvalidArgumentException $exception) {
- if ($this->exceptionThrownByContainer($exception)) {
- throw new SlimContainerException(
- sprintf('Container error while retrieving "%s"', $id),
- null,
- $exception
- );
- } else {
- throw $exception;
- }
- }
- }
-
- /**
- * Tests whether an exception needs to be recast for compliance with Container-Interop. This will be if the
- * exception was thrown by Pimple.
- *
- * @param \InvalidArgumentException $exception
- *
- * @return bool
- */
- private function exceptionThrownByContainer(\InvalidArgumentException $exception)
- {
- $trace = $exception->getTrace()[0];
-
- return $trace['class'] === PimpleContainer::class && $trace['function'] === 'offsetGet';
- }
-
- /**
- * Returns true if the container can return an entry for the given identifier.
- * Returns false otherwise.
- *
- * @param string $id Identifier of the entry to look for.
- *
- * @return boolean
- */
- public function has($id)
- {
- return $this->offsetExists($id);
- }
-
-
- /********************************************************************************
- * Magic methods for convenience
- *******************************************************************************/
-
- public function __get($name)
- {
- return $this->get($name);
- }
-
- public function __isset($name)
- {
- return $this->has($name);
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim;
-
-use Psr\Http\Message\ResponseInterface;
-use Psr\Http\Message\ServerRequestInterface;
-use Slim\Handlers\PhpError;
-use Slim\Handlers\Error;
-use Slim\Handlers\NotFound;
-use Slim\Handlers\NotAllowed;
-use Slim\Handlers\Strategies\RequestResponse;
-use Slim\Http\Environment;
-use Slim\Http\Headers;
-use Slim\Http\Request;
-use Slim\Http\Response;
-use Slim\Interfaces\CallableResolverInterface;
-use Slim\Interfaces\Http\EnvironmentInterface;
-use Slim\Interfaces\InvocationStrategyInterface;
-use Slim\Interfaces\RouterInterface;
-
-/**
- * Slim's default Service Provider.
- */
-class DefaultServicesProvider
-{
- /**
- * Register Slim's default services.
- *
- * @param Container $container A DI container implementing ArrayAccess and container-interop.
- */
- public function register($container)
- {
- if (!isset($container['environment'])) {
- /**
- * This service MUST return a shared instance
- * of \Slim\Interfaces\Http\EnvironmentInterface.
- *
- * @return EnvironmentInterface
- */
- $container['environment'] = function () {
- return new Environment($_SERVER);
- };
- }
-
- if (!isset($container['request'])) {
- /**
- * PSR-7 Request object
- *
- * @param Container $container
- *
- * @return ServerRequestInterface
- */
- $container['request'] = function ($container) {
- return Request::createFromEnvironment($container->get('environment'));
- };
- }
-
- if (!isset($container['response'])) {
- /**
- * PSR-7 Response object
- *
- * @param Container $container
- *
- * @return ResponseInterface
- */
- $container['response'] = function ($container) {
- $headers = new Headers(['Content-Type' => 'text/html; charset=UTF-8']);
- $response = new Response(200, $headers);
-
- return $response->withProtocolVersion($container->get('settings')['httpVersion']);
- };
- }
-
- if (!isset($container['router'])) {
- /**
- * This service MUST return a SHARED instance
- * of \Slim\Interfaces\RouterInterface.
- *
- * @param Container $container
- *
- * @return RouterInterface
- */
- $container['router'] = function ($container) {
- $routerCacheFile = false;
- if (isset($container->get('settings')['routerCacheFile'])) {
- $routerCacheFile = $container->get('settings')['routerCacheFile'];
- }
-
-
- $router = (new Router)->setCacheFile($routerCacheFile);
- if (method_exists($router, 'setContainer')) {
- $router->setContainer($container);
- }
-
- return $router;
- };
- }
-
- if (!isset($container['foundHandler'])) {
- /**
- * This service MUST return a SHARED instance
- * of \Slim\Interfaces\InvocationStrategyInterface.
- *
- * @return InvocationStrategyInterface
- */
- $container['foundHandler'] = function () {
- return new RequestResponse;
- };
- }
-
- if (!isset($container['phpErrorHandler'])) {
- /**
- * This service MUST return a callable
- * that accepts three arguments:
- *
- * 1. Instance of \Psr\Http\Message\ServerRequestInterface
- * 2. Instance of \Psr\Http\Message\ResponseInterface
- * 3. Instance of \Error
- *
- * The callable MUST return an instance of
- * \Psr\Http\Message\ResponseInterface.
- *
- * @param Container $container
- *
- * @return callable
- */
- $container['phpErrorHandler'] = function ($container) {
- return new PhpError($container->get('settings')['displayErrorDetails']);
- };
- }
-
- if (!isset($container['errorHandler'])) {
- /**
- * This service MUST return a callable
- * that accepts three arguments:
- *
- * 1. Instance of \Psr\Http\Message\ServerRequestInterface
- * 2. Instance of \Psr\Http\Message\ResponseInterface
- * 3. Instance of \Exception
- *
- * The callable MUST return an instance of
- * \Psr\Http\Message\ResponseInterface.
- *
- * @param Container $container
- *
- * @return callable
- */
- $container['errorHandler'] = function ($container) {
- return new Error(
- $container->get('settings')['displayErrorDetails']
- );
- };
- }
-
- if (!isset($container['notFoundHandler'])) {
- /**
- * This service MUST return a callable
- * that accepts two arguments:
- *
- * 1. Instance of \Psr\Http\Message\ServerRequestInterface
- * 2. Instance of \Psr\Http\Message\ResponseInterface
- *
- * The callable MUST return an instance of
- * \Psr\Http\Message\ResponseInterface.
- *
- * @return callable
- */
- $container['notFoundHandler'] = function () {
- return new NotFound;
- };
- }
-
- if (!isset($container['notAllowedHandler'])) {
- /**
- * This service MUST return a callable
- * that accepts three arguments:
- *
- * 1. Instance of \Psr\Http\Message\ServerRequestInterface
- * 2. Instance of \Psr\Http\Message\ResponseInterface
- * 3. Array of allowed HTTP methods
- *
- * The callable MUST return an instance of
- * \Psr\Http\Message\ResponseInterface.
- *
- * @return callable
- */
- $container['notAllowedHandler'] = function () {
- return new NotAllowed;
- };
- }
-
- if (!isset($container['callableResolver'])) {
- /**
- * Instance of \Slim\Interfaces\CallableResolverInterface
- *
- * @param Container $container
- *
- * @return CallableResolverInterface
- */
- $container['callableResolver'] = function ($container) {
- return new CallableResolver($container);
- };
- }
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-
-namespace Slim;
-
-use Closure;
-use Psr\Container\ContainerInterface;
-
-class DeferredCallable
-{
- use CallableResolverAwareTrait;
-
- private $callable;
- /** @var ContainerInterface */
- private $container;
-
- /**
- * DeferredMiddleware constructor.
- * @param callable|string $callable
- * @param ContainerInterface $container
- */
- public function __construct($callable, ContainerInterface $container = null)
- {
- $this->callable = $callable;
- $this->container = $container;
- }
-
- public function __invoke()
- {
- $callable = $this->resolveCallable($this->callable);
- if ($callable instanceof Closure) {
- $callable = $callable->bindTo($this->container);
- }
-
- $args = func_get_args();
-
- return call_user_func_array($callable, $args);
- }
-}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Error;
+
+use Slim\Exception\HttpException;
+use Slim\Interfaces\ErrorRendererInterface;
+use Throwable;
+
+/**
+ * Abstract Slim application error renderer
+ *
+ * It outputs the error message and diagnostic information in one of the following formats:
+ * JSON, XML, Plain Text or HTML
+ */
+abstract class AbstractErrorRenderer implements ErrorRendererInterface
+{
+ protected string $defaultErrorTitle = 'Slim Application Error';
+
+ protected string $defaultErrorDescription = 'A website error has occurred. Sorry for the temporary inconvenience.';
+
+ protected function getErrorTitle(Throwable $exception): string
+ {
+ if ($exception instanceof HttpException) {
+ return $exception->getTitle();
+ }
+
+ return $this->defaultErrorTitle;
+ }
+
+ protected function getErrorDescription(Throwable $exception): string
+ {
+ if ($exception instanceof HttpException) {
+ return $exception->getDescription();
+ }
+
+ return $this->defaultErrorDescription;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Error\Renderers;
+
+use Slim\Error\AbstractErrorRenderer;
+use Throwable;
+
+use function get_class;
+use function htmlentities;
+use function sprintf;
+
+/**
+ * Default Slim application HTML Error Renderer
+ */
+class HtmlErrorRenderer extends AbstractErrorRenderer
+{
+ public function __invoke(Throwable $exception, bool $displayErrorDetails): string
+ {
+ if ($displayErrorDetails) {
+ $html = '<p>The application could not run because of the following error:</p>';
+ $html .= '<h2>Details</h2>';
+ $html .= $this->renderExceptionFragment($exception);
+ } else {
+ $html = "<p>{$this->getErrorDescription($exception)}</p>";
+ }
+
+ return $this->renderHtmlBody($this->getErrorTitle($exception), $html);
+ }
+
+ private function renderExceptionFragment(Throwable $exception): string
+ {
+ $html = sprintf('<div><strong>Type:</strong> %s</div>', get_class($exception));
+
+ /** @var int|string $code */
+ $code = $exception->getCode();
+ $html .= sprintf('<div><strong>Code:</strong> %s</div>', $code);
+
+ $html .= sprintf('<div><strong>Message:</strong> %s</div>', htmlentities($exception->getMessage()));
+
+ $html .= sprintf('<div><strong>File:</strong> %s</div>', $exception->getFile());
+
+ $html .= sprintf('<div><strong>Line:</strong> %s</div>', $exception->getLine());
+
+ $html .= '<h2>Trace</h2>';
+ $html .= sprintf('<pre>%s</pre>', htmlentities($exception->getTraceAsString()));
+
+ return $html;
+ }
+
+ public function renderHtmlBody(string $title = '', string $html = ''): string
+ {
+ return sprintf(
+ '<!doctype html>' .
+ '<html lang="en">' .
+ ' <head>' .
+ ' <meta charset="utf-8">' .
+ ' <meta name="viewport" content="width=device-width, initial-scale=1">' .
+ ' <title>%s</title>' .
+ ' <style>' .
+ ' body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif}' .
+ ' h1{margin:0;font-size:48px;font-weight:normal;line-height:48px}' .
+ ' strong{display:inline-block;width:65px}' .
+ ' </style>' .
+ ' </head>' .
+ ' <body>' .
+ ' <h1>%s</h1>' .
+ ' <div>%s</div>' .
+ ' <a href="#" onclick="window.history.go(-1)">Go Back</a>' .
+ ' </body>' .
+ '</html>',
+ $title,
+ $title,
+ $html
+ );
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Error\Renderers;
+
+use Slim\Error\AbstractErrorRenderer;
+use Throwable;
+
+use function get_class;
+use function json_encode;
+
+use const JSON_PRETTY_PRINT;
+use const JSON_UNESCAPED_SLASHES;
+
+/**
+ * Default Slim application JSON Error Renderer
+ */
+class JsonErrorRenderer extends AbstractErrorRenderer
+{
+ public function __invoke(Throwable $exception, bool $displayErrorDetails): string
+ {
+ $error = ['message' => $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<string|int>
+ */
+ private function formatExceptionFragment(Throwable $exception): array
+ {
+ /** @var int|string $code */
+ $code = $exception->getCode();
+ return [
+ 'type' => get_class($exception),
+ 'code' => $code,
+ 'message' => $exception->getMessage(),
+ 'file' => $exception->getFile(),
+ 'line' => $exception->getLine(),
+ ];
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Error\Renderers;
+
+use Slim\Error\AbstractErrorRenderer;
+use Throwable;
+
+use function get_class;
+use function htmlentities;
+use function sprintf;
+
+/**
+ * Default Slim application Plain Text Error Renderer
+ */
+class PlainTextErrorRenderer extends AbstractErrorRenderer
+{
+ public function __invoke(Throwable $exception, bool $displayErrorDetails): string
+ {
+ $text = "{$this->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();
+ /** @var int|string $code */
+ $text .= sprintf("Code: %s\n", $code);
+
+ $text .= sprintf("Message: %s\n", htmlentities($exception->getMessage()));
+
+ $text .= sprintf("File: %s\n", $exception->getFile());
+
+ $text .= sprintf("Line: %s\n", $exception->getLine());
+
+ $text .= sprintf('Trace: %s', $exception->getTraceAsString());
+
+ return $text;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Error\Renderers;
+
+use Slim\Error\AbstractErrorRenderer;
+use Throwable;
+
+use function get_class;
+use function sprintf;
+use function str_replace;
+
+/**
+ * Default Slim application XML Error Renderer
+ */
+class XmlErrorRenderer extends AbstractErrorRenderer
+{
+ public function __invoke(Throwable $exception, bool $displayErrorDetails): string
+ {
+ $xml = '<' . '?xml version="1.0" encoding="UTF-8" standalone="yes"?' . ">\n";
+ $xml .= "<error>\n <message>" . $this->createCdataSection($this->getErrorTitle($exception)) . "</message>\n";
+
+ if ($displayErrorDetails) {
+ do {
+ $xml .= " <exception>\n";
+ $xml .= ' <type>' . get_class($exception) . "</type>\n";
+ $xml .= ' <code>' . $exception->getCode() . "</code>\n";
+ $xml .= ' <message>' . $this->createCdataSection($exception->getMessage()) . "</message>\n";
+ $xml .= ' <file>' . $exception->getFile() . "</file>\n";
+ $xml .= ' <line>' . $exception->getLine() . "</line>\n";
+ $xml .= " </exception>\n";
+ } while ($exception = $exception->getPrevious());
+ }
+
+ $xml .= '</error>';
+
+ return $xml;
+ }
+
+ /**
+ * Returns a CDATA section with the given content.
+ */
+ private function createCdataSection(string $content): string
+ {
+ return sprintf('<![CDATA[%s]]>', str_replace(']]>', ']]]]><![CDATA[>', $content));
+ }
+}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Exception;
-
-use InvalidArgumentException;
-use Interop\Container\Exception\ContainerException as InteropContainerException;
-
-/**
- * Container Exception
- */
-class ContainerException extends InvalidArgumentException implements InteropContainerException
-{
-
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Exception;
-
-use RuntimeException;
-use Interop\Container\Exception\NotFoundException as InteropNotFoundException;
-
-/**
- * Not Found Exception
- */
-class ContainerValueNotFoundException extends RuntimeException implements InteropNotFoundException
-{
-
-}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+class HttpBadRequestException extends HttpSpecializedException
+{
+ /**
+ * @var int
+ */
+ protected $code = 400;
+
+ /**
+ * @var string
+ */
+ protected $message = 'Bad request.';
+
+ protected string $title = '400 Bad Request';
+ protected string $description = 'The server cannot or will not process ' .
+ 'the request due to an apparent client error.';
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+use Psr\Http\Message\ServerRequestInterface;
+use RuntimeException;
+use Throwable;
+
+/**
+ * @method int getCode()
+ */
+class HttpException extends RuntimeException
+{
+ protected ServerRequestInterface $request;
+
+ protected string $title = '';
+
+ protected string $description = '';
+
+ public function __construct(
+ ServerRequestInterface $request,
+ string $message = '',
+ int $code = 0,
+ ?Throwable $previous = null
+ ) {
+ parent::__construct($message, $code, $previous);
+ $this->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;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+class HttpForbiddenException extends HttpSpecializedException
+{
+ /**
+ * @var int
+ */
+ protected $code = 403;
+
+ /**
+ * @var string
+ */
+ protected $message = 'Forbidden.';
+
+ protected string $title = '403 Forbidden';
+ protected string $description = 'You are not permitted to perform the requested operation.';
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+class HttpGoneException extends HttpSpecializedException
+{
+ /**
+ * @var int
+ */
+ protected $code = 410;
+
+ /**
+ * @var string
+ */
+ protected $message = 'Gone.';
+
+ protected string $title = '410 Gone';
+ protected string $description = 'The target resource is no longer available at the origin server.';
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+class HttpInternalServerErrorException extends HttpSpecializedException
+{
+ /**
+ * @var int
+ */
+ protected $code = 500;
+
+ /**
+ * @var string
+ */
+ protected $message = 'Internal server error.';
+
+ protected string $title = '500 Internal Server Error';
+ protected string $description = 'Unexpected condition encountered preventing server from fulfilling request.';
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+use function implode;
+
+class HttpMethodNotAllowedException extends HttpSpecializedException
+{
+ /**
+ * @var string[]
+ */
+ protected array $allowedMethods = [];
+
+ /**
+ * @var int
+ */
+ protected $code = 405;
+
+ /**
+ * @var string
+ */
+ protected $message = 'Method not allowed.';
+
+ protected string $title = '405 Method Not Allowed';
+ protected string $description = 'The request method is not supported for the requested resource.';
+
+ /**
+ * @return string[]
+ */
+ public function getAllowedMethods(): array
+ {
+ return $this->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;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+class HttpNotFoundException extends HttpSpecializedException
+{
+ /**
+ * @var int
+ */
+ protected $code = 404;
+
+ /**
+ * @var string
+ */
+ protected $message = 'Not found.';
+
+ protected string $title = '404 Not Found';
+ protected string $description = 'The requested resource could not be found. Please verify the URI and try again.';
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+class HttpNotImplementedException extends HttpSpecializedException
+{
+ /**
+ * @var int
+ */
+ protected $code = 501;
+
+ /**
+ * @var string
+ */
+ protected $message = 'Not implemented.';
+
+ protected string $title = '501 Not Implemented';
+ protected string $description = 'The server does not support the functionality required to fulfill the request.';
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+use Psr\Http\Message\ServerRequestInterface;
+use Throwable;
+
+abstract class HttpSpecializedException extends HttpException
+{
+ /**
+ * @param ServerRequestInterface $request
+ * @param string|null $message
+ * @param Throwable|null $previous
+ */
+ public function __construct(ServerRequestInterface $request, ?string $message = null, ?Throwable $previous = null)
+ {
+ if ($message !== null) {
+ $this->message = $message;
+ }
+
+ parent::__construct($request, $this->message, $this->code, $previous);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Exception;
+
+class HttpUnauthorizedException extends HttpSpecializedException
+{
+ /**
+ * @var int
+ */
+ protected $code = 401;
+
+ /**
+ * @var string
+ */
+ protected $message = 'Unauthorized.';
+
+ protected string $title = '401 Unauthorized';
+ protected string $description = 'The request requires valid user authentication.';
+}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Exception;
-
-use Psr\Http\Message\ServerRequestInterface;
-
-class InvalidMethodException extends \InvalidArgumentException
-{
- protected $request;
-
- public function __construct(ServerRequestInterface $request, $method)
- {
- $this->request = $request;
- parent::__construct(sprintf('Unsupported HTTP method "%s" provided', $method));
- }
-
- public function getRequest()
- {
- return $this->request;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Exception;
-
-use Psr\Http\Message\ServerRequestInterface;
-use Psr\Http\Message\ResponseInterface;
-
-class MethodNotAllowedException extends SlimException
-{
- /**
- * HTTP methods allowed
- *
- * @var string[]
- */
- protected $allowedMethods;
-
- /**
- * Create new exception
- *
- * @param ServerRequestInterface $request
- * @param ResponseInterface $response
- * @param string[] $allowedMethods
- */
- public function __construct(ServerRequestInterface $request, ResponseInterface $response, array $allowedMethods)
- {
- parent::__construct($request, $response);
- $this->allowedMethods = $allowedMethods;
- }
-
- /**
- * Get allowed methods
- *
- * @return string[]
- */
- public function getAllowedMethods()
- {
- return $this->allowedMethods;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Exception;
-
-class NotFoundException extends SlimException
-{
-
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Exception;
-
-use Exception;
-use Psr\Http\Message\ServerRequestInterface;
-use Psr\Http\Message\ResponseInterface;
-
-/**
- * Stop Exception
- *
- * This Exception is thrown when the Slim application needs to abort
- * processing and return control flow to the outer PHP script.
- */
-class SlimException extends Exception
-{
- /**
- * A request object
- *
- * @var ServerRequestInterface
- */
- protected $request;
-
- /**
- * A response object to send to the HTTP client
- *
- * @var ResponseInterface
- */
- protected $response;
-
- /**
- * Create new exception
- *
- * @param ServerRequestInterface $request
- * @param ResponseInterface $response
- */
- public function __construct(ServerRequestInterface $request, ResponseInterface $response)
- {
- parent::__construct();
- $this->request = $request;
- $this->response = $response;
- }
-
- /**
- * Get request
- *
- * @return ServerRequestInterface
- */
- public function getRequest()
- {
- return $this->request;
- }
-
- /**
- * Get response
- *
- * @return ResponseInterface
- */
- public function getResponse()
- {
- return $this->response;
- }
-}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory;
+
+use Psr\Container\ContainerInterface;
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\StreamFactoryInterface;
+use RuntimeException;
+use Slim\App;
+use Slim\Factory\Psr17\Psr17Factory;
+use Slim\Factory\Psr17\Psr17FactoryProvider;
+use Slim\Factory\Psr17\SlimHttpPsr17Factory;
+use Slim\Interfaces\CallableResolverInterface;
+use Slim\Interfaces\MiddlewareDispatcherInterface;
+use Slim\Interfaces\Psr17FactoryProviderInterface;
+use Slim\Interfaces\RouteCollectorInterface;
+use Slim\Interfaces\RouteResolverInterface;
+
+class AppFactory
+{
+ protected static ?Psr17FactoryProviderInterface $psr17FactoryProvider = null;
+
+ protected static ?ResponseFactoryInterface $responseFactory = null;
+
+ protected static ?StreamFactoryInterface $streamFactory = null;
+
+ protected static ?ContainerInterface $container = null;
+
+ protected static ?CallableResolverInterface $callableResolver = null;
+
+ protected static ?RouteCollectorInterface $routeCollector = null;
+
+ protected static ?RouteResolverInterface $routeResolver = null;
+
+ protected static ?MiddlewareDispatcherInterface $middlewareDispatcher = null;
+
+ protected static bool $slimHttpDecoratorsAutomaticDetectionEnabled = true;
+
+ 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
+ );
+ }
+
+ 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;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+class GuzzlePsr17Factory extends Psr17Factory
+{
+ protected static string $responseFactoryClass = 'GuzzleHttp\Psr7\HttpFactory';
+ protected static string $streamFactoryClass = 'GuzzleHttp\Psr7\HttpFactory';
+ protected static string $serverRequestCreatorClass = 'GuzzleHttp\Psr7\ServerRequest';
+ protected static string $serverRequestCreatorMethod = 'fromGlobals';
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+class HttpSoftPsr17Factory extends Psr17Factory
+{
+ protected static string $responseFactoryClass = 'HttpSoft\Message\ResponseFactory';
+ protected static string $streamFactoryClass = 'HttpSoft\Message\StreamFactory';
+ protected static string $serverRequestCreatorClass = 'HttpSoft\ServerRequest\ServerRequestCreator';
+ protected static string $serverRequestCreatorMethod = 'createFromGlobals';
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+class LaminasDiactorosPsr17Factory extends Psr17Factory
+{
+ protected static string $responseFactoryClass = 'Laminas\Diactoros\ResponseFactory';
+ protected static string $streamFactoryClass = 'Laminas\Diactoros\StreamFactory';
+ protected static string $serverRequestCreatorClass = 'Laminas\Diactoros\ServerRequestFactory';
+ protected static string $serverRequestCreatorMethod = 'fromGlobals';
+}
--- /dev/null
+<?php
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+use Slim\Interfaces\ServerRequestCreatorInterface;
+
+class NyholmPsr17Factory extends Psr17Factory
+{
+ protected static string $responseFactoryClass = 'Nyholm\Psr7\Factory\Psr17Factory';
+ protected static string $streamFactoryClass = 'Nyholm\Psr7\Factory\Psr17Factory';
+ protected static string $serverRequestCreatorClass = 'Nyholm\Psr7Server\ServerRequestCreator';
+ protected static string $serverRequestCreatorMethod = 'fromGlobals';
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function getServerRequestCreator(): ServerRequestCreatorInterface
+ {
+ /*
+ * Nyholm Psr17Factory implements all factories in one unified
+ * factory which implements all of the PSR-17 factory interfaces
+ */
+ $psr17Factory = new static::$responseFactoryClass();
+
+ $serverRequestCreator = new static::$serverRequestCreatorClass(
+ $psr17Factory,
+ $psr17Factory,
+ $psr17Factory,
+ $psr17Factory
+ );
+
+ return new ServerRequestCreator($serverRequestCreator, static::$serverRequestCreatorMethod);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\StreamFactoryInterface;
+use RuntimeException;
+use Slim\Interfaces\Psr17FactoryInterface;
+use Slim\Interfaces\ServerRequestCreatorInterface;
+
+use function class_exists;
+use function get_called_class;
+
+abstract class Psr17Factory implements Psr17FactoryInterface
+{
+ protected static string $responseFactoryClass;
+
+ protected static string $streamFactoryClass;
+
+ protected static string $serverRequestCreatorClass;
+
+ protected static string $serverRequestCreatorMethod;
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function getResponseFactory(): ResponseFactoryInterface
+ {
+ if (
+ !static::isResponseFactoryAvailable()
+ || !(($responseFactory = new static::$responseFactoryClass()) instanceof ResponseFactoryInterface)
+ ) {
+ throw new RuntimeException(get_called_class() . ' could not instantiate a response factory.');
+ }
+
+ return $responseFactory;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function getStreamFactory(): StreamFactoryInterface
+ {
+ if (
+ !static::isStreamFactoryAvailable()
+ || !(($streamFactory = new static::$streamFactoryClass()) instanceof StreamFactoryInterface)
+ ) {
+ throw new RuntimeException(get_called_class() . ' could not instantiate a stream factory.');
+ }
+
+ return $streamFactory;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function getServerRequestCreator(): ServerRequestCreatorInterface
+ {
+ if (!static::isServerRequestCreatorAvailable()) {
+ throw new RuntimeException(get_called_class() . ' could not instantiate a server request creator.');
+ }
+
+ return new ServerRequestCreator(static::$serverRequestCreatorClass, static::$serverRequestCreatorMethod);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function isResponseFactoryAvailable(): bool
+ {
+ return static::$responseFactoryClass && class_exists(static::$responseFactoryClass);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function isStreamFactoryAvailable(): bool
+ {
+ return static::$streamFactoryClass && class_exists(static::$streamFactoryClass);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function isServerRequestCreatorAvailable(): bool
+ {
+ return (
+ static::$serverRequestCreatorClass
+ && static::$serverRequestCreatorMethod
+ && class_exists(static::$serverRequestCreatorClass)
+ );
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+use Slim\Interfaces\Psr17FactoryProviderInterface;
+
+use function array_unshift;
+
+class Psr17FactoryProvider implements Psr17FactoryProviderInterface
+{
+ /**
+ * @var string[]
+ */
+ protected static array $factories = [
+ SlimPsr17Factory::class,
+ HttpSoftPsr17Factory::class,
+ NyholmPsr17Factory::class,
+ LaminasDiactorosPsr17Factory::class,
+ GuzzlePsr17Factory::class,
+ ];
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function getFactories(): array
+ {
+ return static::$factories;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function setFactories(array $factories): void
+ {
+ static::$factories = $factories;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function addFactory(string $factory): void
+ {
+ array_unshift(static::$factories, $factory);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+use Closure;
+use Psr\Http\Message\ServerRequestInterface;
+use Slim\Interfaces\ServerRequestCreatorInterface;
+
+class ServerRequestCreator implements ServerRequestCreatorInterface
+{
+ /**
+ * @var object|string
+ */
+ protected $serverRequestCreator;
+
+ protected string $serverRequestCreatorMethod;
+
+ /**
+ * @param object|string $serverRequestCreator
+ */
+ public function __construct($serverRequestCreator, string $serverRequestCreatorMethod)
+ {
+ $this->serverRequestCreator = $serverRequestCreator;
+ $this->serverRequestCreatorMethod = $serverRequestCreatorMethod;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function createServerRequestFromGlobals(): ServerRequestInterface
+ {
+ /** @var callable $callable */
+ $callable = [$this->serverRequestCreator, $this->serverRequestCreatorMethod];
+ return (Closure::fromCallable($callable))();
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\StreamFactoryInterface;
+use RuntimeException;
+
+class SlimHttpPsr17Factory extends Psr17Factory
+{
+ protected static string $responseFactoryClass = 'Slim\Http\Factory\DecoratedResponseFactory';
+
+ /**
+ * @throws RuntimeException when the factory could not be instantiated
+ */
+ public static function createDecoratedResponseFactory(
+ ResponseFactoryInterface $responseFactory,
+ StreamFactoryInterface $streamFactory
+ ): ResponseFactoryInterface {
+ if (
+ !((
+ $decoratedResponseFactory = new static::$responseFactoryClass($responseFactory, $streamFactory)
+ ) instanceof ResponseFactoryInterface
+ )
+ ) {
+ throw new RuntimeException(get_called_class() . ' could not instantiate a decorated response factory.');
+ }
+
+ return $decoratedResponseFactory;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+use Psr\Http\Message\ServerRequestInterface;
+use RuntimeException;
+use Slim\Interfaces\ServerRequestCreatorInterface;
+
+use function class_exists;
+
+class SlimHttpServerRequestCreator implements ServerRequestCreatorInterface
+{
+ protected ServerRequestCreatorInterface $serverRequestCreator;
+
+ protected static string $serverRequestDecoratorClass = 'Slim\Http\ServerRequest';
+
+ public function __construct(ServerRequestCreatorInterface $serverRequestCreator)
+ {
+ $this->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);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory\Psr17;
+
+class SlimPsr17Factory extends Psr17Factory
+{
+ protected static string $responseFactoryClass = 'Slim\Psr7\Factory\ResponseFactory';
+ protected static string $streamFactoryClass = 'Slim\Psr7\Factory\StreamFactory';
+ protected static string $serverRequestCreatorClass = 'Slim\Psr7\Factory\ServerRequestFactory';
+ protected static string $serverRequestCreatorMethod = 'createFromGlobals';
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Factory;
+
+use RuntimeException;
+use Slim\Factory\Psr17\Psr17Factory;
+use Slim\Factory\Psr17\Psr17FactoryProvider;
+use Slim\Factory\Psr17\SlimHttpServerRequestCreator;
+use Slim\Interfaces\Psr17FactoryProviderInterface;
+use Slim\Interfaces\ServerRequestCreatorInterface;
+
+class ServerRequestCreatorFactory
+{
+ protected static ?Psr17FactoryProviderInterface $psr17FactoryProvider = null;
+
+ protected static ?ServerRequestCreatorInterface $serverRequestCreator = null;
+
+ protected static bool $slimHttpDecoratorsAutomaticDetectionEnabled = true;
+
+ public static function create(): ServerRequestCreatorInterface
+ {
+ return static::determineServerRequestCreator();
+ }
+
+ /**
+ * @throws RuntimeException
+ */
+ public static function determineServerRequestCreator(): ServerRequestCreatorInterface
+ {
+ if (static::$serverRequestCreator) {
+ return static::attemptServerRequestCreatorDecoration(static::$serverRequestCreator);
+ }
+
+ $psr17FactoryProvider = static::$psr17FactoryProvider ?? new Psr17FactoryProvider();
+
+ /** @var Psr17Factory $psr17Factory */
+ foreach ($psr17FactoryProvider->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;
+ }
+}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Handlers;
-
-/**
- * Abstract Slim application error handler
- */
-abstract class AbstractError extends AbstractHandler
-{
- /**
- * @var bool
- */
- protected $displayErrorDetails;
-
- /**
- * Constructor
- *
- * @param bool $displayErrorDetails Set to true to display full details
- */
- public function __construct($displayErrorDetails = false)
- {
- $this->displayErrorDetails = (bool) $displayErrorDetails;
- }
-
- /**
- * Write to the error log if displayErrorDetails is false
- *
- * @param \Exception|\Throwable $throwable
- *
- * @return void
- */
- protected function writeToErrorLog($throwable)
- {
- if ($this->displayErrorDetails) {
- return;
- }
-
- $message = 'Slim Application Error:' . PHP_EOL;
- $message .= $this->renderThrowableAsText($throwable);
- while ($throwable = $throwable->getPrevious()) {
- $message .= PHP_EOL . 'Previous error:' . PHP_EOL;
- $message .= $this->renderThrowableAsText($throwable);
- }
-
- $message .= PHP_EOL . 'View in rendered output by enabling the "displayErrorDetails" setting.' . PHP_EOL;
-
- $this->logError($message);
- }
-
- /**
- * Render error as Text.
- *
- * @param \Exception|\Throwable $throwable
- *
- * @return string
- */
- protected function renderThrowableAsText($throwable)
- {
- $text = sprintf('Type: %s' . PHP_EOL, get_class($throwable));
-
- if ($code = $throwable->getCode()) {
- $text .= sprintf('Code: %s' . PHP_EOL, $code);
- }
-
- if ($message = $throwable->getMessage()) {
- $text .= sprintf('Message: %s' . PHP_EOL, htmlentities($message));
- }
-
- if ($file = $throwable->getFile()) {
- $text .= sprintf('File: %s' . PHP_EOL, $file);
- }
-
- if ($line = $throwable->getLine()) {
- $text .= sprintf('Line: %s' . PHP_EOL, $line);
- }
-
- if ($trace = $throwable->getTraceAsString()) {
- $text .= sprintf('Trace: %s', $trace);
- }
-
- return $text;
- }
-
- /**
- * Wraps the error_log function so that this can be easily tested
- *
- * @param $message
- */
- protected function logError($message)
- {
- error_log($message);
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Handlers;
-
-use Psr\Http\Message\ServerRequestInterface;
-
-/**
- * Abstract Slim application handler
- */
-abstract class AbstractHandler
-{
- /**
- * Known handled content types
- *
- * @var array
- */
- protected $knownContentTypes = [
- 'application/json',
- 'application/xml',
- 'text/xml',
- 'text/html',
- ];
-
- /**
- * 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.
- *
- * @param ServerRequestInterface $request
- * @return string
- */
- protected function determineContentType(ServerRequestInterface $request)
- {
- $acceptHeader = $request->getHeaderLine('Accept');
- $selectedContentTypes = array_intersect(explode(',', $acceptHeader), $this->knownContentTypes);
-
- if (count($selectedContentTypes)) {
- return current($selectedContentTypes);
- }
-
- // handle +json and +xml specially
- if (preg_match('/\+(json|xml)/', $acceptHeader, $matches)) {
- $mediaType = 'application/' . $matches[1];
- if (in_array($mediaType, $this->knownContentTypes)) {
- return $mediaType;
- }
- }
-
- return 'text/html';
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Handlers;
-
-use Psr\Http\Message\ResponseInterface;
-use Psr\Http\Message\ServerRequestInterface;
-use Slim\Http\Body;
-use UnexpectedValueException;
-
-/**
- * Default Slim application error handler
- *
- * It outputs the error message and diagnostic information in either JSON, XML,
- * or HTML based on the Accept header.
- */
-class Error extends AbstractError
-{
- /**
- * Invoke error handler
- *
- * @param ServerRequestInterface $request The most recent Request object
- * @param ResponseInterface $response The most recent Response object
- * @param \Exception $exception The caught Exception object
- *
- * @return ResponseInterface
- * @throws UnexpectedValueException
- */
- public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Exception $exception)
- {
- $contentType = $this->determineContentType($request);
- switch ($contentType) {
- case 'application/json':
- $output = $this->renderJsonErrorMessage($exception);
- break;
-
- case 'text/xml':
- case 'application/xml':
- $output = $this->renderXmlErrorMessage($exception);
- break;
-
- case 'text/html':
- $output = $this->renderHtmlErrorMessage($exception);
- break;
-
- default:
- throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType);
- }
-
- $this->writeToErrorLog($exception);
-
- $body = new Body(fopen('php://temp', 'r+'));
- $body->write($output);
-
- return $response
- ->withStatus(500)
- ->withHeader('Content-type', $contentType)
- ->withBody($body);
- }
-
- /**
- * Render HTML error page
- *
- * @param \Exception $exception
- *
- * @return string
- */
- protected function renderHtmlErrorMessage(\Exception $exception)
- {
- $title = 'Slim Application Error';
-
- if ($this->displayErrorDetails) {
- $html = '<p>The application could not run because of the following error:</p>';
- $html .= '<h2>Details</h2>';
- $html .= $this->renderHtmlException($exception);
-
- while ($exception = $exception->getPrevious()) {
- $html .= '<h2>Previous exception</h2>';
- $html .= $this->renderHtmlExceptionOrError($exception);
- }
- } else {
- $html = '<p>A website error has occurred. Sorry for the temporary inconvenience.</p>';
- }
-
- $output = sprintf(
- "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" .
- "<title>%s</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana," .
- "sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{" .
- "display:inline-block;width:65px;}</style></head><body><h1>%s</h1>%s</body></html>",
- $title,
- $title,
- $html
- );
-
- return $output;
- }
-
- /**
- * Render exception as HTML.
- *
- * Provided for backwards compatibility; use renderHtmlExceptionOrError().
- *
- * @param \Exception $exception
- *
- * @return string
- */
- protected function renderHtmlException(\Exception $exception)
- {
- return $this->renderHtmlExceptionOrError($exception);
- }
-
- /**
- * Render exception or error as HTML.
- *
- * @param \Exception|\Error $exception
- *
- * @return string
- */
- protected function renderHtmlExceptionOrError($exception)
- {
- if (!$exception instanceof \Exception && !$exception instanceof \Error) {
- throw new \RuntimeException("Unexpected type. Expected Exception or Error.");
- }
-
- $html = sprintf('<div><strong>Type:</strong> %s</div>', get_class($exception));
-
- if (($code = $exception->getCode())) {
- $html .= sprintf('<div><strong>Code:</strong> %s</div>', $code);
- }
-
- if (($message = $exception->getMessage())) {
- $html .= sprintf('<div><strong>Message:</strong> %s</div>', htmlentities($message));
- }
-
- if (($file = $exception->getFile())) {
- $html .= sprintf('<div><strong>File:</strong> %s</div>', $file);
- }
-
- if (($line = $exception->getLine())) {
- $html .= sprintf('<div><strong>Line:</strong> %s</div>', $line);
- }
-
- if (($trace = $exception->getTraceAsString())) {
- $html .= '<h2>Trace</h2>';
- $html .= sprintf('<pre>%s</pre>', htmlentities($trace));
- }
-
- return $html;
- }
-
- /**
- * Render JSON error
- *
- * @param \Exception $exception
- *
- * @return string
- */
- protected function renderJsonErrorMessage(\Exception $exception)
- {
- $error = [
- 'message' => 'Slim Application Error',
- ];
-
- if ($this->displayErrorDetails) {
- $error['exception'] = [];
-
- do {
- $error['exception'][] = [
- 'type' => get_class($exception),
- 'code' => $exception->getCode(),
- 'message' => $exception->getMessage(),
- 'file' => $exception->getFile(),
- 'line' => $exception->getLine(),
- 'trace' => explode("\n", $exception->getTraceAsString()),
- ];
- } while ($exception = $exception->getPrevious());
- }
-
- return json_encode($error, JSON_PRETTY_PRINT);
- }
-
- /**
- * Render XML error
- *
- * @param \Exception $exception
- *
- * @return string
- */
- protected function renderXmlErrorMessage(\Exception $exception)
- {
- $xml = "<error>\n <message>Slim Application Error</message>\n";
- if ($this->displayErrorDetails) {
- do {
- $xml .= " <exception>\n";
- $xml .= " <type>" . get_class($exception) . "</type>\n";
- $xml .= " <code>" . $exception->getCode() . "</code>\n";
- $xml .= " <message>" . $this->createCdataSection($exception->getMessage()) . "</message>\n";
- $xml .= " <file>" . $exception->getFile() . "</file>\n";
- $xml .= " <line>" . $exception->getLine() . "</line>\n";
- $xml .= " <trace>" . $this->createCdataSection($exception->getTraceAsString()) . "</trace>\n";
- $xml .= " </exception>\n";
- } while ($exception = $exception->getPrevious());
- }
- $xml .= "</error>";
-
- return $xml;
- }
-
- /**
- * Returns a CDATA section with the given content.
- *
- * @param string $content
- * @return string
- */
- private function createCdataSection($content)
- {
- return sprintf('<![CDATA[%s]]>', str_replace(']]>', ']]]]><![CDATA[>', $content));
- }
-}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Handlers;
+
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Log\LoggerInterface;
+use RuntimeException;
+use Slim\Error\Renderers\HtmlErrorRenderer;
+use Slim\Error\Renderers\JsonErrorRenderer;
+use Slim\Error\Renderers\PlainTextErrorRenderer;
+use Slim\Error\Renderers\XmlErrorRenderer;
+use Slim\Exception\HttpException;
+use Slim\Exception\HttpMethodNotAllowedException;
+use Slim\Interfaces\CallableResolverInterface;
+use Slim\Interfaces\ErrorHandlerInterface;
+use Slim\Interfaces\ErrorRendererInterface;
+use Slim\Logger;
+use Throwable;
+
+use function array_intersect;
+use function array_key_exists;
+use function array_keys;
+use function call_user_func;
+use function count;
+use function current;
+use function explode;
+use function implode;
+use function next;
+use function preg_match;
+
+/**
+ * Default Slim application error handler
+ *
+ * It outputs the error message and diagnostic information in one of the following formats:
+ * JSON, XML, Plain Text or HTML based on the Accept header.
+ */
+class ErrorHandler implements ErrorHandlerInterface
+{
+ protected string $defaultErrorRendererContentType = 'text/html';
+
+ /**
+ * @var ErrorRendererInterface|string|callable
+ */
+ protected $defaultErrorRenderer = HtmlErrorRenderer::class;
+
+ /**
+ * @var ErrorRendererInterface|string|callable
+ */
+ protected $logErrorRenderer = PlainTextErrorRenderer::class;
+
+ /**
+ * @var array<string|callable>
+ */
+ 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->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;
+ }
+}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Handlers;
-
-use Psr\Http\Message\ServerRequestInterface;
-use Psr\Http\Message\ResponseInterface;
-use Slim\Http\Body;
-use UnexpectedValueException;
-
-/**
- * Default Slim application not allowed handler
- *
- * It outputs a simple message in either JSON, XML or HTML based on the
- * Accept header.
- */
-class NotAllowed extends AbstractHandler
-{
- /**
- * Invoke error handler
- *
- * @param ServerRequestInterface $request The most recent Request object
- * @param ResponseInterface $response The most recent Response object
- * @param string[] $methods Allowed HTTP methods
- *
- * @return ResponseInterface
- * @throws UnexpectedValueException
- */
- public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $methods)
- {
- if ($request->getMethod() === 'OPTIONS') {
- $status = 200;
- $contentType = 'text/plain';
- $output = $this->renderPlainOptionsMessage($methods);
- } else {
- $status = 405;
- $contentType = $this->determineContentType($request);
- switch ($contentType) {
- case 'application/json':
- $output = $this->renderJsonNotAllowedMessage($methods);
- break;
-
- case 'text/xml':
- case 'application/xml':
- $output = $this->renderXmlNotAllowedMessage($methods);
- break;
-
- case 'text/html':
- $output = $this->renderHtmlNotAllowedMessage($methods);
- break;
- default:
- throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType);
- }
- }
-
- $body = new Body(fopen('php://temp', 'r+'));
- $body->write($output);
- $allow = implode(', ', $methods);
-
- return $response
- ->withStatus($status)
- ->withHeader('Content-type', $contentType)
- ->withHeader('Allow', $allow)
- ->withBody($body);
- }
-
- /**
- * Render PLAIN message for OPTIONS response
- *
- * @param array $methods
- * @return string
- */
- protected function renderPlainOptionsMessage($methods)
- {
- $allow = implode(', ', $methods);
-
- return 'Allowed methods: ' . $allow;
- }
-
- /**
- * Render JSON not allowed message
- *
- * @param array $methods
- * @return string
- */
- protected function renderJsonNotAllowedMessage($methods)
- {
- $allow = implode(', ', $methods);
-
- return '{"message":"Method not allowed. Must be one of: ' . $allow . '"}';
- }
-
- /**
- * Render XML not allowed message
- *
- * @param array $methods
- * @return string
- */
- protected function renderXmlNotAllowedMessage($methods)
- {
- $allow = implode(', ', $methods);
-
- return "<root><message>Method not allowed. Must be one of: $allow</message></root>";
- }
-
- /**
- * Render HTML not allowed message
- *
- * @param array $methods
- * @return string
- */
- protected function renderHtmlNotAllowedMessage($methods)
- {
- $allow = implode(', ', $methods);
- $output = <<<END
-<html>
- <head>
- <title>Method not allowed</title>
- <style>
- body{
- margin:0;
- padding:30px;
- font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;
- }
- h1{
- margin:0;
- font-size:48px;
- font-weight:normal;
- line-height:48px;
- }
- </style>
- </head>
- <body>
- <h1>Method not allowed</h1>
- <p>Method not allowed. Must be one of: <strong>$allow</strong></p>
- </body>
-</html>
-END;
-
- return $output;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Handlers;
-
-use Psr\Http\Message\ServerRequestInterface;
-use Psr\Http\Message\ResponseInterface;
-use Slim\Http\Body;
-use UnexpectedValueException;
-
-/**
- * Default Slim application not found handler.
- *
- * It outputs a simple message in either JSON, XML or HTML based on the
- * Accept header.
- */
-class NotFound extends AbstractHandler
-{
- /**
- * Invoke not found handler
- *
- * @param ServerRequestInterface $request The most recent Request object
- * @param ResponseInterface $response The most recent Response object
- *
- * @return ResponseInterface
- * @throws UnexpectedValueException
- */
- public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
- {
- if ($request->getMethod() === 'OPTIONS') {
- $contentType = 'text/plain';
- $output = $this->renderPlainNotFoundOutput();
- } else {
- $contentType = $this->determineContentType($request);
- switch ($contentType) {
- case 'application/json':
- $output = $this->renderJsonNotFoundOutput();
- break;
-
- case 'text/xml':
- case 'application/xml':
- $output = $this->renderXmlNotFoundOutput();
- break;
-
- case 'text/html':
- $output = $this->renderHtmlNotFoundOutput($request);
- break;
-
- default:
- throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType);
- }
- }
-
- $body = new Body(fopen('php://temp', 'r+'));
- $body->write($output);
-
- return $response->withStatus(404)
- ->withHeader('Content-Type', $contentType)
- ->withBody($body);
- }
-
- /**
- * Render plain not found message
- *
- * @return ResponseInterface
- */
- protected function renderPlainNotFoundOutput()
- {
- return 'Not found';
- }
-
- /**
- * Return a response for application/json content not found
- *
- * @return ResponseInterface
- */
- protected function renderJsonNotFoundOutput()
- {
- return '{"message":"Not found"}';
- }
-
- /**
- * Return a response for xml content not found
- *
- * @return ResponseInterface
- */
- protected function renderXmlNotFoundOutput()
- {
- return '<root><message>Not found</message></root>';
- }
-
- /**
- * Return a response for text/html content not found
- *
- * @param ServerRequestInterface $request The most recent Request object
- *
- * @return ResponseInterface
- */
- protected function renderHtmlNotFoundOutput(ServerRequestInterface $request)
- {
- $homeUrl = (string)($request->getUri()->withPath('')->withQuery('')->withFragment(''));
- return <<<END
-<html>
- <head>
- <title>Page Not Found</title>
- <style>
- body{
- margin:0;
- padding:30px;
- font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;
- }
- h1{
- margin:0;
- font-size:48px;
- font-weight:normal;
- line-height:48px;
- }
- strong{
- display:inline-block;
- width:65px;
- }
- </style>
- </head>
- <body>
- <h1>Page Not Found</h1>
- <p>
- The page you are looking for could not be found. Check the address bar
- to ensure your URL is spelled correctly. If all else fails, you can
- visit our home page at the link below.
- </p>
- <a href='$homeUrl'>Visit the Home Page</a>
- </body>
-</html>
-END;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Handlers;
-
-use Psr\Http\Message\ResponseInterface;
-use Psr\Http\Message\ServerRequestInterface;
-use Slim\Http\Body;
-use UnexpectedValueException;
-
-/**
- * Default Slim application error handler for PHP 7+ Throwables
- *
- * It outputs the error message and diagnostic information in either JSON, XML,
- * or HTML based on the Accept header.
- */
-class PhpError extends AbstractError
-{
- /**
- * Invoke error handler
- *
- * @param ServerRequestInterface $request The most recent Request object
- * @param ResponseInterface $response The most recent Response object
- * @param \Throwable $error The caught Throwable object
- *
- * @return ResponseInterface
- * @throws UnexpectedValueException
- */
- public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Throwable $error)
- {
- $contentType = $this->determineContentType($request);
- switch ($contentType) {
- case 'application/json':
- $output = $this->renderJsonErrorMessage($error);
- break;
-
- case 'text/xml':
- case 'application/xml':
- $output = $this->renderXmlErrorMessage($error);
- break;
-
- case 'text/html':
- $output = $this->renderHtmlErrorMessage($error);
- break;
- default:
- throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType);
- }
-
- $this->writeToErrorLog($error);
-
- $body = new Body(fopen('php://temp', 'r+'));
- $body->write($output);
-
- return $response
- ->withStatus(500)
- ->withHeader('Content-type', $contentType)
- ->withBody($body);
- }
-
- /**
- * Render HTML error page
- *
- * @param \Throwable $error
- *
- * @return string
- */
- protected function renderHtmlErrorMessage(\Throwable $error)
- {
- $title = 'Slim Application Error';
-
- if ($this->displayErrorDetails) {
- $html = '<p>The application could not run because of the following error:</p>';
- $html .= '<h2>Details</h2>';
- $html .= $this->renderHtmlError($error);
-
- while ($error = $error->getPrevious()) {
- $html .= '<h2>Previous error</h2>';
- $html .= $this->renderHtmlError($error);
- }
- } else {
- $html = '<p>A website error has occurred. Sorry for the temporary inconvenience.</p>';
- }
-
- $output = sprintf(
- "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" .
- "<title>%s</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana," .
- "sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{" .
- "display:inline-block;width:65px;}</style></head><body><h1>%s</h1>%s</body></html>",
- $title,
- $title,
- $html
- );
-
- return $output;
- }
-
- /**
- * Render error as HTML.
- *
- * @param \Throwable $error
- *
- * @return string
- */
- protected function renderHtmlError(\Throwable $error)
- {
- $html = sprintf('<div><strong>Type:</strong> %s</div>', get_class($error));
-
- if (($code = $error->getCode())) {
- $html .= sprintf('<div><strong>Code:</strong> %s</div>', $code);
- }
-
- if (($message = $error->getMessage())) {
- $html .= sprintf('<div><strong>Message:</strong> %s</div>', htmlentities($message));
- }
-
- if (($file = $error->getFile())) {
- $html .= sprintf('<div><strong>File:</strong> %s</div>', $file);
- }
-
- if (($line = $error->getLine())) {
- $html .= sprintf('<div><strong>Line:</strong> %s</div>', $line);
- }
-
- if (($trace = $error->getTraceAsString())) {
- $html .= '<h2>Trace</h2>';
- $html .= sprintf('<pre>%s</pre>', htmlentities($trace));
- }
-
- return $html;
- }
-
- /**
- * Render JSON error
- *
- * @param \Throwable $error
- *
- * @return string
- */
- protected function renderJsonErrorMessage(\Throwable $error)
- {
- $json = [
- 'message' => 'Slim Application Error',
- ];
-
- if ($this->displayErrorDetails) {
- $json['error'] = [];
-
- do {
- $json['error'][] = [
- 'type' => get_class($error),
- 'code' => $error->getCode(),
- 'message' => $error->getMessage(),
- 'file' => $error->getFile(),
- 'line' => $error->getLine(),
- 'trace' => explode("\n", $error->getTraceAsString()),
- ];
- } while ($error = $error->getPrevious());
- }
-
- return json_encode($json, JSON_PRETTY_PRINT);
- }
-
- /**
- * Render XML error
- *
- * @param \Throwable $error
- *
- * @return string
- */
- protected function renderXmlErrorMessage(\Throwable $error)
- {
- $xml = "<error>\n <message>Slim Application Error</message>\n";
- if ($this->displayErrorDetails) {
- do {
- $xml .= " <error>\n";
- $xml .= " <type>" . get_class($error) . "</type>\n";
- $xml .= " <code>" . $error->getCode() . "</code>\n";
- $xml .= " <message>" . $this->createCdataSection($error->getMessage()) . "</message>\n";
- $xml .= " <file>" . $error->getFile() . "</file>\n";
- $xml .= " <line>" . $error->getLine() . "</line>\n";
- $xml .= " <trace>" . $this->createCdataSection($error->getTraceAsString()) . "</trace>\n";
- $xml .= " </error>\n";
- } while ($error = $error->getPrevious());
- }
- $xml .= "</error>";
-
- return $xml;
- }
-
- /**
- * Returns a CDATA section with the given content.
- *
- * @param string $content
- * @return string
- */
- private function createCdataSection($content)
- {
- return sprintf('<![CDATA[%s]]>', str_replace(']]>', ']]]]><![CDATA[>', $content));
- }
-}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Handlers\Strategies;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Slim\Interfaces\RequestHandlerInvocationStrategyInterface;
+
+/**
+ * PSR-15 RequestHandler invocation strategy
+ */
+class RequestHandler implements RequestHandlerInvocationStrategyInterface
+{
+ protected bool $appendRouteArgumentsToRequestAttributes;
+
+ public function __construct(bool $appendRouteArgumentsToRequestAttributes = false)
+ {
+ $this->appendRouteArgumentsToRequestAttributes = $appendRouteArgumentsToRequestAttributes;
+ }
+
+ /**
+ * Invoke a route callable that implements RequestHandlerInterface
+ *
+ * @param array<string, string> $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);
+ }
+}
<?php
+
/**
* Slim Framework (https://slimframework.com)
*
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/
+
+declare(strict_types=1);
+
namespace Slim\Handlers\Strategies;
use Psr\Http\Message\ResponseInterface;
* Invoke a route callable with request, response, and all route parameters
* as an array of arguments.
*
- * @param array|callable $callable
- * @param ServerRequestInterface $request
- * @param ResponseInterface $response
- * @param array $routeArguments
- *
- * @return mixed
+ * @param array<string, string> $routeArguments
*/
public function __invoke(
callable $callable,
ServerRequestInterface $request,
ResponseInterface $response,
array $routeArguments
- ) {
+ ): ResponseInterface {
foreach ($routeArguments as $k => $v) {
$request = $request->withAttribute($k, $v);
}
- return call_user_func($callable, $request, $response, $routeArguments);
+ return $callable($request, $response, $routeArguments);
}
}
<?php
+
/**
* Slim Framework (https://slimframework.com)
*
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/
+
+declare(strict_types=1);
+
namespace Slim\Handlers\Strategies;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Interfaces\InvocationStrategyInterface;
+use function array_values;
+
/**
* Route callback strategy with route parameters as individual arguments.
*/
class RequestResponseArgs implements InvocationStrategyInterface
{
-
/**
* Invoke a route callable with request, response and all route parameters
* as individual arguments.
*
- * @param array|callable $callable
- * @param ServerRequestInterface $request
- * @param ResponseInterface $response
- * @param array $routeArguments
- *
- * @return mixed
+ * @param array<string, string> $routeArguments
*/
public function __invoke(
callable $callable,
ServerRequestInterface $request,
ResponseInterface $response,
array $routeArguments
- ) {
- array_unshift($routeArguments, $request, $response);
-
- return call_user_func_array($callable, $routeArguments);
+ ): ResponseInterface {
+ return $callable($request, $response, ...array_values($routeArguments));
}
}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Handlers\Strategies;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Slim\Interfaces\InvocationStrategyInterface;
+use RuntimeException;
+
+/**
+ * Route callback strategy with route parameters as individual arguments.
+ */
+class RequestResponseNamedArgs implements InvocationStrategyInterface
+{
+ public function __construct()
+ {
+ if (PHP_VERSION_ID < 80000) {
+ throw new RuntimeException('Named arguments are only available for PHP >= 8.0.0');
+ }
+ }
+
+ /**
+ * Invoke a route callable with request, response and all route parameters
+ * as individual arguments.
+ *
+ * @param array<string, string> $routeArguments
+ */
+ public function __invoke(
+ callable $callable,
+ ServerRequestInterface $request,
+ ResponseInterface $response,
+ array $routeArguments
+ ): ResponseInterface {
+ return $callable($request, $response, ...$routeArguments);
+ }
+}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-/**
- * Body
- *
- * This class represents an HTTP message body and encapsulates a
- * streamable resource according to the PSR-7 standard.
- *
- * @link https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php
- */
-class Body extends Stream
-{
-
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-use InvalidArgumentException;
-use Slim\Interfaces\Http\CookiesInterface;
-
-/**
- * Cookie helper
- */
-class Cookies implements CookiesInterface
-{
- /**
- * Cookies from HTTP request
- *
- * @var array
- */
- protected $requestCookies = [];
-
- /**
- * Cookies for HTTP response
- *
- * @var array
- */
- protected $responseCookies = [];
-
- /**
- * Default cookie properties
- *
- * @var array
- */
- protected $defaults = [
- 'value' => '',
- 'domain' => null,
- 'hostonly' => null,
- 'path' => null,
- 'expires' => null,
- 'secure' => false,
- 'httponly' => false
- ];
-
- /**
- * Create new cookies helper
- *
- * @param array $cookies
- */
- public function __construct(array $cookies = [])
- {
- $this->requestCookies = $cookies;
- }
-
- /**
- * Set default cookie properties
- *
- * @param array $settings
- */
- public function setDefaults(array $settings)
- {
- $this->defaults = array_replace($this->defaults, $settings);
- }
-
- /**
- * Get request cookie
- *
- * @param string $name Cookie name
- * @param mixed $default Cookie default value
- *
- * @return mixed Cookie value if present, else default
- */
- public function get($name, $default = null)
- {
- return isset($this->requestCookies[$name]) ? $this->requestCookies[$name] : $default;
- }
-
- /**
- * Set response cookie
- *
- * @param string $name Cookie name
- * @param string|array $value Cookie value, or cookie properties
- */
- public function set($name, $value)
- {
- if (!is_array($value)) {
- $value = ['value' => (string)$value];
- }
- $this->responseCookies[$name] = array_replace($this->defaults, $value);
- }
-
- /**
- * Convert to `Set-Cookie` headers
- *
- * @return string[]
- */
- public function toHeaders()
- {
- $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($name, array $properties)
- {
- $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 !== 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';
- }
-
- return $result;
- }
-
- /**
- * Parse HTTP request `Cookie:` header and extract
- * into a PHP associative array.
- *
- * @param string $header The raw HTTP request `Cookie:` header
- *
- * @return array Associative array of cookie names and values
- *
- * @throws InvalidArgumentException if the cookie data cannot be parsed
- */
- public static function parseHeader($header)
- {
- if (is_array($header) === true) {
- $header = isset($header[0]) ? $header[0] : '';
- }
-
- if (is_string($header) === false) {
- throw new InvalidArgumentException('Cannot parse Cookie data. Header value must be a string.');
- }
-
- $header = rtrim($header, "\r\n");
- $pieces = preg_split('@[;]\s*@', $header);
- $cookies = [];
-
- 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;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-use Slim\Collection;
-use Slim\Interfaces\Http\EnvironmentInterface;
-
-/**
- * Environment
- *
- * This class decouples the Slim application from the global PHP environment.
- * This is particularly useful for unit testing, but it also lets us create
- * custom sub-requests.
- */
-class Environment extends Collection implements EnvironmentInterface
-{
- /**
- * Create mock environment
- *
- * @param array $userData Array of custom environment keys and values
- *
- * @return self
- */
- public static function mock(array $userData = [])
- {
- //Validates if default protocol is HTTPS to set default port 443
- if ((isset($userData['HTTPS']) && $userData['HTTPS'] !== 'off') ||
- ((isset($userData['REQUEST_SCHEME']) && $userData['REQUEST_SCHEME'] === 'https'))) {
- $defscheme = 'https';
- $defport = 443;
- } else {
- $defscheme = 'http';
- $defport = 80;
- }
-
- $data = array_merge([
- 'SERVER_PROTOCOL' => 'HTTP/1.1',
- 'REQUEST_METHOD' => 'GET',
- 'REQUEST_SCHEME' => $defscheme,
- 'SCRIPT_NAME' => '',
- 'REQUEST_URI' => '',
- 'QUERY_STRING' => '',
- 'SERVER_NAME' => 'localhost',
- 'SERVER_PORT' => $defport,
- 'HTTP_HOST' => 'localhost',
- 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
- 'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8',
- 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
- 'HTTP_USER_AGENT' => 'Slim Framework',
- 'REMOTE_ADDR' => '127.0.0.1',
- 'REQUEST_TIME' => time(),
- 'REQUEST_TIME_FLOAT' => microtime(true),
- ], $userData);
-
- return new static($data);
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-use Slim\Collection;
-use Slim\Interfaces\Http\HeadersInterface;
-
-/**
- * Headers
- *
- * This class represents a collection of HTTP headers
- * that is used in both the HTTP request and response objects.
- * It also enables header name case-insensitivity when
- * getting or setting a header value.
- *
- * Each HTTP header can have multiple values. This class
- * stores values into an array for each header name. When
- * you request a header value, you receive an array of values
- * for that header.
- */
-class Headers extends Collection implements HeadersInterface
-{
- /**
- * Special HTTP headers that do not have the "HTTP_" prefix
- *
- * @var array
- */
- protected static $special = [
- 'CONTENT_TYPE' => 1,
- 'CONTENT_LENGTH' => 1,
- 'PHP_AUTH_USER' => 1,
- 'PHP_AUTH_PW' => 1,
- 'PHP_AUTH_DIGEST' => 1,
- 'AUTH_TYPE' => 1,
- ];
-
- /**
- * Create new headers collection with data extracted from
- * the application Environment object
- *
- * @param Environment $environment The Slim application Environment
- *
- * @return self
- */
- public static function createFromEnvironment(Environment $environment)
- {
- $data = [];
- $environment = self::determineAuthorization($environment);
- foreach ($environment as $key => $value) {
- $key = strtoupper($key);
- if (isset(static::$special[$key]) || strpos($key, 'HTTP_') === 0) {
- if ($key !== 'HTTP_CONTENT_LENGTH') {
- $data[$key] = $value;
- }
- }
- }
-
- return new static($data);
- }
-
- /**
- * If HTTP_AUTHORIZATION does not exist tries to get it from
- * getallheaders() when available.
- *
- * @param Environment $environment The Slim application Environment
- *
- * @return Environment
- */
-
- public static function determineAuthorization(Environment $environment)
- {
- $authorization = $environment->get('HTTP_AUTHORIZATION');
-
- if (empty($authorization) && is_callable('getallheaders')) {
- $headers = getallheaders();
- $headers = array_change_key_case($headers, CASE_LOWER);
- if (isset($headers['authorization'])) {
- $environment->set('HTTP_AUTHORIZATION', $headers['authorization']);
- }
- }
-
- return $environment;
- }
-
- /**
- * Return array of HTTP header names and values.
- * This method returns the _original_ header name
- * as specified by the end user.
- *
- * @return array
- */
- public function all()
- {
- $all = parent::all();
- $out = [];
- foreach ($all as $key => $props) {
- $out[$props['originalKey']] = $props['value'];
- }
-
- return $out;
- }
-
- /**
- * Set HTTP header value
- *
- * This method sets a header value. It replaces
- * any values that may already exist for the header name.
- *
- * @param string $key The case-insensitive header name
- * @param string $value The header value
- */
- public function set($key, $value)
- {
- if (!is_array($value)) {
- $value = [$value];
- }
- parent::set($this->normalizeKey($key), [
- 'value' => $value,
- 'originalKey' => $key
- ]);
- }
-
- /**
- * Get HTTP header value
- *
- * @param string $key The case-insensitive header name
- * @param mixed $default The default value if key does not exist
- *
- * @return string[]
- */
- public function get($key, $default = null)
- {
- if ($this->has($key)) {
- return parent::get($this->normalizeKey($key))['value'];
- }
-
- return $default;
- }
-
- /**
- * Get HTTP header key as originally specified
- *
- * @param string $key The case-insensitive header name
- * @param mixed $default The default value if key does not exist
- *
- * @return string
- */
- public function getOriginalKey($key, $default = null)
- {
- if ($this->has($key)) {
- return parent::get($this->normalizeKey($key))['originalKey'];
- }
-
- return $default;
- }
-
- /**
- * Add HTTP header value
- *
- * This method appends a header value. Unlike the set() method,
- * this method _appends_ this new value to any values
- * that already exist for this header name.
- *
- * @param string $key The case-insensitive header name
- * @param array|string $value The new header value(s)
- */
- public function add($key, $value)
- {
- $oldValues = $this->get($key, []);
- $newValues = is_array($value) ? $value : [$value];
- $this->set($key, array_merge($oldValues, array_values($newValues)));
- }
-
- /**
- * Does this collection have a given header?
- *
- * @param string $key The case-insensitive header name
- *
- * @return bool
- */
- public function has($key)
- {
- return parent::has($this->normalizeKey($key));
- }
-
- /**
- * Remove header from collection
- *
- * @param string $key The case-insensitive header name
- */
- public function remove($key)
- {
- parent::remove($this->normalizeKey($key));
- }
-
- /**
- * Normalize header name
- *
- * This method transforms header names into a
- * normalized form. This is how we enable case-insensitive
- * header names in the other methods in this class.
- *
- * @param string $key The case-insensitive header name
- *
- * @return string Normalized header name
- */
- public function normalizeKey($key)
- {
- $key = strtr(strtolower($key), '_', '-');
- if (strpos($key, 'http-') === 0) {
- $key = substr($key, 5);
- }
-
- return $key;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-use InvalidArgumentException;
-use Psr\Http\Message\MessageInterface;
-use Psr\Http\Message\StreamInterface;
-
-/**
- * Abstract message (base class for Request and Response)
- *
- * This class represents a general HTTP message. It provides common properties and methods for
- * the HTTP request and response, as defined in the PSR-7 MessageInterface.
- *
- * @link https://github.com/php-fig/http-message/blob/master/src/MessageInterface.php
- * @see Slim\Http\Request
- * @see Slim\Http\Response
- */
-abstract class Message implements MessageInterface
-{
- /**
- * Protocol version
- *
- * @var string
- */
- protected $protocolVersion = '1.1';
-
- /**
- * A map of valid protocol versions
- *
- * @var array
- */
- protected static $validProtocolVersions = [
- '1.0' => true,
- '1.1' => true,
- '2.0' => true,
- '2' => true,
- ];
-
- /**
- * Headers
- *
- * @var \Slim\Interfaces\Http\HeadersInterface
- */
- protected $headers;
-
- /**
- * Body object
- *
- * @var \Psr\Http\Message\StreamInterface
- */
- protected $body;
-
-
- /**
- * Disable magic setter to ensure immutability
- */
- public function __set($name, $value)
- {
- // Do nothing
- }
-
- /*******************************************************************************
- * Protocol
- ******************************************************************************/
-
- /**
- * Retrieves the HTTP protocol version as a string.
- *
- * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
- *
- * @return string HTTP protocol version.
- */
- public function getProtocolVersion()
- {
- return $this->protocolVersion;
- }
-
- /**
- * Return an instance with the specified HTTP protocol version.
- *
- * The version string MUST contain only the HTTP version number (e.g.,
- * "1.1", "1.0").
- *
- * 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 protocol version.
- *
- * @param string $version HTTP protocol version
- * @return static
- * @throws InvalidArgumentException if the http version is an invalid number
- */
- public function withProtocolVersion($version)
- {
- 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;
- }
-
- /*******************************************************************************
- * Headers
- ******************************************************************************/
-
- /**
- * Retrieves all message header values.
- *
- * The keys represent the header name as it will be sent over the wire, and
- * each value is an array of strings associated with the header.
- *
- * // Represent the headers as a string
- * foreach ($message->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 array 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()
- {
- return $this->headers->all();
- }
-
- /**
- * 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($name)
- {
- return $this->headers->has($name);
- }
-
- /**
- * 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($name)
- {
- return $this->headers->get($name, []);
- }
-
- /**
- * 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($name)
- {
- return implode(',', $this->headers->get($name, []));
- }
-
- /**
- * 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($name, $value)
- {
- $clone = clone $this;
- $clone->headers->set($name, $value);
-
- return $clone;
- }
-
- /**
- * 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($name, $value)
- {
- $clone = clone $this;
- $clone->headers->add($name, $value);
-
- return $clone;
- }
-
- /**
- * 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($name)
- {
- $clone = clone $this;
- $clone->headers->remove($name);
-
- return $clone;
- }
-
- /*******************************************************************************
- * Body
- ******************************************************************************/
-
- /**
- * Gets the body of the message.
- *
- * @return StreamInterface Returns the body as a stream.
- */
- public function getBody()
- {
- return $this->body;
- }
-
- /**
- * 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)
- {
- // TODO: Test for invalid body?
- $clone = clone $this;
- $clone->body = $body;
-
- return $clone;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-use Closure;
-use InvalidArgumentException;
-use Psr\Http\Message\UploadedFileInterface;
-use RuntimeException;
-use Psr\Http\Message\ServerRequestInterface;
-use Psr\Http\Message\UriInterface;
-use Psr\Http\Message\StreamInterface;
-use Slim\Collection;
-use Slim\Exception\InvalidMethodException;
-use Slim\Interfaces\Http\HeadersInterface;
-
-/**
- * Request
- *
- * This class represents an HTTP request. It manages
- * the request method, URI, headers, cookies, and body
- * according to the PSR-7 standard.
- *
- * @link https://github.com/php-fig/http-message/blob/master/src/MessageInterface.php
- * @link https://github.com/php-fig/http-message/blob/master/src/RequestInterface.php
- * @link https://github.com/php-fig/http-message/blob/master/src/ServerRequestInterface.php
- */
-class Request extends Message implements ServerRequestInterface
-{
- /**
- * The request method
- *
- * @var string
- */
- protected $method;
-
- /**
- * The original request method (ignoring override)
- *
- * @var string
- */
- protected $originalMethod;
-
- /**
- * The request URI object
- *
- * @var \Psr\Http\Message\UriInterface
- */
- protected $uri;
-
- /**
- * The request URI target (path + query string)
- *
- * @var string
- */
- protected $requestTarget;
-
- /**
- * The request query string params
- *
- * @var array
- */
- protected $queryParams;
-
- /**
- * The request cookies
- *
- * @var array
- */
- protected $cookies;
-
- /**
- * The server environment variables at the time the request was created.
- *
- * @var array
- */
- protected $serverParams;
-
- /**
- * The request attributes (route segment names and values)
- *
- * @var \Slim\Collection
- */
- protected $attributes;
-
- /**
- * The request body parsed (if possible) into a PHP array or object
- *
- * @var null|array|object
- */
- protected $bodyParsed = false;
-
- /**
- * List of request body parsers (e.g., url-encoded, JSON, XML, multipart)
- *
- * @var callable[]
- */
- protected $bodyParsers = [];
-
- /**
- * List of uploaded files
- *
- * @var UploadedFileInterface[]
- */
- protected $uploadedFiles;
-
- /**
- * Valid request methods
- *
- * @var string[]
- * @deprecated
- */
- protected $validMethods = [
- 'CONNECT' => 1,
- 'DELETE' => 1,
- 'GET' => 1,
- 'HEAD' => 1,
- 'OPTIONS' => 1,
- 'PATCH' => 1,
- 'POST' => 1,
- 'PUT' => 1,
- 'TRACE' => 1,
- ];
-
- /**
- * Create new HTTP request with data extracted from the application
- * Environment object
- *
- * @param Environment $environment The Slim application Environment
- *
- * @return static
- */
- public static function createFromEnvironment(Environment $environment)
- {
- $method = $environment['REQUEST_METHOD'];
- $uri = Uri::createFromEnvironment($environment);
- $headers = Headers::createFromEnvironment($environment);
- $cookies = Cookies::parseHeader($headers->get('Cookie', []));
- $serverParams = $environment->all();
- $body = new RequestBody();
- $uploadedFiles = UploadedFile::createFromEnvironment($environment);
-
- $request = new static($method, $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles);
-
- if ($method === 'POST' &&
- in_array($request->getMediaType(), ['application/x-www-form-urlencoded', 'multipart/form-data'])
- ) {
- // parsed body must be $_POST
- $request = $request->withParsedBody($_POST);
- }
- return $request;
- }
-
- /**
- * Create new HTTP request.
- *
- * Adds a host header when none was provided and a host is defined in uri.
- *
- * @param string $method The request method
- * @param UriInterface $uri The request URI object
- * @param HeadersInterface $headers The request headers collection
- * @param array $cookies The request cookies collection
- * @param array $serverParams The server environment variables
- * @param StreamInterface $body The request body object
- * @param array $uploadedFiles The request uploadedFiles collection
- * @throws InvalidMethodException on invalid HTTP method
- */
- public function __construct(
- $method,
- UriInterface $uri,
- HeadersInterface $headers,
- array $cookies,
- array $serverParams,
- StreamInterface $body,
- array $uploadedFiles = []
- ) {
- try {
- $this->originalMethod = $this->filterMethod($method);
- } catch (InvalidMethodException $e) {
- $this->originalMethod = $method;
- }
-
- $this->uri = $uri;
- $this->headers = $headers;
- $this->cookies = $cookies;
- $this->serverParams = $serverParams;
- $this->attributes = new Collection();
- $this->body = $body;
- $this->uploadedFiles = $uploadedFiles;
-
- if (isset($serverParams['SERVER_PROTOCOL'])) {
- $this->protocolVersion = str_replace('HTTP/', '', $serverParams['SERVER_PROTOCOL']);
- }
-
- if (!$this->headers->has('Host') || $this->uri->getHost() !== '') {
- $this->headers->set('Host', $this->uri->getHost());
- }
-
- $this->registerMediaTypeParser('application/json', function ($input) {
- $result = json_decode($input, true);
- if (!is_array($result)) {
- return null;
- }
- return $result;
- });
-
- $this->registerMediaTypeParser('application/xml', function ($input) {
- $backup = libxml_disable_entity_loader(true);
- $backup_errors = libxml_use_internal_errors(true);
- $result = simplexml_load_string($input);
- libxml_disable_entity_loader($backup);
- libxml_clear_errors();
- libxml_use_internal_errors($backup_errors);
- if ($result === false) {
- return null;
- }
- return $result;
- });
-
- $this->registerMediaTypeParser('text/xml', function ($input) {
- $backup = libxml_disable_entity_loader(true);
- $backup_errors = libxml_use_internal_errors(true);
- $result = simplexml_load_string($input);
- libxml_disable_entity_loader($backup);
- libxml_clear_errors();
- libxml_use_internal_errors($backup_errors);
- if ($result === false) {
- return null;
- }
- return $result;
- });
-
- $this->registerMediaTypeParser('application/x-www-form-urlencoded', function ($input) {
- parse_str($input, $data);
- return $data;
- });
-
- // if the request had an invalid method, we can throw it now
- if (isset($e) && $e instanceof InvalidMethodException) {
- throw $e;
- }
- }
-
- /**
- * 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->attributes = clone $this->attributes;
- $this->body = clone $this->body;
- }
-
- /*******************************************************************************
- * Method
- ******************************************************************************/
-
- /**
- * Retrieves the HTTP method of the request.
- *
- * @return string Returns the request method.
- */
- public function getMethod()
- {
- if ($this->method === null) {
- $this->method = $this->originalMethod;
- $customMethod = $this->getHeaderLine('X-Http-Method-Override');
-
- if ($customMethod) {
- $this->method = $this->filterMethod($customMethod);
- } elseif ($this->originalMethod === 'POST') {
- $overrideMethod = $this->filterMethod($this->getParsedBodyParam('_METHOD'));
- if ($overrideMethod !== null) {
- $this->method = $overrideMethod;
- }
-
- if ($this->getBody()->eof()) {
- $this->getBody()->rewind();
- }
- }
- }
-
- return $this->method;
- }
-
- /**
- * Get the original HTTP method (ignore override).
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return string
- */
- public function getOriginalMethod()
- {
- return $this->originalMethod;
- }
-
- /**
- * Return an instance with the provided HTTP method.
- *
- * While HTTP method names are typically all uppercase characters, HTTP
- * method names are case-sensitive and thus implementations SHOULD NOT
- * modify the given string.
- *
- * 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
- * changed request method.
- *
- * @param string $method Case-sensitive method.
- * @return static
- * @throws \InvalidArgumentException for invalid HTTP methods.
- */
- public function withMethod($method)
- {
- $method = $this->filterMethod($method);
- $clone = clone $this;
- $clone->originalMethod = $method;
- $clone->method = $method;
-
- return $clone;
- }
-
- /**
- * Validate the HTTP method
- *
- * @param null|string $method
- * @return null|string
- * @throws \InvalidArgumentException on invalid HTTP method.
- */
- protected function filterMethod($method)
- {
- if ($method === null) {
- return $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))
- ));
- }
-
- $method = strtoupper($method);
- if (preg_match("/^[!#$%&'*+.^_`|~0-9a-z-]+$/i", $method) !== 1) {
- throw new InvalidMethodException($this, $method);
- }
-
- return $method;
- }
-
- /**
- * Does this request use a given method?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @param string $method HTTP method
- * @return bool
- */
- public function isMethod($method)
- {
- return $this->getMethod() === $method;
- }
-
- /**
- * Is this a GET request?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isGet()
- {
- return $this->isMethod('GET');
- }
-
- /**
- * Is this a POST request?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isPost()
- {
- return $this->isMethod('POST');
- }
-
- /**
- * Is this a PUT request?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isPut()
- {
- return $this->isMethod('PUT');
- }
-
- /**
- * Is this a PATCH request?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isPatch()
- {
- return $this->isMethod('PATCH');
- }
-
- /**
- * Is this a DELETE request?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isDelete()
- {
- return $this->isMethod('DELETE');
- }
-
- /**
- * Is this a HEAD request?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isHead()
- {
- return $this->isMethod('HEAD');
- }
-
- /**
- * Is this a OPTIONS request?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isOptions()
- {
- return $this->isMethod('OPTIONS');
- }
-
- /**
- * Is this an XHR request?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isXhr()
- {
- return $this->getHeaderLine('X-Requested-With') === 'XMLHttpRequest';
- }
-
- /*******************************************************************************
- * URI
- ******************************************************************************/
-
- /**
- * Retrieves the message's request target.
- *
- * Retrieves the message's request-target either as it will appear (for
- * clients), as it appeared at request (for servers), or as it was
- * specified for the instance (see withRequestTarget()).
- *
- * In most cases, this will be the origin-form of the composed URI,
- * unless a value was provided to the concrete implementation (see
- * withRequestTarget() below).
- *
- * If no URI is available, and no request-target has been specifically
- * provided, this method MUST return the string "/".
- *
- * @return string
- */
- public function getRequestTarget()
- {
- if ($this->requestTarget) {
- return $this->requestTarget;
- }
-
- if ($this->uri === null) {
- return '/';
- }
-
- $basePath = $this->uri->getBasePath();
- $path = $this->uri->getPath();
- $path = $basePath . '/' . ltrim($path, '/');
-
- $query = $this->uri->getQuery();
- if ($query) {
- $path .= '?' . $query;
- }
- $this->requestTarget = $path;
-
- return $this->requestTarget;
- }
-
- /**
- * Return an instance with the specific request-target.
- *
- * If the request needs a non-origin-form request-target — e.g., for
- * specifying an absolute-form, authority-form, or asterisk-form —
- * this method may be used to create an instance with the specified
- * request-target, verbatim.
- *
- * 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
- * changed request target.
- *
- * @link http://tools.ietf.org/html/rfc7230#section-2.7 (for the various
- * request-target forms allowed in request messages)
- * @param mixed $requestTarget
- * @return static
- * @throws InvalidArgumentException if the request target is invalid
- */
- public function withRequestTarget($requestTarget)
- {
- if (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;
- }
-
- /**
- * Retrieves the URI instance.
- *
- * This method MUST return a UriInterface instance.
- *
- * @link http://tools.ietf.org/html/rfc3986#section-4.3
- * @return UriInterface Returns a UriInterface instance
- * representing the URI of the request.
- */
- public function getUri()
- {
- return $this->uri;
- }
-
- /**
- * Returns an instance with the provided URI.
- *
- * This method MUST update the Host header of the returned request by
- * default if the URI contains a host component. If the URI does not
- * contain a host component, any pre-existing Host header MUST be carried
- * over to the returned request.
- *
- * You can opt-in to preserving the original state of the Host header by
- * setting `$preserveHost` to `true`. When `$preserveHost` is set to
- * `true`, this method interacts with the Host header in the following ways:
- *
- * - If the 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.
- * - 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.
- * - If a Host header is present and non-empty, this method MUST NOT update
- * the Host header in the returned request.
- *
- * 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 UriInterface instance.
- *
- * @link http://tools.ietf.org/html/rfc3986#section-4.3
- * @param UriInterface $uri New request URI to use.
- * @param bool $preserveHost Preserve the original state of the Host header.
- * @return static
- */
- public function withUri(UriInterface $uri, $preserveHost = false)
- {
- $clone = clone $this;
- $clone->uri = $uri;
-
- if (!$preserveHost) {
- if ($uri->getHost() !== '') {
- $clone->headers->set('Host', $uri->getHost());
- }
- } else {
- if ($uri->getHost() !== '' && (!$this->hasHeader('Host') || $this->getHeaderLine('Host') === '')) {
- $clone->headers->set('Host', $uri->getHost());
- }
- }
-
- return $clone;
- }
-
- /**
- * Get request content type.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return string|null The request content type, if known
- */
- public function getContentType()
- {
- $result = $this->getHeader('Content-Type');
-
- return $result ? $result[0] : null;
- }
-
- /**
- * Get request media type, if known.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return string|null The request media type, minus content-type params
- */
- public function getMediaType()
- {
- $contentType = $this->getContentType();
- if ($contentType) {
- $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
-
- return strtolower($contentTypeParts[0]);
- }
-
- return null;
- }
-
- /**
- * Get request media type params, if known.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return array
- */
- public function getMediaTypeParams()
- {
- $contentType = $this->getContentType();
- $contentTypeParams = [];
- if ($contentType) {
- $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
- $contentTypePartsLength = count($contentTypeParts);
- for ($i = 1; $i < $contentTypePartsLength; $i++) {
- $paramParts = explode('=', $contentTypeParts[$i]);
- $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1];
- }
- }
-
- return $contentTypeParams;
- }
-
- /**
- * Get request content character set, if known.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return string|null
- */
- public function getContentCharset()
- {
- $mediaTypeParams = $this->getMediaTypeParams();
- if (isset($mediaTypeParams['charset'])) {
- return $mediaTypeParams['charset'];
- }
-
- return null;
- }
-
- /**
- * Get request content length, if known.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return int|null
- */
- public function getContentLength()
- {
- $result = $this->headers->get('Content-Length');
-
- return $result ? (int)$result[0] : null;
- }
-
- /*******************************************************************************
- * Cookies
- ******************************************************************************/
-
- /**
- * Retrieve cookies.
- *
- * Retrieves cookies sent by the client to the server.
- *
- * The data MUST be compatible with the structure of the $_COOKIE
- * superglobal.
- *
- * @return array
- */
- public function getCookieParams()
- {
- return $this->cookies;
- }
-
- /**
- * Fetch cookie value from cookies sent by the client to the server.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @param string $key The attribute name.
- * @param mixed $default Default value to return if the attribute does not exist.
- *
- * @return mixed
- */
- public function getCookieParam($key, $default = null)
- {
- $cookies = $this->getCookieParams();
- $result = $default;
- if (isset($cookies[$key])) {
- $result = $cookies[$key];
- }
-
- return $result;
- }
-
- /**
- * Return an instance with the specified cookies.
- *
- * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST
- * be compatible with the structure of $_COOKIE. Typically, this data will
- * be injected at instantiation.
- *
- * This method MUST NOT update the related Cookie header of the request
- * instance, nor related 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 cookie values.
- *
- * @param array $cookies Array of key/value pairs representing cookies.
- * @return static
- */
- public function withCookieParams(array $cookies)
- {
- $clone = clone $this;
- $clone->cookies = $cookies;
-
- return $clone;
- }
-
- /*******************************************************************************
- * Query Params
- ******************************************************************************/
-
- /**
- * Retrieve query string arguments.
- *
- * Retrieves the deserialized query string arguments, if any.
- *
- * Note: the query params might not be in sync with the URI or server
- * params. If you need to ensure you are only getting the original
- * values, you may need to parse the query string from `getUri()->getQuery()`
- * or from the `QUERY_STRING` server param.
- *
- * @return array
- */
- public function getQueryParams()
- {
- if (is_array($this->queryParams)) {
- return $this->queryParams;
- }
-
- if ($this->uri === null) {
- return [];
- }
-
- parse_str($this->uri->getQuery(), $this->queryParams); // <-- URL decodes data
-
- return $this->queryParams;
- }
-
- /**
- * 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)
- {
- $clone = clone $this;
- $clone->queryParams = $query;
-
- return $clone;
- }
-
- /*******************************************************************************
- * File Params
- ******************************************************************************/
-
- /**
- * 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()
- {
- return $this->uploadedFiles;
- }
-
- /**
- * 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)
- {
- $clone = clone $this;
- $clone->uploadedFiles = $uploadedFiles;
-
- return $clone;
- }
-
- /*******************************************************************************
- * Server Params
- ******************************************************************************/
-
- /**
- * Retrieve server parameters.
- *
- * Retrieves data related to the incoming request environment,
- * typically derived from PHP's $_SERVER superglobal. The data IS NOT
- * REQUIRED to originate from $_SERVER.
- *
- * @return array
- */
- public function getServerParams()
- {
- return $this->serverParams;
- }
-
- /**
- * Retrieve a server parameter.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @param string $key
- * @param mixed $default
- * @return mixed
- */
- public function getServerParam($key, $default = null)
- {
- $serverParams = $this->getServerParams();
-
- return isset($serverParams[$key]) ? $serverParams[$key] : $default;
- }
-
- /*******************************************************************************
- * Attributes
- ******************************************************************************/
-
- /**
- * 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()
- {
- return $this->attributes->all();
- }
-
- /**
- * 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($name, $default = null)
- {
- return $this->attributes->get($name, $default);
- }
-
- /**
- * 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($name, $value)
- {
- $clone = clone $this;
- $clone->attributes->set($name, $value);
-
- return $clone;
- }
-
- /**
- * Create a new instance with the specified derived request attributes.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * This method allows setting all new derived request attributes as
- * described in getAttributes().
- *
- * 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
- * updated attributes.
- *
- * @param array $attributes New attributes
- * @return static
- */
- public function withAttributes(array $attributes)
- {
- $clone = clone $this;
- $clone->attributes = new Collection($attributes);
-
- return $clone;
- }
-
- /**
- * 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($name)
- {
- $clone = clone $this;
- $clone->attributes->remove($name);
-
- return $clone;
- }
-
- /*******************************************************************************
- * Body
- ******************************************************************************/
-
- /**
- * 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.
- * @throws RuntimeException if the request body media type parser returns an invalid value
- */
- public function getParsedBody()
- {
- if ($this->bodyParsed !== false) {
- return $this->bodyParsed;
- }
-
- if (!$this->body) {
- return null;
- }
-
- $mediaType = $this->getMediaType();
-
- // 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]) === true) {
- $body = (string)$this->getBody();
- $parsed = $this->bodyParsers[$mediaType]($body);
-
- if (!is_null($parsed) && !is_object($parsed) && !is_array($parsed)) {
- throw new RuntimeException(
- 'Request body media type parser return value must be an array, an object, or null'
- );
- }
- $this->bodyParsed = $parsed;
- return $this->bodyParsed;
- }
-
- return null;
- }
-
- /**
- * 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)
- {
- 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->bodyParsed = $data;
-
- return $clone;
- }
-
- /**
- * Force Body to be parsed again.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return $this
- */
- public function reparseBody()
- {
- $this->bodyParsed = false;
-
- return $this;
- }
-
- /**
- * Register media type parser.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @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 registerMediaTypeParser($mediaType, callable $callable)
- {
- if ($callable instanceof Closure) {
- $callable = $callable->bindTo($this);
- }
- $this->bodyParsers[(string)$mediaType] = $callable;
- }
-
- /*******************************************************************************
- * Parameters (e.g., POST and GET data)
- ******************************************************************************/
-
- /**
- * Fetch request parameter value from body or query string (in that order).
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @param string $key The parameter key.
- * @param string $default The default value.
- *
- * @return mixed The parameter value.
- */
- public function getParam($key, $default = null)
- {
- $postParams = $this->getParsedBody();
- $getParams = $this->getQueryParams();
- $result = $default;
- if (is_array($postParams) && isset($postParams[$key])) {
- $result = $postParams[$key];
- } elseif (is_object($postParams) && property_exists($postParams, $key)) {
- $result = $postParams->$key;
- } elseif (isset($getParams[$key])) {
- $result = $getParams[$key];
- }
-
- return $result;
- }
-
- /**
- * Fetch parameter value from request body.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @param string $key
- * @param mixed $default
- *
- * @return mixed
- */
- public function getParsedBodyParam($key, $default = null)
- {
- $postParams = $this->getParsedBody();
- $result = $default;
- if (is_array($postParams) && isset($postParams[$key])) {
- $result = $postParams[$key];
- } elseif (is_object($postParams) && property_exists($postParams, $key)) {
- $result = $postParams->$key;
- }
-
- return $result;
- }
-
- /**
- * Fetch parameter value from query string.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @param string $key
- * @param mixed $default
- *
- * @return mixed
- */
- public function getQueryParam($key, $default = null)
- {
- $getParams = $this->getQueryParams();
- $result = $default;
- if (isset($getParams[$key])) {
- $result = $getParams[$key];
- }
-
- return $result;
- }
-
- /**
- * Fetch associative array of body and query string parameters.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @param array|null $only list the keys to retrieve.
- * @return array|null
- */
- public function getParams(array $only = null)
- {
- $params = $this->getQueryParams();
- $postParams = $this->getParsedBody();
- if ($postParams) {
- $params = array_merge($params, (array)$postParams);
- }
-
- if ($only) {
- $onlyParams = [];
- foreach ($only as $key) {
- if (array_key_exists($key, $params)) {
- $onlyParams[$key] = $params[$key];
- }
- }
- return $onlyParams;
- }
-
- return $params;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-/**
- * Provides a PSR-7 implementation of a reusable raw request body
- */
-class RequestBody extends Body
-{
- /**
- * Create a new RequestBody.
- */
- public function __construct()
- {
- $stream = fopen('php://temp', 'w+');
- stream_copy_to_stream(fopen('php://input', 'r'), $stream);
- rewind($stream);
-
- parent::__construct($stream);
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-use InvalidArgumentException;
-use Psr\Http\Message\ResponseInterface;
-use Psr\Http\Message\StreamInterface;
-use Psr\Http\Message\UriInterface;
-use Slim\Interfaces\Http\HeadersInterface;
-
-/**
- * Response
- *
- * This class represents an HTTP response. It manages
- * the response status, headers, and body
- * according to the PSR-7 standard.
- *
- * @link https://github.com/php-fig/http-message/blob/master/src/MessageInterface.php
- * @link https://github.com/php-fig/http-message/blob/master/src/ResponseInterface.php
- */
-class Response extends Message implements ResponseInterface
-{
- /**
- * Status code
- *
- * @var int
- */
- protected $status = 200;
-
- /**
- * Reason phrase
- *
- * @var string
- */
- protected $reasonPhrase = '';
-
- /**
- * Status codes and reason phrases
- *
- * @var array
- */
- protected static $messages = [
- //Informational 1xx
- 100 => 'Continue',
- 101 => 'Switching Protocols',
- 102 => 'Processing',
- //Successful 2xx
- 200 => 'OK',
- 201 => 'Created',
- 202 => 'Accepted',
- 203 => 'Non-Authoritative Information',
- 204 => 'No Content',
- 205 => 'Reset Content',
- 206 => 'Partial Content',
- 207 => 'Multi-Status',
- 208 => 'Already Reported',
- 226 => 'IM Used',
- //Redirection 3xx
- 300 => 'Multiple Choices',
- 301 => 'Moved Permanently',
- 302 => 'Found',
- 303 => 'See Other',
- 304 => 'Not Modified',
- 305 => 'Use Proxy',
- 306 => '(Unused)',
- 307 => 'Temporary Redirect',
- 308 => 'Permanent Redirect',
- //Client Error 4xx
- 400 => 'Bad Request',
- 401 => 'Unauthorized',
- 402 => 'Payment Required',
- 403 => 'Forbidden',
- 404 => 'Not Found',
- 405 => 'Method Not Allowed',
- 406 => 'Not Acceptable',
- 407 => 'Proxy Authentication Required',
- 408 => 'Request Timeout',
- 409 => 'Conflict',
- 410 => 'Gone',
- 411 => 'Length Required',
- 412 => 'Precondition Failed',
- 413 => 'Request Entity Too Large',
- 414 => 'Request-URI Too Long',
- 415 => 'Unsupported Media Type',
- 416 => 'Requested Range Not Satisfiable',
- 417 => 'Expectation Failed',
- 418 => 'I\'m a teapot',
- 421 => 'Misdirected Request',
- 422 => 'Unprocessable Entity',
- 423 => 'Locked',
- 424 => 'Failed Dependency',
- 426 => 'Upgrade Required',
- 428 => 'Precondition Required',
- 429 => 'Too Many Requests',
- 431 => 'Request Header Fields Too Large',
- 444 => 'Connection Closed Without Response',
- 451 => 'Unavailable For Legal Reasons',
- 499 => 'Client Closed Request',
- //Server Error 5xx
- 500 => 'Internal Server Error',
- 501 => 'Not Implemented',
- 502 => 'Bad Gateway',
- 503 => 'Service Unavailable',
- 504 => 'Gateway Timeout',
- 505 => 'HTTP Version Not Supported',
- 506 => 'Variant Also Negotiates',
- 507 => 'Insufficient Storage',
- 508 => 'Loop Detected',
- 510 => 'Not Extended',
- 511 => 'Network Authentication Required',
- 599 => 'Network Connect Timeout Error',
- ];
-
- /**
- * EOL characters used for HTTP response.
- *
- * @var string
- */
- const EOL = "\r\n";
-
- /**
- * Create new HTTP response.
- *
- * @param int $status The response status code.
- * @param HeadersInterface|null $headers The response headers.
- * @param StreamInterface|null $body The response body.
- */
- public function __construct($status = 200, HeadersInterface $headers = null, StreamInterface $body = null)
- {
- $this->status = $this->filterStatus($status);
- $this->headers = $headers ? $headers : new Headers();
- $this->body = $body ? $body : new Body(fopen('php://temp', 'r+'));
- }
-
- /**
- * 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;
- }
-
- /*******************************************************************************
- * Status
- ******************************************************************************/
-
- /**
- * Gets the response status code.
- *
- * The status code is a 3-digit integer result code of the server's attempt
- * to understand and satisfy the request.
- *
- * @return int Status code.
- */
- public function getStatusCode()
- {
- return $this->status;
- }
-
- /**
- * Return an instance with the specified status code and, optionally, reason phrase.
- *
- * If no reason phrase is specified, implementations MAY choose to default
- * to the RFC 7231 or IANA recommended reason phrase for the response's
- * status code.
- *
- * 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 status and reason phrase.
- *
- * @link http://tools.ietf.org/html/rfc7231#section-6
- * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
- * @param int $code The 3-digit integer result code to set.
- * @param string $reasonPhrase The reason phrase to use with the
- * provided status code; if none is provided, implementations MAY
- * use the defaults as suggested in the HTTP specification.
- * @return static
- * @throws \InvalidArgumentException For invalid status code arguments.
- */
- public function withStatus($code, $reasonPhrase = '')
- {
- $code = $this->filterStatus($code);
-
- if (!is_string($reasonPhrase) && !method_exists($reasonPhrase, '__toString')) {
- throw new InvalidArgumentException('ReasonPhrase must be a string');
- }
-
- $clone = clone $this;
- $clone->status = $code;
- if ($reasonPhrase === '' && isset(static::$messages[$code])) {
- $reasonPhrase = static::$messages[$code];
- }
-
- if ($reasonPhrase === '') {
- throw new InvalidArgumentException('ReasonPhrase must be supplied for this code');
- }
-
- $clone->reasonPhrase = $reasonPhrase;
-
- return $clone;
- }
-
- /**
- * 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)
- {
- if (!is_integer($status) || $status<100 || $status>599) {
- throw new InvalidArgumentException('Invalid HTTP status code');
- }
-
- return $status;
- }
-
- /**
- * Gets the response reason phrase associated with the status code.
- *
- * Because a reason phrase is not a required element in a response
- * status line, the reason phrase value MAY be null. Implementations MAY
- * choose to return the default RFC 7231 recommended reason phrase (or those
- * listed in the IANA HTTP Status Code Registry) for the response's
- * status code.
- *
- * @link http://tools.ietf.org/html/rfc7231#section-6
- * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
- * @return string Reason phrase; must return an empty string if none present.
- */
- public function getReasonPhrase()
- {
- if ($this->reasonPhrase) {
- return $this->reasonPhrase;
- }
- if (isset(static::$messages[$this->status])) {
- return static::$messages[$this->status];
- }
- return '';
- }
-
- /*******************************************************************************
- * Headers
- ******************************************************************************/
-
- /**
- * Return an instance with the provided value replacing the specified header.
- *
- * If a Location header is set and the status code is 200, then set the status
- * code to 302 to mimic what PHP does. See https://github.com/slimphp/Slim/issues/1730
- *
- * @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($name, $value)
- {
- $clone = clone $this;
- $clone->headers->set($name, $value);
-
- if ($clone->getStatusCode() === 200 && strtolower($name) === 'location') {
- $clone = $clone->withStatus(302);
- }
-
- return $clone;
- }
-
-
- /*******************************************************************************
- * Body
- ******************************************************************************/
-
- /**
- * Write data to the response body.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * Proxies to the underlying stream and writes the provided data to it.
- *
- * @param string $data
- * @return $this
- */
- public function write($data)
- {
- $this->getBody()->write($data);
-
- return $this;
- }
-
- /*******************************************************************************
- * Response Helpers
- ******************************************************************************/
-
- /**
- * Redirect.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * This method prepares the response object to return an HTTP Redirect
- * response to the client.
- *
- * @param string|UriInterface $url The redirect destination.
- * @param int|null $status The redirect HTTP status code.
- * @return static
- */
- public function withRedirect($url, $status = null)
- {
- $responseWithRedirect = $this->withHeader('Location', (string)$url);
-
- if (is_null($status) && $this->getStatusCode() === 200) {
- $status = 302;
- }
-
- if (!is_null($status)) {
- return $responseWithRedirect->withStatus($status);
- }
-
- return $responseWithRedirect;
- }
-
- /**
- * Json.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * This method prepares the response object to return an HTTP Json
- * response to the client.
- *
- * @param mixed $data The data
- * @param int $status The HTTP status code.
- * @param int $encodingOptions Json encoding options
- * @throws \RuntimeException
- * @return static
- */
- public function withJson($data, $status = null, $encodingOptions = 0)
- {
- $response = $this->withBody(new Body(fopen('php://temp', 'r+')));
- $response->body->write($json = json_encode($data, $encodingOptions));
-
- // Ensure that the json encoding passed successfully
- if ($json === false) {
- throw new \RuntimeException(json_last_error_msg(), json_last_error());
- }
-
- $responseWithJson = $response->withHeader('Content-Type', 'application/json;charset=utf-8');
- if (isset($status)) {
- return $responseWithJson->withStatus($status);
- }
- return $responseWithJson;
- }
-
- /**
- * Is this response empty?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isEmpty()
- {
- return in_array($this->getStatusCode(), [204, 205, 304]);
- }
-
- /**
- * Is this response informational?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isInformational()
- {
- return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
- }
-
- /**
- * Is this response OK?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isOk()
- {
- return $this->getStatusCode() === 200;
- }
-
- /**
- * Is this response successful?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isSuccessful()
- {
- return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
- }
-
- /**
- * Is this response a redirect?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isRedirect()
- {
- return in_array($this->getStatusCode(), [301, 302, 303, 307]);
- }
-
- /**
- * Is this response a redirection?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isRedirection()
- {
- return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
- }
-
- /**
- * Is this response forbidden?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- * @api
- */
- public function isForbidden()
- {
- return $this->getStatusCode() === 403;
- }
-
- /**
- * Is this response not Found?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isNotFound()
- {
- return $this->getStatusCode() === 404;
- }
-
- /**
- * Is this response a client error?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isClientError()
- {
- return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
- }
-
- /**
- * Is this response a server error?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- public function isServerError()
- {
- return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
- }
-
- /**
- * Convert response to string.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return string
- */
- public function __toString()
- {
- $output = sprintf(
- 'HTTP/%s %s %s',
- $this->getProtocolVersion(),
- $this->getStatusCode(),
- $this->getReasonPhrase()
- );
- $output .= Response::EOL;
- foreach ($this->getHeaders() as $name => $values) {
- $output .= sprintf('%s: %s', $name, $this->getHeaderLine($name)) . Response::EOL;
- }
- $output .= Response::EOL;
- $output .= (string)$this->getBody();
-
- return $output;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-use InvalidArgumentException;
-use Psr\Http\Message\StreamInterface;
-use RuntimeException;
-
-/**
- * Represents a data stream as defined in PSR-7.
- *
- * @link https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php
- */
-class Stream implements StreamInterface
-{
- /**
- * Bit mask to determine if the stream is a pipe
- *
- * This is octal as per header stat.h
- */
- const FSTAT_MODE_S_IFIFO = 0010000;
-
- /**
- * Resource modes
- *
- * @var array
- * @link http://php.net/manual/function.fopen.php
- */
- protected static $modes = [
- 'readable' => ['r', 'r+', 'w+', 'a+', 'x+', 'c+'],
- 'writable' => ['r+', 'w', 'w+', 'a', 'a+', 'x', 'x+', 'c', 'c+'],
- ];
-
- /**
- * The underlying stream resource
- *
- * @var resource
- */
- protected $stream;
-
- /**
- * Stream metadata
- *
- * @var array
- */
- protected $meta;
-
- /**
- * Is this stream readable?
- *
- * @var bool
- */
- protected $readable;
-
- /**
- * Is this stream writable?
- *
- * @var bool
- */
- protected $writable;
-
- /**
- * Is this stream seekable?
- *
- * @var bool
- */
- protected $seekable;
-
- /**
- * The size of the stream if known
- *
- * @var null|int
- */
- protected $size;
-
- /**
- * Is this stream a pipe?
- *
- * @var bool
- */
- protected $isPipe;
-
- /**
- * Create a new Stream.
- *
- * @param resource $stream A PHP resource handle.
- *
- * @throws InvalidArgumentException If argument is not a resource.
- */
- public function __construct($stream)
- {
- $this->attach($stream);
- }
-
- /**
- * Get stream metadata as an associative array or retrieve a specific key.
- *
- * The keys returned are identical to the keys returned from PHP's
- * stream_get_meta_data() function.
- *
- * @link http://php.net/manual/en/function.stream-get-meta-data.php
- *
- * @param string $key Specific metadata to retrieve.
- *
- * @return array|mixed|null Returns an associative array if no key is
- * provided. Returns a specific key value if a key is provided and the
- * value is found, or null if the key is not found.
- */
- public function getMetadata($key = null)
- {
- $this->meta = stream_get_meta_data($this->stream);
- if (is_null($key) === true) {
- return $this->meta;
- }
-
- return isset($this->meta[$key]) ? $this->meta[$key] : null;
- }
-
- /**
- * Is a resource attached to this stream?
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @return bool
- */
- protected function isAttached()
- {
- return is_resource($this->stream);
- }
-
- /**
- * Attach new resource to this object.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @param resource $newStream A PHP resource handle.
- *
- * @throws InvalidArgumentException If argument is not a valid PHP resource.
- */
- protected function attach($newStream)
- {
- if (is_resource($newStream) === false) {
- throw new InvalidArgumentException(__METHOD__ . ' argument must be a valid PHP resource');
- }
-
- if ($this->isAttached() === true) {
- $this->detach();
- }
-
- $this->stream = $newStream;
- }
-
- /**
- * Separates any underlying resources from the stream.
- *
- * After the stream has been detached, the stream is in an unusable state.
- *
- * @return resource|null Underlying PHP stream, if any
- */
- 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;
-
- return $oldResource;
- }
-
- /**
- * Reads all data from the stream into a string, from the beginning to end.
- *
- * This method MUST attempt to seek to the beginning of the stream before
- * reading data and read the stream until the end is reached.
- *
- * Warning: This could attempt to load a large amount of data into memory.
- *
- * This method MUST NOT raise an exception in order to conform with PHP's
- * string casting operations.
- *
- * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
- * @return string
- */
- public function __toString()
- {
- if (!$this->isAttached()) {
- return '';
- }
-
- try {
- $this->rewind();
- return $this->getContents();
- } catch (RuntimeException $e) {
- return '';
- }
- }
-
- /**
- * Closes the stream and any underlying resources.
- */
- public function close()
- {
- if ($this->isAttached() === true) {
- if ($this->isPipe()) {
- pclose($this->stream);
- } else {
- fclose($this->stream);
- }
- }
-
- $this->detach();
- }
-
- /**
- * Get the size of the stream if known.
- *
- * @return int|null Returns the size in bytes if known, or null if unknown.
- */
- public function getSize()
- {
- if (!$this->size && $this->isAttached() === true) {
- $stats = fstat($this->stream);
- $this->size = isset($stats['size']) && !$this->isPipe() ? $stats['size'] : null;
- }
-
- return $this->size;
- }
-
- /**
- * Returns the current position of the file read/write pointer
- *
- * @return int Position of the file pointer
- *
- * @throws RuntimeException on error.
- */
- public function tell()
- {
- if (!$this->isAttached() || ($position = ftell($this->stream)) === false || $this->isPipe()) {
- throw new RuntimeException('Could not get the position of the pointer in stream');
- }
-
- return $position;
- }
-
- /**
- * Returns true if the stream is at the end of the stream.
- *
- * @return bool
- */
- public function eof()
- {
- return $this->isAttached() ? feof($this->stream) : true;
- }
-
- /**
- * Returns whether or not the stream is readable.
- *
- * @return bool
- */
- public function isReadable()
- {
- if ($this->readable === null) {
- if ($this->isPipe()) {
- $this->readable = true;
- } else {
- $this->readable = false;
- if ($this->isAttached()) {
- $meta = $this->getMetadata();
- foreach (self::$modes['readable'] as $mode) {
- if (strpos($meta['mode'], $mode) === 0) {
- $this->readable = true;
- break;
- }
- }
- }
- }
- }
-
- return $this->readable;
- }
-
- /**
- * Returns whether or not the stream is writable.
- *
- * @return bool
- */
- public function isWritable()
- {
- if ($this->writable === null) {
- $this->writable = false;
- if ($this->isAttached()) {
- $meta = $this->getMetadata();
- foreach (self::$modes['writable'] as $mode) {
- if (strpos($meta['mode'], $mode) === 0) {
- $this->writable = true;
- break;
- }
- }
- }
- }
-
- return $this->writable;
- }
-
- /**
- * Returns whether or not the stream is seekable.
- *
- * @return bool
- */
- public function isSeekable()
- {
- if ($this->seekable === null) {
- $this->seekable = false;
- if ($this->isAttached()) {
- $meta = $this->getMetadata();
- $this->seekable = !$this->isPipe() && $meta['seekable'];
- }
- }
-
- return $this->seekable;
- }
-
- /**
- * Seek to a position in the stream.
- *
- * @link http://www.php.net/manual/en/function.fseek.php
- *
- * @param int $offset Stream offset
- * @param int $whence Specifies how the cursor position will be calculated
- * based on the seek offset. Valid values are identical to the built-in
- * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
- * offset bytes SEEK_CUR: Set position to current location plus offset
- * SEEK_END: Set position to end-of-stream plus offset.
- *
- * @throws RuntimeException on failure.
- */
- public function seek($offset, $whence = SEEK_SET)
- {
- // Note that fseek returns 0 on success!
- if (!$this->isSeekable() || fseek($this->stream, $offset, $whence) === -1) {
- throw new RuntimeException('Could not seek in stream');
- }
- }
-
- /**
- * Seek to the beginning of the stream.
- *
- * If the stream is not seekable, this method will raise an exception;
- * otherwise, it will perform a seek(0).
- *
- * @see seek()
- *
- * @link http://www.php.net/manual/en/function.fseek.php
- *
- * @throws RuntimeException on failure.
- */
- public function rewind()
- {
- if (!$this->isSeekable() || rewind($this->stream) === false) {
- throw new RuntimeException('Could not rewind stream');
- }
- }
-
- /**
- * Read data from the stream.
- *
- * @param int $length Read up to $length bytes from the object and return
- * them. Fewer than $length bytes may be returned if underlying stream
- * call returns fewer bytes.
- *
- * @return string Returns the data read from the stream, or an empty string
- * if no bytes are available.
- *
- * @throws RuntimeException if an error occurs.
- */
- public function read($length)
- {
- if (!$this->isReadable() || ($data = fread($this->stream, $length)) === false) {
- throw new RuntimeException('Could not read from stream');
- }
-
- return $data;
- }
-
- /**
- * Write data to the stream.
- *
- * @param string $string The string that is to be written.
- *
- * @return int Returns the number of bytes written to the stream.
- *
- * @throws RuntimeException on failure.
- */
- public function write($string)
- {
- if (!$this->isWritable() || ($written = fwrite($this->stream, $string)) === false) {
- throw new RuntimeException('Could not write to stream');
- }
-
- // reset size so that it will be recalculated on next call to getSize()
- $this->size = null;
-
- return $written;
- }
-
- /**
- * Returns the remaining contents in a string
- *
- * @return string
- *
- * @throws RuntimeException if unable to read or an error occurs while
- * reading.
- */
- public function getContents()
- {
- if (!$this->isReadable() || ($contents = stream_get_contents($this->stream)) === false) {
- throw new RuntimeException('Could not get contents of stream');
- }
-
- return $contents;
- }
-
- /**
- * Returns whether or not the stream is a pipe.
- *
- * @return bool
- */
- public function isPipe()
- {
- if ($this->isPipe === null) {
- $this->isPipe = false;
- if ($this->isAttached()) {
- $mode = fstat($this->stream)['mode'];
- $this->isPipe = ($mode & self::FSTAT_MODE_S_IFIFO) !== 0;
- }
- }
-
- return $this->isPipe;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-use RuntimeException;
-use InvalidArgumentException;
-use Psr\Http\Message\StreamInterface;
-use Psr\Http\Message\UploadedFileInterface;
-
-/**
- * Represents Uploaded Files.
- *
- * It manages and normalizes uploaded files according to the PSR-7 standard.
- *
- * @link https://github.com/php-fig/http-message/blob/master/src/UploadedFileInterface.php
- * @link https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php
- */
-class UploadedFile implements UploadedFileInterface
-{
- /**
- * The client-provided full path to the file
- *
- * @note this is public to maintain BC with 3.1.0 and earlier.
- *
- * @var string
- */
- public $file;
- /**
- * The client-provided file name.
- *
- * @var string
- */
- protected $name;
- /**
- * The client-provided media type of the file.
- *
- * @var string
- */
- protected $type;
- /**
- * The size of the file in bytes.
- *
- * @var int
- */
- protected $size;
- /**
- * A valid PHP UPLOAD_ERR_xxx code for the file upload.
- *
- * @var int
- */
- protected $error = UPLOAD_ERR_OK;
- /**
- * Indicates if the upload is from a SAPI environment.
- *
- * @var bool
- */
- protected $sapi = false;
- /**
- * An optional StreamInterface wrapping the file resource.
- *
- * @var StreamInterface
- */
- protected $stream;
- /**
- * Indicates if the uploaded file has already been moved.
- *
- * @var bool
- */
- protected $moved = false;
-
- /**
- * Create a normalized tree of UploadedFile instances from the Environment.
- *
- * @param Environment $env The environment
- *
- * @return array|null A normalized tree of UploadedFile instances or null if none are provided.
- */
- public static function createFromEnvironment(Environment $env)
- {
- if (is_array($env['slim.files']) && $env->has('slim.files')) {
- return $env['slim.files'];
- } elseif (isset($_FILES)) {
- return static::parseUploadedFiles($_FILES);
- }
-
- return [];
- }
-
- /**
- * Parse a non-normalized, i.e. $_FILES superglobal, tree of uploaded file data.
- *
- * @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)
- {
- $parsed = [];
- foreach ($uploadedFiles as $field => $uploadedFile) {
- if (!isset($uploadedFile['error'])) {
- if (is_array($uploadedFile)) {
- $parsed[$field] = static::parseUploadedFiles($uploadedFile);
- }
- continue;
- }
-
- $parsed[$field] = [];
- if (!is_array($uploadedFile['error'])) {
- $parsed[$field] = new static(
- $uploadedFile['tmp_name'],
- isset($uploadedFile['name']) ? $uploadedFile['name'] : null,
- isset($uploadedFile['type']) ? $uploadedFile['type'] : null,
- isset($uploadedFile['size']) ? $uploadedFile['size'] : null,
- $uploadedFile['error'],
- true
- );
- } else {
- $subArray = [];
- foreach ($uploadedFile['error'] as $fileIdx => $error) {
- // normalise subarray and re-parse to move the input's keyname 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] = static::parseUploadedFiles($subArray);
- }
- }
- }
-
- return $parsed;
- }
-
- /**
- * Construct a new UploadedFile instance.
- *
- * @param string $file The full path to the uploaded file provided by the client.
- * @param string|null $name The file name.
- * @param string|null $type The file media type.
- * @param int|null $size The file size in bytes.
- * @param int $error The UPLOAD_ERR_XXX code representing the status of the upload.
- * @param bool $sapi Indicates if the upload is in a SAPI environment.
- */
- public function __construct($file, $name = null, $type = null, $size = null, $error = UPLOAD_ERR_OK, $sapi = false)
- {
- $this->file = $file;
- $this->name = $name;
- $this->type = $type;
- $this->size = $size;
- $this->error = $error;
- $this->sapi = $sapi;
- }
-
- /**
- * Retrieve a stream representing the uploaded file.
- *
- * This method MUST return a StreamInterface instance, representing the
- * uploaded file. The purpose of this method is to allow utilizing native PHP
- * stream functionality to manipulate the file upload, such as
- * stream_copy_to_stream() (though the result will need to be decorated in a
- * native PHP stream wrapper to work with such functions).
- *
- * If the moveTo() method has been called previously, this method MUST raise
- * an exception.
- *
- * @return StreamInterface Stream representation of the uploaded file.
- * @throws \RuntimeException in cases when no stream is available or can be
- * created.
- */
- public function getStream()
- {
- if ($this->moved) {
- throw new \RuntimeException(sprintf('Uploaded file %1s has already been moved', $this->name));
- }
- if ($this->stream === null) {
- $this->stream = new Stream(fopen($this->file, 'r'));
- }
-
- return $this->stream;
- }
-
- /**
- * Move the uploaded file to a new location.
- *
- * Use this method as an alternative to move_uploaded_file(). This method is
- * guaranteed to work in both SAPI and non-SAPI environments.
- * Implementations must determine which environment they are in, and use the
- * appropriate method (move_uploaded_file(), rename(), or a stream
- * operation) to perform the operation.
- *
- * $targetPath may be an absolute path, or a relative path. If it is a
- * relative path, resolution should be the same as used by PHP's rename()
- * function.
- *
- * The original file or stream MUST be removed on completion.
- *
- * If this method is called more than once, any subsequent calls MUST raise
- * an exception.
- *
- * When used in an SAPI environment where $_FILES is populated, when writing
- * files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be
- * used to ensure permissions and upload status are verified correctly.
- *
- * If you wish to move to a stream, use getStream(), as SAPI operations
- * cannot guarantee writing to stream destinations.
- *
- * @see http://php.net/is_uploaded_file
- * @see http://php.net/move_uploaded_file
- *
- * @param string $targetPath Path to which to move the uploaded file.
- *
- * @throws InvalidArgumentException if the $path specified is invalid.
- * @throws RuntimeException on any error during the move operation, or on
- * the second or subsequent call to the method.
- */
- public function moveTo($targetPath)
- {
- 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 %1s to %2s', $this->name, $targetPath));
- }
- if (!unlink($this->file)) {
- throw new RuntimeException(sprintf('Error removing uploaded file %1s', $this->name));
- }
- } elseif ($this->sapi) {
- if (!is_uploaded_file($this->file)) {
- throw new RuntimeException(sprintf('%1s is not a valid uploaded file', $this->file));
- }
-
- if (!move_uploaded_file($this->file, $targetPath)) {
- throw new RuntimeException(sprintf('Error moving uploaded file %1s to %2s', $this->name, $targetPath));
- }
- } else {
- if (!rename($this->file, $targetPath)) {
- throw new RuntimeException(sprintf('Error moving uploaded file %1s to %2s', $this->name, $targetPath));
- }
- }
-
- $this->moved = true;
- }
-
- /**
- * Retrieve the error associated with the uploaded file.
- *
- * The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.
- *
- * If the file was uploaded successfully, this method MUST return
- * UPLOAD_ERR_OK.
- *
- * Implementations SHOULD return the value stored in the "error" key of
- * the file in the $_FILES array.
- *
- * @see http://php.net/manual/en/features.file-upload.errors.php
- *
- * @return int One of PHP's UPLOAD_ERR_XXX constants.
- */
- public function getError()
- {
- return $this->error;
- }
-
- /**
- * Retrieve the filename sent by the client.
- *
- * Do not trust the value returned by this method. A client could send
- * a malicious filename with the intention to corrupt or hack your
- * application.
- *
- * Implementations SHOULD return the value stored in the "name" key of
- * the file in the $_FILES array.
- *
- * @return string|null The filename sent by the client or null if none
- * was provided.
- */
- public function getClientFilename()
- {
- return $this->name;
- }
-
- /**
- * Retrieve the media type sent by the client.
- *
- * Do not trust the value returned by this method. A client could send
- * a malicious media type with the intention to corrupt or hack your
- * application.
- *
- * Implementations SHOULD return the value stored in the "type" key of
- * the file in the $_FILES array.
- *
- * @return string|null The media type sent by the client or null if none
- * was provided.
- */
- public function getClientMediaType()
- {
- return $this->type;
- }
-
- /**
- * Retrieve the file size.
- *
- * Implementations SHOULD return the value stored in the "size" key of
- * the file in the $_FILES array if available, as PHP calculates this based
- * on the actual size transmitted.
- *
- * @return int|null The file size in bytes or null if unknown.
- */
- public function getSize()
- {
- return $this->size;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Http;
-
-use InvalidArgumentException;
-use \Psr\Http\Message\UriInterface;
-use Slim\Http\Environment;
-
-/**
- * Value object representing a URI.
- *
- * This interface is meant to represent URIs according to RFC 3986 and to
- * provide methods for most common operations. Additional functionality for
- * working with URIs can be provided on top of the interface or externally.
- * Its primary use is for HTTP requests, but may also be used in other
- * contexts.
- *
- * Instances of this interface are considered immutable; all methods that
- * might change state MUST be implemented such that they retain the internal
- * state of the current instance and return an instance that contains the
- * changed state.
- *
- * Typically the Host header will be also be present in the request message.
- * For server-side requests, the scheme will typically be discoverable in the
- * server parameters.
- *
- * @link http://tools.ietf.org/html/rfc3986 (the URI specification)
- */
-class Uri implements UriInterface
-{
- /**
- * Uri scheme (without "://" suffix)
- *
- * @var string
- */
- protected $scheme = '';
-
- /**
- * Uri user
- *
- * @var string
- */
- protected $user = '';
-
- /**
- * Uri password
- *
- * @var string
- */
- protected $password = '';
-
- /**
- * Uri host
- *
- * @var string
- */
- protected $host = '';
-
- /**
- * Uri port number
- *
- * @var null|int
- */
- protected $port;
-
- /**
- * Uri base path
- *
- * @var string
- */
- protected $basePath = '';
-
- /**
- * Uri path
- *
- * @var string
- */
- protected $path = '';
-
- /**
- * Uri query string (without "?" prefix)
- *
- * @var string
- */
- protected $query = '';
-
- /**
- * Uri fragment string (without "#" prefix)
- *
- * @var string
- */
- protected $fragment = '';
-
- /**
- * Create new Uri.
- *
- * @param string $scheme Uri scheme.
- * @param string $host Uri host.
- * @param int $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(
- $scheme,
- $host,
- $port = null,
- $path = '/',
- $query = '',
- $fragment = '',
- $user = '',
- $password = ''
- ) {
- $this->scheme = $this->filterScheme($scheme);
- $this->host = $host;
- $this->port = $this->filterPort($port);
- $this->path = empty($path) ? '/' : $this->filterPath($path);
- $this->query = $this->filterQuery($query);
- $this->fragment = $this->filterQuery($fragment);
- $this->user = $user;
- $this->password = $password;
- }
-
- /**
- * Create new Uri from string.
- *
- * @param string $uri Complete Uri string
- * (i.e., https://user:pass@host:443/path?query).
- *
- * @return self
- */
- public static function createFromString($uri)
- {
- if (!is_string($uri) && !method_exists($uri, '__toString')) {
- throw new InvalidArgumentException('Uri must be a string');
- }
-
- $parts = parse_url($uri);
- $scheme = isset($parts['scheme']) ? $parts['scheme'] : '';
- $user = isset($parts['user']) ? $parts['user'] : '';
- $pass = isset($parts['pass']) ? $parts['pass'] : '';
- $host = isset($parts['host']) ? $parts['host'] : '';
- $port = isset($parts['port']) ? $parts['port'] : null;
- $path = isset($parts['path']) ? $parts['path'] : '';
- $query = isset($parts['query']) ? $parts['query'] : '';
- $fragment = isset($parts['fragment']) ? $parts['fragment'] : '';
-
- return new static($scheme, $host, $port, $path, $query, $fragment, $user, $pass);
- }
-
- /**
- * Create new Uri from environment.
- *
- * @param Environment $env
- *
- * @return self
- */
- public static function createFromEnvironment(Environment $env)
- {
- // Scheme
- $isSecure = $env->get('HTTPS');
- $scheme = (empty($isSecure) || $isSecure === 'off') ? 'http' : 'https';
-
- // Authority: Username and password
- $username = $env->get('PHP_AUTH_USER', '');
- $password = $env->get('PHP_AUTH_PW', '');
-
- // Authority: Host
- if ($env->has('HTTP_HOST')) {
- $host = $env->get('HTTP_HOST');
- } else {
- $host = $env->get('SERVER_NAME');
- }
-
- // Authority: Port
- $port = (int)$env->get('SERVER_PORT', 80);
- if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', $host, $matches)) {
- $host = $matches[1];
-
- if (isset($matches[2])) {
- $port = (int) substr($matches[2], 1);
- }
- } else {
- $pos = strpos($host, ':');
- if ($pos !== false) {
- $port = (int) substr($host, $pos + 1);
- $host = strstr($host, ':', true);
- }
- }
-
- // Path
- $requestScriptName = parse_url($env->get('SCRIPT_NAME'), PHP_URL_PATH);
- $requestScriptDir = dirname($requestScriptName);
-
- // parse_url() requires a full URL. As we don't extract the domain name or scheme,
- // we use a stand-in.
- $requestUri = parse_url('http://example.com' . $env->get('REQUEST_URI'), PHP_URL_PATH);
-
- $basePath = '';
- $virtualPath = $requestUri;
- if (stripos($requestUri, $requestScriptName) === 0) {
- $basePath = $requestScriptName;
- } elseif ($requestScriptDir !== '/' && stripos($requestUri, $requestScriptDir) === 0) {
- $basePath = $requestScriptDir;
- }
-
- if ($basePath) {
- $virtualPath = ltrim(substr($requestUri, strlen($basePath)), '/');
- }
-
- // Query string
- $queryString = $env->get('QUERY_STRING', '');
- if ($queryString === '') {
- $queryString = parse_url('http://example.com' . $env->get('REQUEST_URI'), PHP_URL_QUERY);
- }
-
- // Fragment
- $fragment = '';
-
- // Build Uri
- $uri = new static($scheme, $host, $port, $virtualPath, $queryString, $fragment, $username, $password);
- if ($basePath) {
- $uri = $uri->withBasePath($basePath);
- }
-
- return $uri;
- }
-
- /********************************************************************************
- * Scheme
- *******************************************************************************/
-
- /**
- * Retrieve the scheme component of the URI.
- *
- * If no scheme is present, this method MUST return an empty string.
- *
- * The value returned MUST be normalized to lowercase, per RFC 3986
- * Section 3.1.
- *
- * The trailing ":" character is not part of the scheme and MUST NOT be
- * added.
- *
- * @see https://tools.ietf.org/html/rfc3986#section-3.1
- * @return string The URI scheme.
- */
- public function getScheme()
- {
- return $this->scheme;
- }
-
- /**
- * 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 self A new instance with the specified scheme.
- * @throws \InvalidArgumentException for invalid or unsupported schemes.
- */
- public function withScheme($scheme)
- {
- $scheme = $this->filterScheme($scheme);
- $clone = clone $this;
- $clone->scheme = $scheme;
-
- return $clone;
- }
-
- /**
- * Filter Uri scheme.
- *
- * @param string $scheme Raw Uri scheme.
- * @return string
- *
- * @throws InvalidArgumentException If the Uri scheme is not a string.
- * @throws InvalidArgumentException If Uri scheme is not "", "https", or "http".
- */
- protected function filterScheme($scheme)
- {
- static $valid = [
- '' => true,
- 'https' => true,
- 'http' => true,
- ];
-
- if (!is_string($scheme) && !method_exists($scheme, '__toString')) {
- throw new InvalidArgumentException('Uri scheme must be a string');
- }
-
- $scheme = str_replace('://', '', strtolower((string)$scheme));
- if (!isset($valid[$scheme])) {
- throw new InvalidArgumentException('Uri scheme must be one of: "", "https", "http"');
- }
-
- return $scheme;
- }
-
- /********************************************************************************
- * Authority
- *******************************************************************************/
-
- /**
- * Retrieve the authority component of the URI.
- *
- * If no authority information is present, this method MUST return an empty
- * string.
- *
- * The authority syntax of the URI is:
- *
- * <pre>
- * [user-info@]host[:port]
- * </pre>
- *
- * 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()
- {
- $userInfo = $this->getUserInfo();
- $host = $this->getHost();
- $port = $this->getPort();
-
- return ($userInfo ? $userInfo . '@' : '') . $host . ($port !== null ? ':' . $port : '');
- }
-
- /**
- * 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()
- {
- return $this->user . ($this->password ? ':' . $this->password : '');
- }
-
- /**
- * 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 self A new instance with the specified user information.
- */
- public function withUserInfo($user, $password = null)
- {
- $clone = clone $this;
- $clone->user = $this->filterUserInfo($user);
- if ($clone->user) {
- $clone->password = $password ? $this->filterUserInfo($password) : '';
- } else {
- $clone->password = '';
- }
-
- return $clone;
- }
-
- /**
- * Filters the user info string.
- *
- * @param string $query The raw uri query string.
- * @return string The percent-encoded query string.
- */
- protected function filterUserInfo($query)
- {
- return preg_replace_callback(
- '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=]+|%(?![A-Fa-f0-9]{2}))/u',
- function ($match) {
- return rawurlencode($match[0]);
- },
- $query
- );
- }
-
- /**
- * 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()
- {
- return $this->host;
- }
-
- /**
- * 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 self A new instance with the specified host.
- * @throws \InvalidArgumentException for invalid hostnames.
- */
- public function withHost($host)
- {
- $clone = clone $this;
- $clone->host = $host;
-
- return $clone;
- }
-
- /**
- * 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()
- {
- return $this->port && !$this->hasStandardPort() ? $this->port : null;
- }
-
- /**
- * 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 self A new instance with the specified port.
- * @throws \InvalidArgumentException for invalid ports.
- */
- public function withPort($port)
- {
- $port = $this->filterPort($port);
- $clone = clone $this;
- $clone->port = $port;
-
- return $clone;
- }
-
- /**
- * Does this Uri use a standard port?
- *
- * @return bool
- */
- protected function hasStandardPort()
- {
- return ($this->scheme === 'http' && $this->port === 80) || ($this->scheme === 'https' && $this->port === 443);
- }
-
- /**
- * Filter Uri port.
- *
- * @param null|int $port The Uri port number.
- * @return null|int
- *
- * @throws InvalidArgumentException If the port is invalid.
- */
- protected function filterPort($port)
- {
- if (is_null($port) || (is_integer($port) && ($port >= 1 && $port <= 65535))) {
- return $port;
- }
-
- throw new InvalidArgumentException('Uri port must be null or an integer between 1 and 65535 (inclusive)');
- }
-
- /********************************************************************************
- * Path
- *******************************************************************************/
-
- /**
- * 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()
- {
- return $this->path;
- }
-
- /**
- * 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 self A new instance with the specified path.
- * @throws \InvalidArgumentException for invalid paths.
- */
- public function withPath($path)
- {
- if (!is_string($path)) {
- throw new InvalidArgumentException('Uri path must be a string');
- }
-
- $clone = clone $this;
- $clone->path = $this->filterPath($path);
-
- // if the path is absolute, then clear basePath
- if (substr($path, 0, 1) == '/') {
- $clone->basePath = '';
- }
-
- return $clone;
- }
-
- /**
- * Retrieve the base path segment of the URI.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * This method MUST return a string; if no path is present it MUST return
- * an empty string.
- *
- * @return string The base path segment of the URI.
- */
- public function getBasePath()
- {
- return $this->basePath;
- }
-
- /**
- * Set base path.
- *
- * Note: This method is not part of the PSR-7 standard.
- *
- * @param string $basePath
- * @return self
- */
- public function withBasePath($basePath)
- {
- if (!is_string($basePath)) {
- throw new InvalidArgumentException('Uri path must be a string');
- }
- if (!empty($basePath)) {
- $basePath = '/' . trim($basePath, '/'); // <-- Trim on both sides
- }
- $clone = clone $this;
-
- if ($basePath !== '/') {
- $clone->basePath = $this->filterPath($basePath);
- }
-
- 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)
- {
- return preg_replace_callback(
- '/(?:[^a-zA-Z0-9_\-\.~:@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/',
- function ($match) {
- return rawurlencode($match[0]);
- },
- $path
- );
- }
-
- /********************************************************************************
- * Query
- *******************************************************************************/
-
- /**
- * 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()
- {
- return $this->query;
- }
-
- /**
- * 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 self A new instance with the specified query string.
- * @throws \InvalidArgumentException for invalid query strings.
- */
- public function withQuery($query)
- {
- if (!is_string($query) && !method_exists($query, '__toString')) {
- throw new InvalidArgumentException('Uri query must be a string');
- }
- $query = ltrim((string)$query, '?');
- $clone = clone $this;
- $clone->query = $this->filterQuery($query);
-
- return $clone;
- }
-
- /**
- * Filters the query string or fragment of a URI.
- *
- * @param string $query The raw uri query string.
- * @return string The percent-encoded query string.
- */
- protected function filterQuery($query)
- {
- return preg_replace_callback(
- '/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/',
- function ($match) {
- return rawurlencode($match[0]);
- },
- $query
- );
- }
-
- /********************************************************************************
- * Fragment
- *******************************************************************************/
-
- /**
- * 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()
- {
- return $this->fragment;
- }
-
- /**
- * 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 self A new instance with the specified fragment.
- */
- public function withFragment($fragment)
- {
- if (!is_string($fragment) && !method_exists($fragment, '__toString')) {
- throw new InvalidArgumentException('Uri fragment must be a string');
- }
- $fragment = ltrim((string)$fragment, '#');
- $clone = clone $this;
- $clone->fragment = $this->filterQuery($fragment);
-
- return $clone;
- }
-
- /********************************************************************************
- * Helpers
- *******************************************************************************/
-
- /**
- * 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()
- {
- $scheme = $this->getScheme();
- $authority = $this->getAuthority();
- $basePath = $this->getBasePath();
- $path = $this->getPath();
- $query = $this->getQuery();
- $fragment = $this->getFragment();
-
- $path = $basePath . '/' . ltrim($path, '/');
-
- return ($scheme ? $scheme . ':' : '')
- . ($authority ? '//' . $authority : '')
- . $path
- . ($query ? '?' . $query : '')
- . ($fragment ? '#' . $fragment : '');
- }
-
- /**
- * Return the fully qualified base URL.
- *
- * Note that this method never includes a trailing /
- *
- * This method is not part of PSR-7.
- *
- * @return string
- */
- public function getBaseUrl()
- {
- $scheme = $this->getScheme();
- $authority = $this->getAuthority();
- $basePath = $this->getBasePath();
-
- if ($authority && substr($basePath, 0, 1) !== '/') {
- $basePath = $basePath . '/' . $basePath;
- }
-
- return ($scheme ? $scheme . ':' : '')
- . ($authority ? '//' . $authority : '')
- . rtrim($basePath, '/');
- }
-}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+interface AdvancedCallableResolverInterface extends CallableResolverInterface
+{
+ /**
+ * Resolve $toResolve into a callable
+ *
+ * @param string|callable $toResolve
+ */
+ public function resolveRoute($toResolve): callable;
+
+ /**
+ * Resolve $toResolve into a callable
+ *
+ * @param string|callable $toResolve
+ */
+ public function resolveMiddleware($toResolve): callable;
+}
<?php
+
/**
* Slim Framework (https://slimframework.com)
*
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/
+
+declare(strict_types=1);
+
namespace Slim\Interfaces;
-/**
- * Resolves a callable.
- *
- * @package Slim
- * @since 3.0.0
- */
interface CallableResolverInterface
{
/**
- * Invoke the resolved callable.
- *
- * @param mixed $toResolve
+ * Resolve $toResolve into a callable
*
- * @return callable
+ * @param string|callable $toResolve
*/
- public function resolve($toResolve);
+ public function resolve($toResolve): callable;
}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Interfaces;
-
-/**
- * Collection Interface
- *
- * @package Slim
- * @since 3.0.0
- */
-interface CollectionInterface extends \ArrayAccess, \Countable, \IteratorAggregate
-{
- public function set($key, $value);
-
- public function get($key, $default = null);
-
- public function replace(array $items);
-
- public function all();
-
- public function has($key);
-
- public function remove($key);
-
- public function clear();
-}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use Slim\Routing\RoutingResults;
+
+interface DispatcherInterface
+{
+ /**
+ * Get routing results for a given request method and uri
+ */
+ public function dispatch(string $method, string $uri): RoutingResults;
+
+ /**
+ * Get allowed methods for a given uri
+ *
+ * @return string[]
+ */
+ public function getAllowedMethods(string $uri): array;
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Throwable;
+
+interface ErrorHandlerInterface
+{
+ public function __invoke(
+ ServerRequestInterface $request,
+ Throwable $exception,
+ bool $displayErrorDetails,
+ bool $logErrors,
+ bool $logErrorDetails
+ ): ResponseInterface;
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use Throwable;
+
+interface ErrorRendererInterface
+{
+ public function __invoke(Throwable $exception, bool $displayErrorDetails): string;
+}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Interfaces\Http;
-
-/**
- * Cookies Interface
- *
- * @package Slim
- * @since 3.0.0
- */
-interface CookiesInterface
-{
- public function get($name, $default = null);
- public function set($name, $value);
- public function toHeaders();
- public static function parseHeader($header);
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Interfaces\Http;
-
-/**
- * Environment Interface
- *
- * @package Slim
- * @since 3.0.0
- */
-interface EnvironmentInterface
-{
- public static function mock(array $settings = []);
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Interfaces\Http;
-
-use Slim\Interfaces\CollectionInterface;
-
-/**
- * Headers Interface
- *
- * @package Slim
- * @since 3.0.0
- */
-interface HeadersInterface extends CollectionInterface
-{
- public function add($key, $value);
-
- public function normalizeKey($key);
-}
<?php
+
/**
* Slim Framework (https://slimframework.com)
*
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/
+
+declare(strict_types=1);
+
namespace Slim\Interfaces;
use Psr\Http\Message\ResponseInterface;
/**
* Invoke a route callable.
*
- * @param callable $callable The callable to invoke using the strategy.
- * @param ServerRequestInterface $request The request object.
- * @param ResponseInterface $response The response object.
- * @param array $routeArguments The route's placholder arguments
+ * @param callable $callable The callable to invoke using the strategy.
+ * @param ServerRequestInterface $request The request object.
+ * @param ResponseInterface $response The response object.
+ * @param array<string, string> $routeArguments The route's placeholder arguments
*
- * @return ResponseInterface|string The response from the callable.
+ * @return ResponseInterface The response from the callable.
*/
public function __invoke(
callable $callable,
ServerRequestInterface $request,
ResponseInterface $response,
array $routeArguments
- );
+ ): ResponseInterface;
}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+
+interface MiddlewareDispatcherInterface extends RequestHandlerInterface
+{
+ /**
+ * 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): self;
+
+ /**
+ * 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): self;
+
+ /**
+ * Seed the middleware stack with the inner request handler
+ */
+ public function seedMiddlewareStack(RequestHandlerInterface $kernel): void;
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\StreamFactoryInterface;
+use RuntimeException;
+
+interface Psr17FactoryInterface
+{
+ /**
+ * @throws RuntimeException when the factory could not be instantiated
+ */
+ public static function getResponseFactory(): ResponseFactoryInterface;
+
+ /**
+ * @throws RuntimeException when the factory could not be instantiated
+ */
+ public static function getStreamFactory(): StreamFactoryInterface;
+
+ /**
+ * @throws RuntimeException when the factory could not be instantiated
+ */
+ public static function getServerRequestCreator(): ServerRequestCreatorInterface;
+
+ /**
+ * Is the PSR-17 ResponseFactory available
+ */
+ public static function isResponseFactoryAvailable(): bool;
+
+ /**
+ * Is the PSR-17 StreamFactory available
+ */
+ public static function isStreamFactoryAvailable(): bool;
+
+ /**
+ * Is the ServerRequest creator available
+ */
+ public static function isServerRequestCreatorAvailable(): bool;
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+interface Psr17FactoryProviderInterface
+{
+ /**
+ * @return string[]
+ */
+ public static function getFactories(): array;
+
+ /**
+ * @param string[] $factories
+ */
+ public static function setFactories(array $factories): void;
+
+ public static function addFactory(string $factory): void;
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+interface RequestHandlerInvocationStrategyInterface extends InvocationStrategyInterface
+{
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use InvalidArgumentException;
+use RuntimeException;
+
+interface RouteCollectorInterface
+{
+ /**
+ * Get the route parser
+ */
+ public function getRouteParser(): RouteParserInterface;
+
+ /**
+ * Get default route invocation strategy
+ */
+ public function getDefaultInvocationStrategy(): InvocationStrategyInterface;
+
+ /**
+ * Set default route invocation strategy
+ */
+ public function setDefaultInvocationStrategy(InvocationStrategyInterface $strategy): RouteCollectorInterface;
+
+ /**
+ * Get path to FastRoute cache file
+ */
+ public function getCacheFile(): ?string;
+
+ /**
+ * Set path to FastRoute cache file
+ *
+ * @throws InvalidArgumentException
+ * @throws RuntimeException
+ */
+ public function setCacheFile(string $cacheFile): RouteCollectorInterface;
+
+ /**
+ * Get the base path used in pathFor()
+ */
+ public function getBasePath(): string;
+
+ /**
+ * Set the base path used in pathFor()
+ */
+ public function setBasePath(string $basePath): RouteCollectorInterface;
+
+ /**
+ * Get route objects
+ *
+ * @return RouteInterface[]
+ */
+ public function getRoutes(): array;
+
+ /**
+ * Get named route object
+ *
+ * @param string $name Route name
+ *
+ * @throws RuntimeException If named route does not exist
+ */
+ public function getNamedRoute(string $name): RouteInterface;
+
+ /**
+ * Remove named route
+ *
+ * @param string $name Route name
+ *
+ * @throws RuntimeException If named route does not exist
+ */
+ public function removeNamedRoute(string $name): RouteCollectorInterface;
+
+ /**
+ * Lookup a route via the route's unique identifier
+ *
+ * @throws RuntimeException If route of identifier does not exist
+ */
+ public function lookupRoute(string $identifier): RouteInterface;
+
+ /**
+ * Add route group
+ * @param string|callable $callable
+ */
+ public function group(string $pattern, $callable): RouteGroupInterface;
+
+ /**
+ * Add route
+ *
+ * @param string[] $methods Array of HTTP methods
+ * @param string $pattern The route pattern
+ * @param callable|string $handler The route callable
+ */
+ public function map(array $methods, string $pattern, $handler): RouteInterface;
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use Psr\Container\ContainerInterface;
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\UriInterface;
+
+interface RouteCollectorProxyInterface
+{
+ public function getResponseFactory(): ResponseFactoryInterface;
+
+ public function getCallableResolver(): CallableResolverInterface;
+
+ public function getContainer(): ?ContainerInterface;
+
+ public function getRouteCollector(): RouteCollectorInterface;
+
+ /**
+ * Get the RouteCollectorProxy's base path
+ */
+ public function getBasePath(): string;
+
+ /**
+ * Set the RouteCollectorProxy's base path
+ */
+ 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;
+}
<?php
+
/**
* Slim Framework (https://slimframework.com)
*
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/
+
+declare(strict_types=1);
+
namespace Slim\Interfaces;
-use Slim\App;
+use Psr\Http\Server\MiddlewareInterface;
+use Slim\MiddlewareDispatcher;
-/**
- * RouteGroup Interface
- *
- * @package Slim
- * @since 3.0.0
- */
interface RouteGroupInterface
{
+ public function collectRoutes(): RouteGroupInterface;
+
/**
- * Get route pattern
+ * Add middleware to the route group
*
- * @return string
+ * @param MiddlewareInterface|string|callable $middleware
*/
- public function getPattern();
+ public function add($middleware): RouteGroupInterface;
/**
- * Prepend middleware to the group middleware collection
- *
- * @param callable|string $callable The callback routine
- *
- * @return RouteGroupInterface
+ * Add middleware to the route group
*/
- public function add($callable);
+ public function addMiddleware(MiddlewareInterface $middleware): RouteGroupInterface;
/**
- * Execute route group callable in the context of the Slim App
- *
- * This method invokes the route group object's callable, collecting
- * nested route objects
- *
- * @param App $app
+ * Append the group's middleware to the MiddlewareDispatcher
+ */
+ public function appendMiddlewareToDispatcher(MiddlewareDispatcher $dispatcher): RouteGroupInterface;
+
+ /**
+ * Get the RouteGroup's pattern
*/
- public function __invoke(App $app);
+ public function getPattern(): string;
}
<?php
+
/**
* Slim Framework (https://slimframework.com)
*
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/
+
+declare(strict_types=1);
+
namespace Slim\Interfaces;
-use InvalidArgumentException;
-use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
-/**
- * Route Interface
- *
- * @package Slim
- * @since 3.0.0
- */
interface RouteInterface
{
+ /**
+ * Get route invocation strategy
+ */
+ public function getInvocationStrategy(): InvocationStrategyInterface;
/**
- * Retrieve a specific route argument
- *
- * @param string $name
- * @param string|null $default
- *
- * @return string|null
+ * Set route invocation strategy
*/
- public function getArgument($name, $default = null);
+ public function setInvocationStrategy(InvocationStrategyInterface $invocationStrategy): RouteInterface;
/**
- * Get route arguments
+ * Get route methods
*
* @return string[]
*/
- public function getArguments();
+ public function getMethods(): array;
/**
- * Get route name
- *
- * @return null|string
+ * Get route pattern
*/
- public function getName();
+ public function getPattern(): string;
/**
- * Get route pattern
- *
- * @return string
+ * Set route pattern
*/
- public function getPattern();
+ public function setPattern(string $pattern): RouteInterface;
/**
- * Set a route argument
- *
- * @param string $name
- * @param string $value
+ * Get route callable
*
- * @return self
+ * @return callable|string
*/
- public function setArgument($name, $value);
+ public function getCallable();
/**
- * Replace route arguments
- *
- * @param string[] $arguments
+ * Set route callable
*
- * @return self
+ * @param callable|string $callable
*/
- public function setArguments(array $arguments);
+ public function setCallable($callable): RouteInterface;
/**
- * Set output buffering mode
- *
- * One of: false, 'prepend' or 'append'
- *
- * @param boolean|string $mode
- *
- * @throws InvalidArgumentException If an unknown buffering mode is specified
+ * Get route name
*/
- public function setOutputBuffering($mode);
+ public function getName(): ?string;
/**
* Set route name
*
- * @param string $name
- *
* @return static
- * @throws InvalidArgumentException if the route name is not a string
*/
- public function setName($name);
+ public function setName(string $name): RouteInterface;
/**
- * Add middleware
- *
- * This method prepends new middleware to the route's middleware stack.
+ * Get the route's unique identifier
+ */
+ public function getIdentifier(): string;
+
+ /**
+ * Retrieve a specific route argument
+ */
+ public function getArgument(string $name, ?string $default = null): ?string;
+
+ /**
+ * Get route arguments
*
- * @param callable|string $callable The callback routine
+ * @return array<string, string>
+ */
+ public function getArguments(): array;
+
+ /**
+ * Set a route argument
+ */
+ public function setArgument(string $name, string $value): RouteInterface;
+
+ /**
+ * Replace route arguments
*
- * @return RouteInterface
+ * @param array<string, string> $arguments
*/
- public function add($callable);
+ 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 ServerRequestInterface $request
- * @param array $arguments
+ * @param array<string, string> $arguments
*/
- public function prepare(ServerRequestInterface $request, 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.
- *
- * @param ServerRequestInterface $request
- * @param ResponseInterface $response
- * @return ResponseInterface
- */
- public function run(ServerRequestInterface $request, ResponseInterface $response);
-
- /**
- * Dispatch route callable against current Request and Response objects
- *
- * This method invokes the route object's callable. If middleware is
- * registered for the route, each callable middleware is invoked in
- * the order specified.
- *
- * @param ServerRequestInterface $request The current Request object
- * @param ResponseInterface $response The current Response object
- *
- * @return ResponseInterface
*/
- public function __invoke(ServerRequestInterface $request, ResponseInterface $response);
+ public function run(ServerRequestInterface $request): ResponseInterface;
}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use InvalidArgumentException;
+use Psr\Http\Message\UriInterface;
+use RuntimeException;
+
+interface RouteParserInterface
+{
+ /**
+ * Build the path for a named route excluding the base path
+ *
+ * @param string $routeName Route name
+ * @param array<string, string> $data Named argument replacement data
+ * @param array<string, string> $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<string, string> $data Named argument replacement data
+ * @param array<string, string> $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<string, string> $data Named argument replacement data
+ * @param array<string, string> $queryParams Optional query string parameters
+ */
+ public function fullUrlFor(UriInterface $uri, string $routeName, array $data = [], array $queryParams = []): string;
+}
--- /dev/null
+<?php
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use Slim\Routing\RoutingResults;
+
+interface RouteResolverInterface
+{
+ /**
+ * @param string $uri Should be ServerRequestInterface::getUri()->getPath()
+ */
+ public function computeRoutingResults(string $uri, string $method): RoutingResults;
+
+ public function resolveRoute(string $identifier): RouteInterface;
+}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim\Interfaces;
-
-use RuntimeException;
-use InvalidArgumentException;
-use Psr\Http\Message\ServerRequestInterface;
-
-/**
- * Router Interface
- *
- * @package Slim
- * @since 3.0.0
- */
-interface RouterInterface
-{
- // array keys from route result
- const DISPATCH_STATUS = 0;
- const ALLOWED_METHODS = 1;
-
- /**
- * Add route
- *
- * @param string[] $methods Array of HTTP methods
- * @param string $pattern The route pattern
- * @param callable $handler The route callable
- *
- * @return RouteInterface
- */
- public function map($methods, $pattern, $handler);
-
- /**
- * Dispatch router for HTTP request
- *
- * @param ServerRequestInterface $request The current HTTP request object
- *
- * @return array
- *
- * @link https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php
- */
- public function dispatch(ServerRequestInterface $request);
-
- /**
- * Add a route group to the array
- *
- * @param string $pattern The group pattern
- * @param callable $callable A group callable
- *
- * @return RouteGroupInterface
- */
- public function pushGroup($pattern, $callable);
-
- /**
- * Removes the last route group from the array
- *
- * @return bool True if successful, else False
- */
- public function popGroup();
-
- /**
- * Get named route object
- *
- * @param string $name Route name
- *
- * @return \Slim\Interfaces\RouteInterface
- *
- * @throws RuntimeException If named route does not exist
- */
- public function getNamedRoute($name);
-
- /**
- * @param $identifier
- *
- * @return \Slim\Interfaces\RouteInterface
- */
- public function lookupRoute($identifier);
-
- /**
- * Build the path for a named route excluding the base path
- *
- * @param string $name Route name
- * @param array $data Named argument replacement data
- * @param array $queryParams Optional query string parameters
- *
- * @return string
- *
- * @throws RuntimeException If named route does not exist
- * @throws InvalidArgumentException If required data not provided
- */
- public function relativePathFor($name, array $data = [], array $queryParams = []);
-
- /**
- * Build the path for a named route including the base path
- *
- * @param string $name Route name
- * @param array $data Named argument replacement data
- * @param array $queryParams Optional query string parameters
- *
- * @return string
- *
- * @throws RuntimeException If named route does not exist
- * @throws InvalidArgumentException If required data not provided
- */
- public function pathFor($name, array $data = [], array $queryParams = []);
-}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Interfaces;
+
+use Psr\Http\Message\ServerRequestInterface;
+
+interface ServerRequestCreatorInterface
+{
+ public function createServerRequestFromGlobals(): ServerRequestInterface;
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim;
+
+use Psr\Log\AbstractLogger;
+use Psr\Log\InvalidArgumentException;
+use Stringable;
+
+use function error_log;
+
+class Logger extends AbstractLogger
+{
+ /**
+ * @param mixed $level
+ * @param string|Stringable $message
+ * @param array<mixed> $context
+ *
+ * @throws InvalidArgumentException
+ */
+ public function log($level, $message, array $context = []): void
+ {
+ error_log((string) $message);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Middleware;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use RuntimeException;
+
+use function count;
+use function explode;
+use function is_array;
+use function is_null;
+use function is_object;
+use function is_string;
+use function json_decode;
+use function libxml_clear_errors;
+use function libxml_disable_entity_loader;
+use function libxml_use_internal_errors;
+use function parse_str;
+use function simplexml_load_string;
+use function strtolower;
+use function trim;
+
+use const LIBXML_VERSION;
+
+class BodyParsingMiddleware implements MiddlewareInterface
+{
+ /**
+ * @var callable[]
+ */
+ protected array $bodyParsers;
+
+ /**
+ * @param callable[] $bodyParsers list of body parsers as an associative array of mediaType => 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<mixed>|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
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Middleware;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+
+class ContentLengthMiddleware implements MiddlewareInterface
+{
+ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
+ {
+ $response = $handler->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;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Middleware;
+
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use Psr\Log\LoggerInterface;
+use Slim\Exception\HttpException;
+use Slim\Handlers\ErrorHandler;
+use Slim\Interfaces\CallableResolverInterface;
+use Slim\Interfaces\ErrorHandlerInterface;
+use Throwable;
+
+use function get_class;
+use function is_subclass_of;
+
+class ErrorMiddleware implements MiddlewareInterface
+{
+ protected CallableResolverInterface $callableResolver;
+
+ protected ResponseFactoryInterface $responseFactory;
+
+ protected bool $displayErrorDetails;
+
+ protected bool $logErrors;
+
+ protected bool $logErrorDetails;
+
+ protected ?LoggerInterface $logger = null;
+
+ /**
+ * @var ErrorHandlerInterface[]|callable[]|string[]
+ */
+ protected array $handlers = [];
+
+ /**
+ * @var ErrorHandlerInterface[]|callable[]|string[]
+ */
+ protected array $subClassHandlers = [];
+
+ /**
+ * @var ErrorHandlerInterface|callable|string|null
+ */
+ protected $defaultErrorHandler;
+
+ public function __construct(
+ CallableResolverInterface $callableResolver,
+ ResponseFactoryInterface $responseFactory,
+ bool $displayErrorDetails,
+ bool $logErrors,
+ bool $logErrorDetails,
+ ?LoggerInterface $logger = null
+ ) {
+ $this->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;
+ }
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Middleware;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+
+use function is_array;
+use function strtoupper;
+
+class MethodOverrideMiddleware implements MiddlewareInterface
+{
+ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
+ {
+ $methodHeader = $request->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);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Middleware;
+
+use InvalidArgumentException;
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Message\StreamFactoryInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use Throwable;
+
+use function in_array;
+use function ob_end_clean;
+use function ob_get_clean;
+use function ob_start;
+
+class OutputBufferingMiddleware implements MiddlewareInterface
+{
+ public const APPEND = 'append';
+ public const PREPEND = 'prepend';
+
+ protected StreamFactoryInterface $streamFactory;
+
+ protected string $style;
+
+ /**
+ * @param string $style Either "append" or "prepend"
+ */
+ public function __construct(StreamFactoryInterface $streamFactory, string $style = 'append')
+ {
+ $this->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;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Middleware;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use RuntimeException;
+use Slim\Exception\HttpMethodNotAllowedException;
+use Slim\Exception\HttpNotFoundException;
+use Slim\Interfaces\RouteParserInterface;
+use Slim\Interfaces\RouteResolverInterface;
+use Slim\Routing\RouteContext;
+use Slim\Routing\RoutingResults;
+
+class RoutingMiddleware implements MiddlewareInterface
+{
+ protected RouteResolverInterface $routeResolver;
+
+ protected RouteParserInterface $routeParser;
+
+ public function __construct(RouteResolverInterface $routeResolver, RouteParserInterface $routeParser)
+ {
+ $this->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()
+ );
+ }
+}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim;
-
-use RuntimeException;
-use Psr\Http\Message\ServerRequestInterface;
-use Psr\Http\Message\ResponseInterface;
-use UnexpectedValueException;
-
-/**
- * Middleware
- *
- * This is an internal class that enables concentric middleware layers. This
- * class is an implementation detail and is used only inside of the Slim
- * application; it is not visible to—and should not be used by—end users.
- */
-trait MiddlewareAwareTrait
-{
- /**
- * Tip of the middleware call stack
- *
- * @var callable
- */
- protected $tip;
-
- /**
- * Middleware stack lock
- *
- * @var bool
- */
- protected $middlewareLock = false;
-
- /**
- * Add middleware
- *
- * This method prepends new middleware to the application middleware stack.
- *
- * @param callable $callable Any callable that accepts three arguments:
- * 1. A Request object
- * 2. A Response object
- * 3. A "next" middleware callable
- * @return static
- *
- * @throws RuntimeException If middleware is added while the stack is dequeuing
- * @throws UnexpectedValueException If the middleware doesn't return a Psr\Http\Message\ResponseInterface
- */
- protected function addMiddleware(callable $callable)
- {
- if ($this->middlewareLock) {
- throw new RuntimeException('Middleware can’t be added once the stack is dequeuing');
- }
-
- if (is_null($this->tip)) {
- $this->seedMiddlewareStack();
- }
- $next = $this->tip;
- $this->tip = function (
- ServerRequestInterface $request,
- ResponseInterface $response
- ) use (
- $callable,
- $next
- ) {
- $result = call_user_func($callable, $request, $response, $next);
- if ($result instanceof ResponseInterface === false) {
- throw new UnexpectedValueException(
- 'Middleware must return instance of \Psr\Http\Message\ResponseInterface'
- );
- }
-
- return $result;
- };
-
- return $this;
- }
-
- /**
- * Seed middleware stack with first callable
- *
- * @param callable $kernel The last item to run as middleware
- *
- * @throws RuntimeException if the stack is seeded more than once
- */
- protected function seedMiddlewareStack(callable $kernel = null)
- {
- if (!is_null($this->tip)) {
- throw new RuntimeException('MiddlewareStack can only be seeded once.');
- }
- if ($kernel === null) {
- $kernel = $this;
- }
- $this->tip = $kernel;
- }
-
- /**
- * Call middleware stack
- *
- * @param ServerRequestInterface $request A request object
- * @param ResponseInterface $response A response object
- *
- * @return ResponseInterface
- */
- public function callMiddlewareStack(ServerRequestInterface $request, ResponseInterface $response)
- {
- if (is_null($this->tip)) {
- $this->seedMiddlewareStack();
- }
- /** @var callable $start */
- $start = $this->tip;
- $this->middlewareLock = true;
- $response = $start($request, $response);
- $this->middlewareLock = false;
- return $response;
- }
-}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim;
+
+use Closure;
+use Psr\Container\ContainerInterface;
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use RuntimeException;
+use Slim\Interfaces\AdvancedCallableResolverInterface;
+use Slim\Interfaces\CallableResolverInterface;
+use Slim\Interfaces\MiddlewareDispatcherInterface;
+
+use function class_exists;
+use function function_exists;
+use function is_callable;
+use function is_string;
+use function preg_match;
+use function sprintf;
+
+class MiddlewareDispatcher implements MiddlewareDispatcherInterface
+{
+ /**
+ * Tip of the middleware call stack
+ */
+ protected RequestHandlerInterface $tip;
+
+ protected ?CallableResolverInterface $callableResolver;
+
+ protected ?ContainerInterface $container;
+
+ public function __construct(
+ RequestHandlerInterface $kernel,
+ ?CallableResolverInterface $callableResolver = null,
+ ?ContainerInterface $container = null
+ ) {
+ $this->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).
+ */
+ 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;
+
+ // 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).
+ */
+ 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;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim;
+
+use Psr\Http\Message\ResponseInterface;
+
+use function connection_status;
+use function header;
+use function headers_sent;
+use function in_array;
+use function min;
+use function sprintf;
+use function strlen;
+use function strtolower;
+
+use const CONNECTION_NORMAL;
+
+class ResponseEmitter
+{
+ private int $responseChunkSize;
+
+ public function __construct(int $responseChunkSize = 4096)
+ {
+ $this->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();
+ }
+}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim;
-
-use Psr\Container\ContainerInterface;
-
-/**
- * A routable, middleware-aware object
- *
- * @package Slim
- * @since 3.0.0
- */
-abstract class Routable
-{
- use CallableResolverAwareTrait;
-
- /**
- * Route callable
- *
- * @var callable
- */
- protected $callable;
-
- /**
- * Container
- *
- * @var ContainerInterface
- */
- protected $container;
-
- /**
- * Route middleware
- *
- * @var callable[]
- */
- protected $middleware = [];
-
- /**
- * Route pattern
- *
- * @var string
- */
- protected $pattern;
-
- /**
- * Get the middleware registered for the group
- *
- * @return callable[]
- */
- public function getMiddleware()
- {
- return $this->middleware;
- }
-
- /**
- * Get the route pattern
- *
- * @return string
- */
- public function getPattern()
- {
- return $this->pattern;
- }
-
- /**
- * Set container for use with resolveCallable
- *
- * @param ContainerInterface $container
- *
- * @return self
- */
- public function setContainer(ContainerInterface $container)
- {
- $this->container = $container;
- return $this;
- }
-
- /**
- * Prepend middleware to the middleware collection
- *
- * @param callable|string $callable The callback routine
- *
- * @return static
- */
- public function add($callable)
- {
- $this->middleware[] = new DeferredCallable($callable, $this->container);
- return $this;
- }
-
- /**
- * Set the route pattern
- *
- * @param string $newPattern
- */
- public function setPattern($newPattern)
- {
- $this->pattern = $newPattern;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim;
-
-use InvalidArgumentException;
-use Psr\Http\Message\ServerRequestInterface;
-use Psr\Http\Message\ResponseInterface;
-use Slim\Handlers\Strategies\RequestResponse;
-use Slim\Interfaces\InvocationStrategyInterface;
-use Slim\Interfaces\RouteInterface;
-
-/**
- * Route
- */
-class Route extends Routable implements RouteInterface
-{
- use MiddlewareAwareTrait;
-
- /**
- * HTTP methods supported by this route
- *
- * @var string[]
- */
- protected $methods = [];
-
- /**
- * Route identifier
- *
- * @var string
- */
- protected $identifier;
-
- /**
- * Route name
- *
- * @var null|string
- */
- protected $name;
-
- /**
- * Parent route groups
- *
- * @var RouteGroup[]
- */
- protected $groups;
-
- private $finalized = false;
-
- /**
- * Output buffering mode
- *
- * One of: false, 'prepend' or 'append'
- *
- * @var boolean|string
- */
- protected $outputBuffering = 'append';
-
- /**
- * Route parameters
- *
- * @var array
- */
- protected $arguments = [];
-
- /**
- * The callable payload
- *
- * @var callable
- */
- protected $callable;
-
- /**
- * Create new route
- *
- * @param string|string[] $methods The route HTTP methods
- * @param string $pattern The route pattern
- * @param callable $callable The route callable
- * @param RouteGroup[] $groups The parent route groups
- * @param int $identifier The route identifier
- */
- public function __construct($methods, $pattern, $callable, $groups = [], $identifier = 0)
- {
- $this->methods = is_string($methods) ? [$methods] : $methods;
- $this->pattern = $pattern;
- $this->callable = $callable;
- $this->groups = $groups;
- $this->identifier = 'route' . $identifier;
- }
-
- /**
- * Finalize the route in preparation for dispatching
- */
- public function finalize()
- {
- if ($this->finalized) {
- return;
- }
-
- $groupMiddleware = [];
- foreach ($this->getGroups() as $group) {
- $groupMiddleware = array_merge($group->getMiddleware(), $groupMiddleware);
- }
-
- $this->middleware = array_merge($this->middleware, $groupMiddleware);
-
- foreach ($this->getMiddleware() as $middleware) {
- $this->addMiddleware($middleware);
- }
-
- $this->finalized = true;
- }
-
- /**
- * Get route callable
- *
- * @return callable
- */
- public function getCallable()
- {
- return $this->callable;
- }
-
- /**
- * This method enables you to override the Route's callable
- *
- * @param string|\Closure $callable
- */
- public function setCallable($callable)
- {
- $this->callable = $callable;
- }
-
- /**
- * Get route methods
- *
- * @return string[]
- */
- public function getMethods()
- {
- return $this->methods;
- }
-
- /**
- * Get parent route groups
- *
- * @return RouteGroup[]
- */
- public function getGroups()
- {
- return $this->groups;
- }
-
- /**
- * Get route name
- *
- * @return null|string
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * Get route identifier
- *
- * @return string
- */
- public function getIdentifier()
- {
- return $this->identifier;
- }
-
- /**
- * Get output buffering mode
- *
- * @return boolean|string
- */
- public function getOutputBuffering()
- {
- return $this->outputBuffering;
- }
-
- /**
- * Set output buffering mode
- *
- * One of: false, 'prepend' or 'append'
- *
- * @param boolean|string $mode
- *
- * @throws InvalidArgumentException If an unknown buffering mode is specified
- */
- public function setOutputBuffering($mode)
- {
- if (!in_array($mode, [false, 'prepend', 'append'], true)) {
- throw new InvalidArgumentException('Unknown output buffering mode');
- }
- $this->outputBuffering = $mode;
- }
-
- /**
- * Set route name
- *
- * @param string $name
- *
- * @return self
- *
- * @throws InvalidArgumentException if the route name is not a string
- */
- public function setName($name)
- {
- if (!is_string($name)) {
- throw new InvalidArgumentException('Route name must be a string');
- }
- $this->name = $name;
- return $this;
- }
-
- /**
- * Set a route argument
- *
- * @param string $name
- * @param string $value
- *
- * @return self
- */
- public function setArgument($name, $value)
- {
- $this->arguments[$name] = $value;
- return $this;
- }
-
- /**
- * Replace route arguments
- *
- * @param array $arguments
- *
- * @return self
- */
- public function setArguments(array $arguments)
- {
- $this->arguments = $arguments;
- return $this;
- }
-
- /**
- * Retrieve route arguments
- *
- * @return array
- */
- public function getArguments()
- {
- return $this->arguments;
- }
-
- /**
- * Retrieve a specific route argument
- *
- * @param string $name
- * @param string|null $default
- *
- * @return mixed
- */
- public function getArgument($name, $default = null)
- {
- if (array_key_exists($name, $this->arguments)) {
- return $this->arguments[$name];
- }
- return $default;
- }
-
- /********************************************************************************
- * Route Runner
- *******************************************************************************/
-
- /**
- * Prepare the route for use
- *
- * @param ServerRequestInterface $request
- * @param array $arguments
- */
- public function prepare(ServerRequestInterface $request, array $arguments)
- {
- // Add the arguments
- foreach ($arguments as $k => $v) {
- $this->setArgument($k, $v);
- }
- }
-
- /**
- * 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.
- *
- * @param ServerRequestInterface $request
- * @param ResponseInterface $response
- *
- * @return ResponseInterface
- */
- public function run(ServerRequestInterface $request, ResponseInterface $response)
- {
- // Finalise route now that we are about to run it
- $this->finalize();
-
- // Traverse middleware stack and fetch updated response
- return $this->callMiddlewareStack($request, $response);
- }
-
- /**
- * Dispatch route callable against current Request and Response objects
- *
- * This method invokes the route object's callable. If middleware is
- * registered for the route, each callable middleware is invoked in
- * the order specified.
- *
- * @param ServerRequestInterface $request The current Request object
- * @param ResponseInterface $response The current Response object
- * @return \Psr\Http\Message\ResponseInterface
- * @throws \Exception if the route callable throws an exception
- */
- public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
- {
- $this->callable = $this->resolveCallable($this->callable);
-
- /** @var InvocationStrategyInterface $handler */
- $handler = isset($this->container) ? $this->container->get('foundHandler') : new RequestResponse();
-
- $newResponse = $handler($this->callable, $request, $response, $this->arguments);
-
- if ($newResponse instanceof ResponseInterface) {
- // if route callback returns a ResponseInterface, then use it
- $response = $newResponse;
- } elseif (is_string($newResponse)) {
- // if route callback returns a string, then append it to the response
- if ($response->getBody()->isWritable()) {
- $response->getBody()->write($newResponse);
- }
- }
-
- return $response;
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim;
-
-use Closure;
-use Slim\Interfaces\RouteGroupInterface;
-
-/**
- * A collector for Routable objects with a common middleware stack
- *
- * @package Slim
- */
-class RouteGroup extends Routable implements RouteGroupInterface
-{
- /**
- * Create a new RouteGroup
- *
- * @param string $pattern The pattern prefix for the group
- * @param callable $callable The group callable
- */
- public function __construct($pattern, $callable)
- {
- $this->pattern = $pattern;
- $this->callable = $callable;
- }
-
- /**
- * Invoke the group to register any Routable objects within it.
- *
- * @param App $app The App instance to bind/pass to the group callable
- */
- public function __invoke(App $app = null)
- {
- $callable = $this->resolveCallable($this->callable);
- if ($callable instanceof Closure && $app !== null) {
- $callable = $callable->bindTo($app);
- }
-
- $callable($app);
- }
-}
+++ /dev/null
-<?php
-/**
- * Slim Framework (https://slimframework.com)
- *
- * @link https://github.com/slimphp/Slim
- * @copyright Copyright (c) 2011-2017 Josh Lockhart
- * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
- */
-namespace Slim;
-
-use FastRoute\Dispatcher;
-use Psr\Container\ContainerInterface;
-use InvalidArgumentException;
-use RuntimeException;
-use Psr\Http\Message\ServerRequestInterface;
-use FastRoute\RouteCollector;
-use FastRoute\RouteParser;
-use FastRoute\RouteParser\Std as StdParser;
-use Slim\Interfaces\RouteGroupInterface;
-use Slim\Interfaces\RouterInterface;
-use Slim\Interfaces\RouteInterface;
-
-/**
- * Router
- *
- * This class organizes Slim application route objects. It is responsible
- * for registering route objects, assigning names to route objects,
- * finding routes that match the current HTTP request, and creating
- * URLs for a named route.
- */
-class Router implements RouterInterface
-{
- /**
- * Container Interface
- *
- * @var ContainerInterface
- */
- protected $container;
-
- /**
- * Parser
- *
- * @var \FastRoute\RouteParser
- */
- protected $routeParser;
-
- /**
- * Base path used in pathFor()
- *
- * @var string
- */
- protected $basePath = '';
-
- /**
- * Path to fast route cache file. Set to false to disable route caching
- *
- * @var string|False
- */
- protected $cacheFile = false;
-
- /**
- * Routes
- *
- * @var Route[]
- */
- protected $routes = [];
-
- /**
- * Route counter incrementer
- * @var int
- */
- protected $routeCounter = 0;
-
- /**
- * Route groups
- *
- * @var RouteGroup[]
- */
- protected $routeGroups = [];
-
- /**
- * @var \FastRoute\Dispatcher
- */
- protected $dispatcher;
-
- /**
- * Create new router
- *
- * @param RouteParser $parser
- */
- public function __construct(RouteParser $parser = null)
- {
- $this->routeParser = $parser ?: new StdParser;
- }
-
- /**
- * Set the base path used in pathFor()
- *
- * @param string $basePath
- *
- * @return self
- */
- public function setBasePath($basePath)
- {
- if (!is_string($basePath)) {
- throw new InvalidArgumentException('Router basePath must be a string');
- }
-
- $this->basePath = $basePath;
-
- return $this;
- }
-
- /**
- * Set path to fast route cache file. If this is false then route caching is disabled.
- *
- * @param string|false $cacheFile
- *
- * @return self
- */
- public function setCacheFile($cacheFile)
- {
- if (!is_string($cacheFile) && $cacheFile !== false) {
- throw new InvalidArgumentException('Router cacheFile must be a string or false');
- }
-
- $this->cacheFile = $cacheFile;
-
- if ($cacheFile !== false && !is_writable(dirname($cacheFile))) {
- throw new RuntimeException('Router cacheFile directory must be writable');
- }
-
-
- return $this;
- }
-
- /**
- * @param ContainerInterface $container
- */
- public function setContainer(ContainerInterface $container)
- {
- $this->container = $container;
- }
-
- /**
- * Add route
- *
- * @param string[] $methods Array of HTTP methods
- * @param string $pattern The route pattern
- * @param callable $handler The route callable
- *
- * @return RouteInterface
- *
- * @throws InvalidArgumentException if the route pattern isn't a string
- */
- public function map($methods, $pattern, $handler)
- {
- if (!is_string($pattern)) {
- throw new InvalidArgumentException('Route pattern must be a string');
- }
-
- // Prepend parent group pattern(s)
- if ($this->routeGroups) {
- $pattern = $this->processGroups() . $pattern;
- }
-
- // According to RFC methods are defined in uppercase (See RFC 7231)
- $methods = array_map("strtoupper", $methods);
-
- // Add route
- $route = $this->createRoute($methods, $pattern, $handler);
- $this->routes[$route->getIdentifier()] = $route;
- $this->routeCounter++;
-
- return $route;
- }
-
- /**
- * Dispatch router for HTTP request
- *
- * @param ServerRequestInterface $request The current HTTP request object
- *
- * @return array
- *
- * @link https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php
- */
- public function dispatch(ServerRequestInterface $request)
- {
- $uri = '/' . ltrim($request->getUri()->getPath(), '/');
-
- return $this->createDispatcher()->dispatch(
- $request->getMethod(),
- $uri
- );
- }
-
- /**
- * Create a new Route object
- *
- * @param string[] $methods Array of HTTP methods
- * @param string $pattern The route pattern
- * @param callable $callable The route callable
- *
- * @return \Slim\Interfaces\RouteInterface
- */
- protected function createRoute($methods, $pattern, $callable)
- {
- $route = new Route($methods, $pattern, $callable, $this->routeGroups, $this->routeCounter);
- if (!empty($this->container)) {
- $route->setContainer($this->container);
- }
-
- return $route;
- }
-
- /**
- * @return \FastRoute\Dispatcher
- */
- protected function createDispatcher()
- {
- if ($this->dispatcher) {
- return $this->dispatcher;
- }
-
- $routeDefinitionCallback = function (RouteCollector $r) {
- foreach ($this->getRoutes() as $route) {
- $r->addRoute($route->getMethods(), $route->getPattern(), $route->getIdentifier());
- }
- };
-
- if ($this->cacheFile) {
- $this->dispatcher = \FastRoute\cachedDispatcher($routeDefinitionCallback, [
- 'routeParser' => $this->routeParser,
- 'cacheFile' => $this->cacheFile,
- ]);
- } else {
- $this->dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback, [
- 'routeParser' => $this->routeParser,
- ]);
- }
-
- return $this->dispatcher;
- }
-
- /**
- * @param \FastRoute\Dispatcher $dispatcher
- */
- public function setDispatcher(Dispatcher $dispatcher)
- {
- $this->dispatcher = $dispatcher;
- }
-
- /**
- * Get route objects
- *
- * @return Route[]
- */
- public function getRoutes()
- {
- return $this->routes;
- }
-
- /**
- * Get named route object
- *
- * @param string $name Route name
- *
- * @return Route
- *
- * @throws RuntimeException If named route does not exist
- */
- public function getNamedRoute($name)
- {
- foreach ($this->routes as $route) {
- if ($name == $route->getName()) {
- return $route;
- }
- }
- throw new RuntimeException('Named route does not exist for name: ' . $name);
- }
-
- /**
- * Remove named route
- *
- * @param string $name Route name
- *
- * @throws RuntimeException If named route does not exist
- */
- public function removeNamedRoute($name)
- {
- $route = $this->getNamedRoute($name);
-
- // no exception, route exists, now remove by id
- unset($this->routes[$route->getIdentifier()]);
- }
-
- /**
- * Process route groups
- *
- * @return string A group pattern to prefix routes with
- */
- protected function processGroups()
- {
- $pattern = "";
- foreach ($this->routeGroups as $group) {
- $pattern .= $group->getPattern();
- }
- return $pattern;
- }
-
- /**
- * Add a route group to the array
- *
- * @param string $pattern
- * @param callable $callable
- *
- * @return RouteGroupInterface
- */
- public function pushGroup($pattern, $callable)
- {
- $group = new RouteGroup($pattern, $callable);
- array_push($this->routeGroups, $group);
- return $group;
- }
-
- /**
- * Removes the last route group from the array
- *
- * @return RouteGroup|bool The RouteGroup if successful, else False
- */
- public function popGroup()
- {
- $group = array_pop($this->routeGroups);
- return $group instanceof RouteGroup ? $group : false;
- }
-
- /**
- * @param $identifier
- * @return \Slim\Interfaces\RouteInterface
- */
- public function lookupRoute($identifier)
- {
- if (!isset($this->routes[$identifier])) {
- throw new RuntimeException('Route not found, looks like your route cache is stale.');
- }
- return $this->routes[$identifier];
- }
-
- /**
- * Build the path for a named route excluding the base path
- *
- * @param string $name Route name
- * @param array $data Named argument replacement data
- * @param array $queryParams Optional query string parameters
- *
- * @return string
- *
- * @throws RuntimeException If named route does not exist
- * @throws InvalidArgumentException If required data not provided
- */
- public function relativePathFor($name, array $data = [], array $queryParams = [])
- {
- $route = $this->getNamedRoute($name);
- $pattern = $route->getPattern();
-
- $routeDatas = $this->routeParser->parse($pattern);
- // $routeDatas is an array of all possible routes that can be made. There is
- // one routedata for each optional parameter plus one for no optional parameters.
- //
- // The most specific is last, so we look for that first.
- $routeDatas = array_reverse($routeDatas);
-
- $segments = [];
- foreach ($routeDatas as $routeData) {
- foreach ($routeData as $item) {
- if (is_string($item)) {
- // this segment is a static string
- $segments[] = $item;
- continue;
- }
-
- // This segment has a parameter: first element is the name
- if (!array_key_exists($item[0], $data)) {
- // we don't have a data element for this segment: cancel
- // testing this routeData item, so that we can try a less
- // specific routeData item.
- $segments = [];
- $segmentName = $item[0];
- break;
- }
- $segments[] = $data[$item[0]];
- }
- if (!empty($segments)) {
- // we found all the parameters for this route data, no need to check
- // less specific ones
- 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;
- }
-
-
- /**
- * Build the path for a named route including the base path
- *
- * @param string $name Route name
- * @param array $data Named argument replacement data
- * @param array $queryParams Optional query string parameters
- *
- * @return string
- *
- * @throws RuntimeException If named route does not exist
- * @throws InvalidArgumentException If required data not provided
- */
- public function pathFor($name, array $data = [], array $queryParams = [])
- {
- $url = $this->relativePathFor($name, $data, $queryParams);
-
- if ($this->basePath) {
- $url = $this->basePath . $url;
- }
-
- return $url;
- }
-
- /**
- * Build the path for a named route.
- *
- * This method is deprecated. Use pathFor() from now on.
- *
- * @param string $name Route name
- * @param array $data Named argument replacement data
- * @param array $queryParams Optional query string parameters
- *
- * @return string
- *
- * @throws RuntimeException If named route does not exist
- * @throws InvalidArgumentException If required data not provided
- */
- public function urlFor($name, array $data = [], array $queryParams = [])
- {
- trigger_error('urlFor() is deprecated. Use pathFor() instead.', E_USER_DEPRECATED);
- return $this->pathFor($name, $data, $queryParams);
- }
-}
--- /dev/null
+<?php
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use FastRoute\DataGenerator\GroupCountBased;
+use FastRoute\RouteCollector as FastRouteCollector;
+use FastRoute\RouteParser\Std;
+use Slim\Interfaces\DispatcherInterface;
+use Slim\Interfaces\RouteCollectorInterface;
+
+class Dispatcher implements DispatcherInterface
+{
+ private RouteCollectorInterface $routeCollector;
+
+ private ?FastRouteDispatcher $dispatcher = null;
+
+ public function __construct(RouteCollectorInterface $routeCollector)
+ {
+ $this->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);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use FastRoute\Dispatcher\GroupCountBased;
+
+class FastRouteDispatcher extends GroupCountBased
+{
+ /**
+ * @var string[][]
+ */
+ private array $allowedMethods = [];
+
+ /**
+ * @param string $httpMethod
+ * @param string $uri
+ *
+ * @return array{int, string|null, array<string, string>}
+ */
+ 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<string, string>}
+ */
+ 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<string, string>} $result */
+ $result = $this->dispatchVariableRoute($this->variableRouteData[$httpMethod], $uri);
+ if ($result[0] === self::FOUND) {
+ /** @var array{int, string, array<string, string>} $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);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use Psr\Container\ContainerInterface;
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use Slim\Handlers\Strategies\RequestHandler;
+use Slim\Handlers\Strategies\RequestResponse;
+use Slim\Interfaces\AdvancedCallableResolverInterface;
+use Slim\Interfaces\CallableResolverInterface;
+use Slim\Interfaces\InvocationStrategyInterface;
+use Slim\Interfaces\RequestHandlerInvocationStrategyInterface;
+use Slim\Interfaces\RouteGroupInterface;
+use Slim\Interfaces\RouteInterface;
+use Slim\MiddlewareDispatcher;
+
+use function array_key_exists;
+use function array_replace;
+use function array_reverse;
+use function class_implements;
+use function in_array;
+use function is_array;
+
+class Route implements RouteInterface, RequestHandlerInterface
+{
+ /**
+ * HTTP methods supported by this route
+ *
+ * @var string[]
+ */
+ protected array $methods = [];
+
+ /**
+ * Route identifier
+ */
+ protected string $identifier;
+
+ /**
+ * Route name
+ */
+ protected ?string $name = null;
+
+ /**
+ * Parent route groups
+ *
+ * @var RouteGroupInterface[]
+ */
+ protected array $groups;
+
+ protected InvocationStrategyInterface $invocationStrategy;
+
+ /**
+ * Route parameters
+ *
+ * @var array<string, string>
+ */
+ protected array $arguments = [];
+
+ /**
+ * Route arguments parameters
+ *
+ * @var string[]
+ */
+ protected array $savedArguments = [];
+
+ /**
+ * Container
+ */
+ protected ?ContainerInterface $container = null;
+
+ 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 ContainerInterface|null $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);
+
+ /** @var RouteGroupInterface $group */
+ 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);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use Psr\Container\ContainerInterface;
+use Psr\Http\Message\ResponseFactoryInterface;
+use RuntimeException;
+use Slim\Handlers\Strategies\RequestResponse;
+use Slim\Interfaces\CallableResolverInterface;
+use Slim\Interfaces\InvocationStrategyInterface;
+use Slim\Interfaces\RouteCollectorInterface;
+use Slim\Interfaces\RouteCollectorProxyInterface;
+use Slim\Interfaces\RouteGroupInterface;
+use Slim\Interfaces\RouteInterface;
+use Slim\Interfaces\RouteParserInterface;
+
+use function array_pop;
+use function dirname;
+use function file_exists;
+use function sprintf;
+use function is_readable;
+use function is_writable;
+
+/**
+ * RouteCollector is used to collect routes and route groups
+ * as well as generate paths and URLs relative to its environment
+ */
+class RouteCollector implements RouteCollectorInterface
+{
+ protected RouteParserInterface $routeParser;
+
+ protected CallableResolverInterface $callableResolver;
+
+ protected ?ContainerInterface $container = null;
+
+ protected InvocationStrategyInterface $defaultInvocationStrategy;
+
+ /**
+ * Base path used in pathFor()
+ */
+ protected string $basePath = '';
+
+ /**
+ * Path to fast route cache file. Set to null to disable route caching
+ */
+ protected ?string $cacheFile = null;
+
+ /**
+ * Routes
+ *
+ * @var RouteInterface[]
+ */
+ protected array $routes = [];
+
+ /**
+ * Routes indexed by name
+ *
+ * @var RouteInterface[]
+ */
+ protected array $routesByName = [];
+
+ /**
+ * Route groups
+ *
+ * @var RouteGroupInterface[]
+ */
+ protected array $routeGroups = [];
+
+ /**
+ * Route counter incrementer
+ */
+ protected int $routeCounter = 0;
+
+ protected ResponseFactoryInterface $responseFactory;
+
+ public function __construct(
+ ResponseFactoryInterface $responseFactory,
+ CallableResolverInterface $callableResolver,
+ ?ContainerInterface $container = null,
+ ?InvocationStrategyInterface $defaultInvocationStrategy = null,
+ ?RouteParserInterface $routeParser = null,
+ ?string $cacheFile = null
+ ) {
+ $this->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);
+
+ 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);
+ }
+
+ protected function createProxy(string $pattern): 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
+ );
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use Psr\Container\ContainerInterface;
+use Psr\Http\Message\ResponseFactoryInterface;
+use Slim\Interfaces\CallableResolverInterface;
+use Slim\Interfaces\RouteCollectorInterface;
+use Slim\Interfaces\RouteCollectorProxyInterface;
+use Slim\Interfaces\RouteGroupInterface;
+use Slim\Interfaces\RouteInterface;
+
+class RouteCollectorProxy implements RouteCollectorProxyInterface
+{
+ protected ResponseFactoryInterface $responseFactory;
+
+ protected CallableResolverInterface $callableResolver;
+
+ protected ?ContainerInterface $container = null;
+
+ protected RouteCollectorInterface $routeCollector;
+
+ protected string $groupPattern;
+
+ 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}
+ */
+ 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);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use Psr\Http\Message\ServerRequestInterface;
+use RuntimeException;
+use Slim\Interfaces\RouteInterface;
+use Slim\Interfaces\RouteParserInterface;
+
+final class RouteContext
+{
+ public const ROUTE = '__route__';
+
+ public const ROUTE_PARSER = '__routeParser__';
+
+ public const ROUTING_RESULTS = '__routingResults__';
+
+ public const BASE_PATH = '__basePath__';
+
+ public static function fromRequest(ServerRequestInterface $serverRequest): self
+ {
+ $route = $serverRequest->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;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use Psr\Http\Server\MiddlewareInterface;
+use Slim\Interfaces\AdvancedCallableResolverInterface;
+use Slim\Interfaces\CallableResolverInterface;
+use Slim\Interfaces\RouteCollectorProxyInterface;
+use Slim\Interfaces\RouteGroupInterface;
+use Slim\MiddlewareDispatcher;
+
+class RouteGroup implements RouteGroupInterface
+{
+ /**
+ * @var callable|string
+ */
+ protected $callable;
+
+ protected CallableResolverInterface $callableResolver;
+
+ protected RouteCollectorProxyInterface $routeCollectorProxy;
+
+ /**
+ * @var MiddlewareInterface[]|string[]|callable[]
+ */
+ protected array $middleware = [];
+
+ protected string $pattern;
+
+ /**
+ * @param callable|string $callable
+ */
+ 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}
+ */
+ public function appendMiddlewareToDispatcher(MiddlewareDispatcher $dispatcher): RouteGroupInterface
+ {
+ foreach ($this->middleware as $middleware) {
+ $dispatcher->add($middleware);
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getPattern(): string
+ {
+ return $this->pattern;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use FastRoute\RouteParser\Std;
+use InvalidArgumentException;
+use Psr\Http\Message\UriInterface;
+use Slim\Interfaces\RouteCollectorInterface;
+use Slim\Interfaces\RouteParserInterface;
+
+use function array_key_exists;
+use function array_reverse;
+use function http_build_query;
+use function implode;
+use function is_string;
+
+class RouteParser implements RouteParserInterface
+{
+ private RouteCollectorInterface $routeCollector;
+
+ private Std $routeParser;
+
+ public function __construct(RouteCollectorInterface $routeCollector)
+ {
+ $this->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;
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use RuntimeException;
+use Slim\Interfaces\DispatcherInterface;
+use Slim\Interfaces\RouteCollectorInterface;
+use Slim\Interfaces\RouteInterface;
+use Slim\Interfaces\RouteResolverInterface;
+
+use function rawurldecode;
+
+/**
+ * RouteResolver instantiates the FastRoute dispatcher
+ * and computes the routing results of a given URI and request method
+ */
+class RouteResolver implements RouteResolverInterface
+{
+ protected RouteCollectorInterface $routeCollector;
+
+ private DispatcherInterface $dispatcher;
+
+ public function __construct(RouteCollectorInterface $routeCollector, ?DispatcherInterface $dispatcher = null)
+ {
+ $this->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);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use Slim\Exception\HttpMethodNotAllowedException;
+use Slim\Exception\HttpNotFoundException;
+use Slim\Interfaces\RouteCollectorProxyInterface;
+use Slim\Interfaces\RouteParserInterface;
+use Slim\Interfaces\RouteResolverInterface;
+use Slim\Middleware\RoutingMiddleware;
+
+class RouteRunner implements RequestHandlerInterface
+{
+ private RouteResolverInterface $routeResolver;
+
+ private RouteParserInterface $routeParser;
+
+ private ?RouteCollectorProxyInterface $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 $route */
+ $route = $request->getAttribute(RouteContext::ROUTE);
+ return $route->run($request);
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Slim Framework (https://slimframework.com)
+ *
+ * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
+ */
+
+declare(strict_types=1);
+
+namespace Slim\Routing;
+
+use Slim\Interfaces\DispatcherInterface;
+
+use function rawurldecode;
+
+class RoutingResults
+{
+ public const NOT_FOUND = 0;
+ public const FOUND = 1;
+ public const METHOD_NOT_ALLOWED = 2;
+
+ protected DispatcherInterface $dispatcher;
+
+ protected string $method;
+
+ protected string $uri;
+
+ /**
+ * The status is one of the constants shown above
+ * NOT_FOUND = 0
+ * FOUND = 1
+ * METHOD_NOT_ALLOWED = 2
+ */
+ protected int $routeStatus;
+
+ protected ?string $routeIdentifier = null;
+
+ /**
+ * @var array<string, string>
+ */
+ protected array $routeArguments;
+
+ /**
+ * @param array<string, string> $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<string, string>
+ */
+ 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);
+ }
+}
"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://slimframework.com",
+ "homepage": "https://www.slimframework.com",
"license": "MIT",
"authors": [
{
"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": ">=5.5.0",
- "pimple/pimple": "^3.0",
- "psr/http-message": "^1.0",
- "nikic/fast-route": "^1.0",
- "container-interop/container-interop": "^1.2",
- "psr/container": "^1.0"
+ "php": "^7.4 || ^8.0",
+ "ext-json": "*",
+ "nikic/fast-route": "^1.3",
+ "psr/container": "^1.0 || ^2.0",
+ "psr/http-factory": "^1.0",
+ "psr/http-message": "^1.1",
+ "psr/http-server-handler": "^1.0",
+ "psr/http-server-middleware": "^1.0",
+ "psr/log": "^1.1 || ^2.0 || ^3.0"
},
"require-dev": {
- "squizlabs/php_codesniffer": "^2.5",
- "phpunit/phpunit": "^4.0"
- },
- "provide": {
- "psr/http-message-implementation": "1.0"
+ "ext-simplexml": "*",
+ "adriansuter/php-autoload-override": "^1.4",
+ "guzzlehttp/psr7": "^2.5",
+ "httpsoft/http-message": "^1.1",
+ "httpsoft/http-server-request": "^1.1",
+ "laminas/laminas-diactoros": "^2.17",
+ "nyholm/psr7": "^1.8",
+ "nyholm/psr7-server": "^1.0",
+ "phpspec/prophecy": "^1.17",
+ "phpspec/prophecy-phpunit": "^2.0",
+ "phpstan/phpstan": "^1.10",
+ "phpunit/phpunit": "^9.6",
+ "slim/http": "^1.3",
+ "slim/psr7": "^1.6",
+ "squizlabs/php_codesniffer": "^3.7"
},
"autoload": {
"psr-4": {
"Slim\\": "Slim"
}
},
+ "autoload-dev": {
+ "psr-4": {
+ "Slim\\Tests\\": "tests"
+ }
+ },
"scripts": {
"test": [
"@phpunit",
- "@phpcs"
+ "@phpcs",
+ "@phpstan"
],
- "phpunit": "php vendor/bin/phpunit",
- "phpcs": "php vendor/bin/phpcs"
+ "phpunit": "phpunit",
+ "phpcs": "phpcs",
+ "phpstan": "phpstan --memory-limit=-1"
+ },
+ "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
}
}
use Psr\Cache\CacheItemInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
-use Psr\Log\NullLogger;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\ResettableInterface;
*/
abstract class AbstractAdapter implements AdapterInterface, LoggerAwareInterface, ResettableInterface
{
+ /**
+ * @internal
+ */
+ const NS_SEPARATOR = ':';
+
use AbstractTrait;
private static $apcuSupported;
*/
protected function __construct($namespace = '', $defaultLifetime = 0)
{
- $this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).':';
- if (null !== $this->maxIdLength && strlen($namespace) > $this->maxIdLength - 24) {
- throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s")', $this->maxIdLength - 24, strlen($namespace), $namespace));
+ $this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).static::NS_SEPARATOR;
+ if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
+ throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
}
$this->createCacheItem = \Closure::bind(
- function ($key, $value, $isHit) use ($defaultLifetime) {
+ static function ($key, $value, $isHit) {
$item = new CacheItem();
$item->key = $key;
$item->value = $value;
$item->isHit = $isHit;
- $item->defaultLifetime = $defaultLifetime;
return $item;
},
);
$getId = function ($key) { return $this->getId((string) $key); };
$this->mergeByLifetime = \Closure::bind(
- function ($deferred, $namespace, &$expiredIds) use ($getId) {
- $byLifetime = array();
+ static function ($deferred, $namespace, &$expiredIds) use ($getId, $defaultLifetime) {
+ $byLifetime = [];
$now = time();
- $expiredIds = array();
+ $expiredIds = [];
foreach ($deferred as $key => $item) {
if (null === $item->expiry) {
- $byLifetime[0 < $item->defaultLifetime ? $item->defaultLifetime : 0][$getId($key)] = $item->value;
+ $byLifetime[0 < $defaultLifetime ? $defaultLifetime : 0][$getId($key)] = $item->value;
+ } elseif (0 === $item->expiry) {
+ $byLifetime[0][$getId($key)] = $item->value;
} elseif ($item->expiry > $now) {
$byLifetime[$item->expiry - $now][$getId($key)] = $item->value;
} else {
}
/**
- * @param string $namespace
- * @param int $defaultLifetime
- * @param string $version
- * @param string $directory
- * @param LoggerInterface|null $logger
+ * @param string $namespace
+ * @param int $defaultLifetime
+ * @param string $version
+ * @param string $directory
*
* @return AdapterInterface
*/
if (null !== $logger) {
$fs->setLogger($logger);
}
- if (!self::$apcuSupported) {
+ if (!self::$apcuSupported || (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN))) {
return $fs;
}
$apcu = new ApcuAdapter($namespace, (int) $defaultLifetime / 5, $version);
- if ('cli' === \PHP_SAPI && !ini_get('apc.enable_cli')) {
- $apcu->setLogger(new NullLogger());
- } elseif (null !== $logger) {
+ if (null !== $logger) {
$apcu->setLogger($logger);
}
- return new ChainAdapter(array($apcu, $fs));
+ return new ChainAdapter([$apcu, $fs]);
}
- public static function createConnection($dsn, array $options = array())
+ public static function createConnection($dsn, array $options = [])
{
- if (!is_string($dsn)) {
- throw new InvalidArgumentException(sprintf('The %s() method expect argument #1 to be string, %s given.', __METHOD__, gettype($dsn)));
+ if (!\is_string($dsn)) {
+ throw new InvalidArgumentException(sprintf('The "%s()" method expect argument #1 to be string, "%s" given.', __METHOD__, \gettype($dsn)));
}
if (0 === strpos($dsn, 'redis://')) {
return RedisAdapter::createConnection($dsn, $options);
return MemcachedAdapter::createConnection($dsn, $options);
}
- throw new InvalidArgumentException(sprintf('Unsupported DSN: %s.', $dsn));
+ throw new InvalidArgumentException(sprintf('Unsupported DSN: "%s".', $dsn));
}
/**
$value = null;
try {
- foreach ($this->doFetch(array($id)) as $value) {
+ foreach ($this->doFetch([$id]) as $value) {
$isHit = true;
}
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to fetch key "{key}"', array('key' => $key, 'exception' => $e));
+ CacheItem::log($this->logger, 'Failed to fetch key "{key}"', ['key' => $key, 'exception' => $e]);
}
return $f($key, $value, $isHit);
/**
* {@inheritdoc}
*/
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
if ($this->deferred) {
$this->commit();
}
- $ids = array();
+ $ids = [];
foreach ($keys as $key) {
$ids[] = $this->getId($key);
try {
$items = $this->doFetch($ids);
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to fetch requested items', array('keys' => $keys, 'exception' => $e));
- $items = array();
+ CacheItem::log($this->logger, 'Failed to fetch requested items', ['keys' => $keys, 'exception' => $e]);
+ $items = [];
}
$ids = array_combine($ids, $keys);
$ok = true;
$byLifetime = $this->mergeByLifetime;
$byLifetime = $byLifetime($this->deferred, $this->namespace, $expiredIds);
- $retry = $this->deferred = array();
+ $retry = $this->deferred = [];
if ($expiredIds) {
$this->doDelete($expiredIds);
$e = $this->doSave($values, $lifetime);
} catch (\Exception $e) {
}
- if (true === $e || array() === $e) {
+ if (true === $e || [] === $e) {
continue;
}
- if (is_array($e) || 1 === count($values)) {
- foreach (is_array($e) ? $e : array_keys($values) as $id) {
+ if (\is_array($e) || 1 === \count($values)) {
+ foreach (\is_array($e) ? $e : array_keys($values) as $id) {
$ok = false;
$v = $values[$id];
- $type = is_object($v) ? get_class($v) : gettype($v);
- CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => substr($id, strlen($this->namespace)), 'type' => $type, 'exception' => $e instanceof \Exception ? $e : null));
+ $type = \is_object($v) ? \get_class($v) : \gettype($v);
+ CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', ['key' => substr($id, \strlen($this->namespace)), 'type' => $type, 'exception' => $e instanceof \Exception ? $e : null]);
}
} else {
foreach ($values as $id => $v) {
foreach ($ids as $id) {
try {
$v = $byLifetime[$lifetime][$id];
- $e = $this->doSave(array($id => $v), $lifetime);
+ $e = $this->doSave([$id => $v], $lifetime);
} catch (\Exception $e) {
}
- if (true === $e || array() === $e) {
+ if (true === $e || [] === $e) {
continue;
}
$ok = false;
- $type = is_object($v) ? get_class($v) : gettype($v);
- CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => substr($id, strlen($this->namespace)), 'type' => $type, 'exception' => $e instanceof \Exception ? $e : null));
+ $type = \is_object($v) ? \get_class($v) : \gettype($v);
+ CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', ['key' => substr($id, \strlen($this->namespace)), 'type' => $type, 'exception' => $e instanceof \Exception ? $e : null]);
}
}
return $ok;
}
+ public function __sleep()
+ {
+ throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
+ }
+
+ public function __wakeup()
+ {
+ throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
+ }
+
public function __destruct()
{
if ($this->deferred) {
yield $key => $f($key, $value, true);
}
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to fetch requested items', array('keys' => array_values($keys), 'exception' => $e));
+ CacheItem::log($this->logger, 'Failed to fetch requested items', ['keys' => array_values($keys), 'exception' => $e]);
}
foreach ($keys as $key) {
*
* @return \Traversable|CacheItem[]
*/
- public function getItems(array $keys = array());
+ public function getItems(array $keys = []);
}
use ArrayTrait;
private $createCacheItem;
+ private $defaultLifetime;
/**
* @param int $defaultLifetime
*/
public function __construct($defaultLifetime = 0, $storeSerialized = true)
{
+ $this->defaultLifetime = $defaultLifetime;
$this->storeSerialized = $storeSerialized;
$this->createCacheItem = \Closure::bind(
- function ($key, $value, $isHit) use ($defaultLifetime) {
+ static function ($key, $value, $isHit) {
$item = new CacheItem();
$item->key = $key;
$item->value = $value;
$item->isHit = $isHit;
- $item->defaultLifetime = $defaultLifetime;
return $item;
},
$isHit = false;
}
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to unserialize key "{key}"', array('key' => $key, 'exception' => $e));
+ CacheItem::log($this->logger, 'Failed to unserialize key "{key}"', ['key' => $key, 'exception' => $e]);
$this->values[$key] = $value = null;
$isHit = false;
}
/**
* {@inheritdoc}
*/
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
foreach ($keys as $key) {
CacheItem::validateKey($key);
$value = $item["\0*\0value"];
$expiry = $item["\0*\0expiry"];
+ if (0 === $expiry) {
+ $expiry = \PHP_INT_MAX;
+ }
+
if (null !== $expiry && $expiry <= time()) {
$this->deleteItem($key);
try {
$value = serialize($value);
} catch (\Exception $e) {
- $type = is_object($value) ? get_class($value) : gettype($value);
- CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => $key, 'type' => $type, 'exception' => $e));
+ $type = \is_object($value) ? \get_class($value) : \gettype($value);
+ CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', ['key' => $key, 'type' => $type, 'exception' => $e]);
return false;
}
}
- if (null === $expiry && 0 < $item["\0*\0defaultLifetime"]) {
- $expiry = time() + $item["\0*\0defaultLifetime"];
+ if (null === $expiry && 0 < $this->defaultLifetime) {
+ $expiry = time() + $this->defaultLifetime;
}
$this->values[$key] = $value;
- $this->expiries[$key] = null !== $expiry ? $expiry : PHP_INT_MAX;
+ $this->expiries[$key] = null !== $expiry ? $expiry : \PHP_INT_MAX;
return true;
}
*/
class ChainAdapter implements AdapterInterface, PruneableInterface, ResettableInterface
{
- private $adapters = array();
+ private $adapters = [];
private $adapterCount;
- private $saveUp;
+ private $syncItem;
/**
- * @param CacheItemPoolInterface[] $adapters The ordered list of adapters used to fetch cached items
- * @param int $maxLifetime The max lifetime of items propagated from lower adapters to upper ones
+ * @param CacheItemPoolInterface[] $adapters The ordered list of adapters used to fetch cached items
+ * @param int $defaultLifetime The default lifetime of items propagated from lower adapters to upper ones
*/
- public function __construct(array $adapters, $maxLifetime = 0)
+ public function __construct(array $adapters, $defaultLifetime = 0)
{
if (!$adapters) {
throw new InvalidArgumentException('At least one adapter must be specified.');
foreach ($adapters as $adapter) {
if (!$adapter instanceof CacheItemPoolInterface) {
- throw new InvalidArgumentException(sprintf('The class "%s" does not implement the "%s" interface.', get_class($adapter), CacheItemPoolInterface::class));
+ throw new InvalidArgumentException(sprintf('The class "%s" does not implement the "%s" interface.', \get_class($adapter), CacheItemPoolInterface::class));
+ }
+ if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && $adapter instanceof ApcuAdapter && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) {
+ continue; // skip putting APCu in the chain when the backend is disabled
}
if ($adapter instanceof AdapterInterface) {
$this->adapters[] = new ProxyAdapter($adapter);
}
}
- $this->adapterCount = count($this->adapters);
+ $this->adapterCount = \count($this->adapters);
- $this->saveUp = \Closure::bind(
- function ($adapter, $item) use ($maxLifetime) {
- $origDefaultLifetime = $item->defaultLifetime;
+ $this->syncItem = \Closure::bind(
+ static function ($sourceItem, $item) use ($defaultLifetime) {
+ $item->value = $sourceItem->value;
+ $item->isHit = $sourceItem->isHit;
- if (0 < $maxLifetime && ($origDefaultLifetime <= 0 || $maxLifetime < $origDefaultLifetime)) {
- $item->defaultLifetime = $maxLifetime;
+ if (0 < $defaultLifetime) {
+ $item->expiresAfter($defaultLifetime);
}
- $adapter->save($item);
- $item->defaultLifetime = $origDefaultLifetime;
+ return $item;
},
null,
CacheItem::class
*/
public function getItem($key)
{
- $saveUp = $this->saveUp;
+ $syncItem = $this->syncItem;
+ $misses = [];
foreach ($this->adapters as $i => $adapter) {
$item = $adapter->getItem($key);
if ($item->isHit()) {
while (0 <= --$i) {
- $saveUp($this->adapters[$i], $item);
+ $this->adapters[$i]->save($syncItem($item, $misses[$i]));
}
return $item;
}
+
+ $misses[$i] = $item;
}
return $item;
/**
* {@inheritdoc}
*/
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
return $this->generateItems($this->adapters[0]->getItems($keys), 0);
}
private function generateItems($items, $adapterIndex)
{
- $missing = array();
+ $missing = [];
+ $misses = [];
$nextAdapterIndex = $adapterIndex + 1;
$nextAdapter = isset($this->adapters[$nextAdapterIndex]) ? $this->adapters[$nextAdapterIndex] : null;
yield $k => $item;
} else {
$missing[] = $k;
+ $misses[$k] = $item;
}
}
if ($missing) {
- $saveUp = $this->saveUp;
+ $syncItem = $this->syncItem;
$adapter = $this->adapters[$adapterIndex];
$items = $this->generateItems($nextAdapter->getItems($missing), $nextAdapterIndex);
foreach ($items as $k => $item) {
if ($item->isHit()) {
- $saveUp($adapter, $item);
+ $adapter->save($syncItem($item, $misses[$k]));
}
yield $k => $item;
use DoctrineTrait;
/**
- * @param CacheProvider $provider
- * @param string $namespace
- * @param int $defaultLifetime
+ * @param string $namespace
+ * @param int $defaultLifetime
*/
public function __construct(CacheProvider $provider, $namespace = '', $defaultLifetime = 0)
{
/**
* {@inheritdoc}
*/
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
return $this->generateItems($keys);
}
* * db_time_col: The column where to store the timestamp [default: item_time]
* * db_username: The username when lazy-connect [default: '']
* * db_password: The password when lazy-connect [default: '']
- * * db_connection_options: An array of driver-specific connection options [default: array()]
+ * * db_connection_options: An array of driver-specific connection options [default: []]
*
* @param \PDO|Connection|string $connOrDsn A \PDO or Connection instance or DSN string or null
* @param string $namespace
* @throws InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
* @throws InvalidArgumentException When namespace contains invalid characters
*/
- public function __construct($connOrDsn, $namespace = '', $defaultLifetime = 0, array $options = array())
+ public function __construct($connOrDsn, $namespace = '', $defaultLifetime = 0, array $options = [])
{
$this->init($connOrDsn, $namespace, $defaultLifetime, $options);
}
{
$this->file = $file;
$this->pool = $fallbackPool;
- $this->zendDetectUnicode = ini_get('zend.detect_unicode');
+ $this->zendDetectUnicode = filter_var(ini_get('zend.detect_unicode'), \FILTER_VALIDATE_BOOLEAN);
$this->createCacheItem = \Closure::bind(
- function ($key, $value, $isHit) {
+ static function ($key, $value, $isHit) {
$item = new CacheItem();
$item->key = $key;
$item->value = $value;
* fallback pool with this adapter only if the current PHP version is supported.
*
* @param string $file The PHP file were values are cached
- * @param CacheItemPoolInterface $fallbackPool Fallback for old PHP versions or opcache disabled
+ * @param CacheItemPoolInterface $fallbackPool A pool to fallback on when an item is not hit
*
* @return CacheItemPoolInterface
*/
public static function create($file, CacheItemPoolInterface $fallbackPool)
{
- // Shared memory is available in PHP 7.0+ with OPCache enabled and in HHVM
- if ((\PHP_VERSION_ID >= 70000 && ini_get('opcache.enable')) || defined('HHVM_VERSION')) {
+ if (\PHP_VERSION_ID >= 70000) {
if (!$fallbackPool instanceof AdapterInterface) {
$fallbackPool = new ProxyAdapter($fallbackPool);
}
*/
public function getItem($key)
{
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
if ('N;' === $value) {
$value = null;
- } elseif (is_string($value) && isset($value[2]) && ':' === $value[1]) {
+ } elseif (\is_string($value) && isset($value[2]) && ':' === $value[1]) {
try {
$e = null;
$value = unserialize($value);
/**
* {@inheritdoc}
*/
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
foreach ($keys as $key) {
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
}
if (null === $this->values) {
*/
public function hasItem($key)
{
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
*/
public function deleteItem($key)
{
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
public function deleteItems(array $keys)
{
$deleted = true;
- $fallbackKeys = array();
+ $fallbackKeys = [];
foreach ($keys as $key) {
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (isset($this->values[$key])) {
private function generateItems(array $keys)
{
$f = $this->createCacheItem;
- $fallbackKeys = array();
+ $fallbackKeys = [];
foreach ($keys as $key) {
if (isset($this->values[$key])) {
if ('N;' === $value) {
yield $key => $f($key, null, true);
- } elseif (is_string($value) && isset($value[2]) && ':' === $value[1]) {
+ } elseif (\is_string($value) && isset($value[2]) && ':' === $value[1]) {
try {
yield $key => $f($key, unserialize($value), true);
} catch (\Error $e) {
/**
* @throws \ReflectionException When $class is not found and is required
*
- * @internal
+ * @internal to be removed in Symfony 5.0
*/
public static function throwOnRequiredClass($class)
{
$e = new \ReflectionException("Class $class does not exist");
- $trace = $e->getTrace();
- $autoloadFrame = array(
+ $trace = debug_backtrace();
+ $autoloadFrame = [
'function' => 'spl_autoload_call',
- 'args' => array($class),
- );
- $i = 1 + array_search($autoloadFrame, $trace, true);
+ 'args' => [$class],
+ ];
+
+ if (\PHP_VERSION_ID >= 80000 && isset($trace[1])) {
+ $callerFrame = $trace[1];
+ } elseif (false !== $i = array_search($autoloadFrame, $trace, true)) {
+ $callerFrame = $trace[++$i];
+ } else {
+ throw $e;
+ }
- if (isset($trace[$i]['function']) && !isset($trace[$i]['class'])) {
- switch ($trace[$i]['function']) {
+ if (isset($callerFrame['function']) && !isset($callerFrame['class'])) {
+ switch ($callerFrame['function']) {
case 'get_class_methods':
case 'get_class_vars':
case 'get_parent_class':
public function __construct($namespace = '', $defaultLifetime = 0, $directory = null)
{
if (!static::isSupported()) {
- throw new CacheException('OPcache is not enabled');
+ throw new CacheException('OPcache is not enabled.');
}
parent::__construct('', $defaultLifetime);
$this->init($namespace, $directory);
$e = new \Exception();
$this->includeHandler = function () use ($e) { throw $e; };
- $this->zendDetectUnicode = ini_get('zend.detect_unicode');
+ $this->zendDetectUnicode = filter_var(ini_get('zend.detect_unicode'), \FILTER_VALIDATE_BOOLEAN);
}
}
private $namespaceLen;
private $createCacheItem;
private $poolHash;
+ private $defaultLifetime;
/**
- * @param CacheItemPoolInterface $pool
- * @param string $namespace
- * @param int $defaultLifetime
+ * @param string $namespace
+ * @param int $defaultLifetime
*/
public function __construct(CacheItemPoolInterface $pool, $namespace = '', $defaultLifetime = 0)
{
$this->pool = $pool;
$this->poolHash = $poolHash = spl_object_hash($pool);
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace);
- $this->namespaceLen = strlen($namespace);
+ $this->namespaceLen = \strlen($namespace);
+ $this->defaultLifetime = $defaultLifetime;
$this->createCacheItem = \Closure::bind(
- function ($key, $innerItem) use ($defaultLifetime, $poolHash) {
+ static function ($key, $innerItem) use ($poolHash) {
$item = new CacheItem();
$item->key = $key;
- $item->value = $innerItem->get();
- $item->isHit = $innerItem->isHit();
- $item->defaultLifetime = $defaultLifetime;
- $item->innerItem = $innerItem;
$item->poolHash = $poolHash;
- $innerItem->set(null);
+
+ if (null !== $innerItem) {
+ $item->value = $innerItem->get();
+ $item->isHit = $innerItem->isHit();
+ $item->innerItem = $innerItem;
+ $innerItem->set(null);
+ }
return $item;
},
/**
* {@inheritdoc}
*/
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
if ($this->namespaceLen) {
foreach ($keys as $i => $key) {
}
$item = (array) $item;
$expiry = $item["\0*\0expiry"];
- if (null === $expiry && 0 < $item["\0*\0defaultLifetime"]) {
- $expiry = time() + $item["\0*\0defaultLifetime"];
+ if (null === $expiry && 0 < $this->defaultLifetime) {
+ $expiry = time() + $this->defaultLifetime;
+ }
+
+ if ($item["\0*\0poolHash"] === $this->poolHash && $item["\0*\0innerItem"]) {
+ $innerItem = $item["\0*\0innerItem"];
+ } elseif ($this->pool instanceof AdapterInterface) {
+ // this is an optimization specific for AdapterInterface implementations
+ // so we can save a round-trip to the backend by just creating a new item
+ $f = $this->createCacheItem;
+ $innerItem = $f($this->namespace.$item["\0*\0key"], null);
+ } else {
+ $innerItem = $this->pool->getItem($this->namespace.$item["\0*\0key"]);
}
- $innerItem = $item["\0*\0poolHash"] === $this->poolHash ? $item["\0*\0innerItem"] : $this->pool->getItem($this->namespace.$item["\0*\0key"]);
+
$innerItem->set($item["\0*\0value"]);
$innerItem->expiresAt(null !== $expiry ? \DateTime::createFromFormat('U', $expiry) : null);
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\PruneableInterface;
-use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Cache\Traits\ProxyTrait;
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
-class SimpleCacheAdapter extends AbstractAdapter implements PruneableInterface, ResettableInterface
+class SimpleCacheAdapter extends AbstractAdapter implements PruneableInterface
{
+ /**
+ * @internal
+ */
+ const NS_SEPARATOR = '_';
+
use ProxyTrait;
private $miss;
use ProxyTrait;
- private $deferred = array();
+ private $deferred = [];
private $createCacheItem;
private $setCacheItemTags;
private $getTagsByKey;
private $invalidateTags;
private $tags;
+ private $knownTagVersions = [];
+ private $knownTagVersionsTtl;
- public function __construct(AdapterInterface $itemsPool, AdapterInterface $tagsPool = null)
+ public function __construct(AdapterInterface $itemsPool, AdapterInterface $tagsPool = null, $knownTagVersionsTtl = 0.15)
{
$this->pool = $itemsPool;
$this->tags = $tagsPool ?: $itemsPool;
+ $this->knownTagVersionsTtl = $knownTagVersionsTtl;
$this->createCacheItem = \Closure::bind(
- function ($key, $value, CacheItem $protoItem) {
+ static function ($key, $value, CacheItem $protoItem) {
$item = new CacheItem();
$item->key = $key;
$item->value = $value;
- $item->defaultLifetime = $protoItem->defaultLifetime;
$item->expiry = $protoItem->expiry;
- $item->innerItem = $protoItem->innerItem;
$item->poolHash = $protoItem->poolHash;
return $item;
CacheItem::class
);
$this->setCacheItemTags = \Closure::bind(
- function (CacheItem $item, $key, array &$itemTags) {
+ static function (CacheItem $item, $key, array &$itemTags) {
if (!$item->isHit) {
return $item;
}
CacheItem::class
);
$this->getTagsByKey = \Closure::bind(
- function ($deferred) {
- $tagsByKey = array();
+ static function ($deferred) {
+ $tagsByKey = [];
foreach ($deferred as $key => $item) {
$tagsByKey[$key] = $item->tags;
}
CacheItem::class
);
$this->invalidateTags = \Closure::bind(
- function (AdapterInterface $tagsAdapter, array $tags) {
- foreach ($tagsAdapter->getItems($tags) as $v) {
- $v->set(1 + (int) $v->get());
- $v->defaultLifetime = 0;
- $v->expiry = null;
+ static function (AdapterInterface $tagsAdapter, array $tags) {
+ foreach ($tags as $v) {
+ $v->expiry = 0;
$tagsAdapter->saveDeferred($v);
}
*/
public function invalidateTags(array $tags)
{
- foreach ($tags as $k => $tag) {
- if ('' !== $tag && is_string($tag)) {
- $tags[$k] = $tag.static::TAGS_PREFIX;
+ $ok = true;
+ $tagsByKey = [];
+ $invalidatedTags = [];
+ foreach ($tags as $tag) {
+ CacheItem::validateKey($tag);
+ $invalidatedTags[$tag] = 0;
+ }
+
+ if ($this->deferred) {
+ $items = $this->deferred;
+ foreach ($items as $key => $item) {
+ if (!$this->pool->saveDeferred($item)) {
+ unset($this->deferred[$key]);
+ $ok = false;
+ }
}
+
+ $f = $this->getTagsByKey;
+ $tagsByKey = $f($items);
+ $this->deferred = [];
}
- $f = $this->invalidateTags;
- return $f($this->tags, $tags);
+ $tagVersions = $this->getTagVersions($tagsByKey, $invalidatedTags);
+ $f = $this->createCacheItem;
+
+ foreach ($tagsByKey as $key => $tags) {
+ $this->pool->saveDeferred($f(static::TAGS_PREFIX.$key, array_intersect_key($tagVersions, $tags), $items[$key]));
+ }
+ $ok = $this->pool->commit() && $ok;
+
+ if ($invalidatedTags) {
+ $f = $this->invalidateTags;
+ $ok = $f($this->tags, $invalidatedTags) && $ok;
+ }
+
+ return $ok;
}
/**
if (!$this->pool->hasItem($key)) {
return false;
}
- if (!$itemTags = $this->pool->getItem(static::TAGS_PREFIX.$key)->get()) {
+
+ $itemTags = $this->pool->getItem(static::TAGS_PREFIX.$key);
+
+ if (!$itemTags->isHit()) {
+ return false;
+ }
+
+ if (!$itemTags = $itemTags->get()) {
return true;
}
- foreach ($this->getTagVersions(array($itemTags)) as $tag => $version) {
- if ($itemTags[$tag] !== $version) {
+ foreach ($this->getTagVersions([$itemTags]) as $tag => $version) {
+ if ($itemTags[$tag] !== $version && 1 !== $itemTags[$tag] - $version) {
return false;
}
}
*/
public function getItem($key)
{
- foreach ($this->getItems(array($key)) as $item) {
+ foreach ($this->getItems([$key]) as $item) {
return $item;
}
+
+ return null;
}
/**
* {@inheritdoc}
*/
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
if ($this->deferred) {
$this->commit();
}
- $tagKeys = array();
+ $tagKeys = [];
foreach ($keys as $key) {
- if ('' !== $key && is_string($key)) {
+ if ('' !== $key && \is_string($key)) {
$key = static::TAGS_PREFIX.$key;
$tagKeys[$key] = $key;
}
*/
public function clear()
{
- $this->deferred = array();
+ $this->deferred = [];
return $this->pool->clear();
}
*/
public function deleteItem($key)
{
- return $this->deleteItems(array($key));
+ return $this->deleteItems([$key]);
}
/**
public function deleteItems(array $keys)
{
foreach ($keys as $key) {
- if ('' !== $key && is_string($key)) {
+ if ('' !== $key && \is_string($key)) {
$keys[] = static::TAGS_PREFIX.$key;
}
}
*/
public function commit()
{
- $ok = true;
-
- if ($this->deferred) {
- $items = $this->deferred;
- foreach ($items as $key => $item) {
- if (!$this->pool->saveDeferred($item)) {
- unset($this->deferred[$key]);
- $ok = false;
- }
- }
-
- $f = $this->getTagsByKey;
- $tagsByKey = $f($items);
- $this->deferred = array();
- $tagVersions = $this->getTagVersions($tagsByKey);
- $f = $this->createCacheItem;
+ return $this->invalidateTags([]);
+ }
- foreach ($tagsByKey as $key => $tags) {
- $this->pool->saveDeferred($f(static::TAGS_PREFIX.$key, array_intersect_key($tagVersions, $tags), $items[$key]));
- }
- }
+ public function __sleep()
+ {
+ throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
+ }
- return $this->pool->commit() && $ok;
+ public function __wakeup()
+ {
+ throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
public function __destruct()
private function generateItems($items, array $tagKeys)
{
- $bufferedItems = $itemTags = array();
+ $bufferedItems = $itemTags = [];
$f = $this->setCacheItemTags;
foreach ($items as $key => $item) {
}
unset($tagKeys[$key]);
- $itemTags[$key] = $item->get() ?: array();
+
+ if ($item->isHit()) {
+ $itemTags[$key] = $item->get() ?: [];
+ }
if (!$tagKeys) {
$tagVersions = $this->getTagVersions($itemTags);
foreach ($itemTags as $key => $tags) {
foreach ($tags as $tag => $version) {
- if ($tagVersions[$tag] !== $version) {
+ if ($tagVersions[$tag] !== $version && 1 !== $version - $tagVersions[$tag]) {
unset($itemTags[$key]);
continue 2;
}
}
}
- private function getTagVersions(array $tagsByKey)
+ private function getTagVersions(array $tagsByKey, array &$invalidatedTags = [])
{
- $tagVersions = array();
+ $tagVersions = $invalidatedTags;
foreach ($tagsByKey as $tags) {
$tagVersions += $tags;
}
- if ($tagVersions) {
- $tags = array();
- foreach ($tagVersions as $tag => $version) {
- $tagVersions[$tag] = $tag.static::TAGS_PREFIX;
- $tags[$tag.static::TAGS_PREFIX] = $tag;
+ if (!$tagVersions) {
+ return [];
+ }
+
+ if (!$fetchTagVersions = 1 !== \func_num_args()) {
+ foreach ($tagsByKey as $tags) {
+ foreach ($tags as $tag => $version) {
+ if ($tagVersions[$tag] > $version) {
+ $tagVersions[$tag] = $version;
+ }
+ }
+ }
+ }
+
+ $now = microtime(true);
+ $tags = [];
+ foreach ($tagVersions as $tag => $version) {
+ $tags[$tag.static::TAGS_PREFIX] = $tag;
+ if ($fetchTagVersions || !isset($this->knownTagVersions[$tag])) {
+ $fetchTagVersions = true;
+ continue;
}
- foreach ($this->tags->getItems($tagVersions) as $tag => $version) {
- $tagVersions[$tags[$tag]] = $version->get() ?: 0;
+ $version -= $this->knownTagVersions[$tag][1];
+ if ((0 !== $version && 1 !== $version) || $now - $this->knownTagVersions[$tag][0] >= $this->knownTagVersionsTtl) {
+ // reuse previously fetched tag versions up to the ttl, unless we are storing items or a potential miss arises
+ $fetchTagVersions = true;
+ } else {
+ $this->knownTagVersions[$tag][1] += $version;
+ }
+ }
+
+ if (!$fetchTagVersions) {
+ return $tagVersions;
+ }
+
+ foreach ($this->tags->getItems(array_keys($tags)) as $tag => $version) {
+ $tagVersions[$tag = $tags[$tag]] = $version->get() ?: 0;
+ if (isset($invalidatedTags[$tag])) {
+ $invalidatedTags[$tag] = $version->set(++$tagVersions[$tag]);
}
+ $this->knownTagVersions[$tag] = [$now, $tagVersions[$tag]];
}
return $tagVersions;
class TraceableAdapter implements AdapterInterface, PruneableInterface, ResettableInterface
{
protected $pool;
- private $calls = array();
+ private $calls = [];
public function __construct(AdapterInterface $pool)
{
/**
* {@inheritdoc}
*/
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
$event = $this->start(__FUNCTION__);
try {
$event->end = microtime(true);
}
$f = function () use ($result, $event) {
- $event->result = array();
+ $event->result = [];
foreach ($result as $key => $item) {
if ($event->result[$key] = $item->isHit()) {
++$event->hits;
*/
public function reset()
{
- if (!$this->pool instanceof ResettableInterface) {
- return;
- }
- $event = $this->start(__FUNCTION__);
- try {
+ if ($this->pool instanceof ResettableInterface) {
$this->pool->reset();
- } finally {
- $event->end = microtime(true);
}
+
+ $this->clearCalls();
}
public function getCalls()
public function clearCalls()
{
- $this->calls = array();
+ $this->calls = [];
}
protected function start($name)
protected $value;
protected $isHit = false;
protected $expiry;
- protected $defaultLifetime;
- protected $tags = array();
- protected $prevTags = array();
+ protected $tags = [];
+ protected $prevTags = [];
protected $innerItem;
protected $poolHash;
/**
* {@inheritdoc}
+ *
+ * @return $this
*/
public function set($value)
{
/**
* {@inheritdoc}
+ *
+ * @return $this
*/
public function expiresAt($expiration)
{
if (null === $expiration) {
- $this->expiry = $this->defaultLifetime > 0 ? time() + $this->defaultLifetime : null;
+ $this->expiry = null;
} elseif ($expiration instanceof \DateTimeInterface) {
$this->expiry = (int) $expiration->format('U');
} else {
- throw new InvalidArgumentException(sprintf('Expiration date must implement DateTimeInterface or be null, "%s" given', is_object($expiration) ? get_class($expiration) : gettype($expiration)));
+ throw new InvalidArgumentException(sprintf('Expiration date must implement DateTimeInterface or be null, "%s" given.', \is_object($expiration) ? \get_class($expiration) : \gettype($expiration)));
}
return $this;
/**
* {@inheritdoc}
+ *
+ * @return $this
*/
public function expiresAfter($time)
{
if (null === $time) {
- $this->expiry = $this->defaultLifetime > 0 ? time() + $this->defaultLifetime : null;
+ $this->expiry = null;
} elseif ($time instanceof \DateInterval) {
$this->expiry = (int) \DateTime::createFromFormat('U', time())->add($time)->format('U');
- } elseif (is_int($time)) {
+ } elseif (\is_int($time)) {
$this->expiry = $time + time();
} else {
- throw new InvalidArgumentException(sprintf('Expiration date must be an integer, a DateInterval or null, "%s" given', is_object($time) ? get_class($time) : gettype($time)));
+ throw new InvalidArgumentException(sprintf('Expiration date must be an integer, a DateInterval or null, "%s" given.', \is_object($time) ? \get_class($time) : \gettype($time)));
}
return $this;
*
* @param string|string[] $tags A tag or array of tags
*
- * @return static
+ * @return $this
*
* @throws InvalidArgumentException When $tag is not valid
*/
public function tag($tags)
{
- if (!is_array($tags)) {
- $tags = array($tags);
+ if (!\is_array($tags)) {
+ $tags = [$tags];
}
foreach ($tags as $tag) {
- if (!is_string($tag)) {
- throw new InvalidArgumentException(sprintf('Cache tag must be string, "%s" given', is_object($tag) ? get_class($tag) : gettype($tag)));
+ if (!\is_string($tag)) {
+ throw new InvalidArgumentException(sprintf('Cache tag must be string, "%s" given.', \is_object($tag) ? \get_class($tag) : \gettype($tag)));
}
if (isset($this->tags[$tag])) {
continue;
}
- if (!isset($tag[0])) {
- throw new InvalidArgumentException('Cache tag length must be greater than zero');
+ if ('' === $tag) {
+ throw new InvalidArgumentException('Cache tag length must be greater than zero.');
}
if (false !== strpbrk($tag, '{}()/\@:')) {
- throw new InvalidArgumentException(sprintf('Cache tag "%s" contains reserved characters {}()/\@:', $tag));
+ throw new InvalidArgumentException(sprintf('Cache tag "%s" contains reserved characters {}()/\@:.', $tag));
}
$this->tags[$tag] = $tag;
}
*/
public static function validateKey($key)
{
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
- if (!isset($key[0])) {
- throw new InvalidArgumentException('Cache key length must be greater than zero');
+ if ('' === $key) {
+ throw new InvalidArgumentException('Cache key length must be greater than zero.');
}
if (false !== strpbrk($key, '{}()/\@:')) {
- throw new InvalidArgumentException(sprintf('Cache key "%s" contains reserved characters {}()/\@:', $key));
+ throw new InvalidArgumentException(sprintf('Cache key "%s" contains reserved characters {}()/\@:.', $key));
}
return $key;
*
* @internal
*/
- public static function log(LoggerInterface $logger = null, $message, $context = array())
+ public static function log(LoggerInterface $logger = null, $message, $context = [])
{
if ($logger) {
$logger->warning($message, $context);
} else {
- $replace = array();
+ $replace = [];
foreach ($context as $k => $v) {
if (is_scalar($v)) {
$replace['{'.$k.'}'] = $v;
}
}
- @trigger_error(strtr($message, $replace), E_USER_WARNING);
+ @trigger_error(strtr($message, $replace), \E_USER_WARNING);
}
}
}
/**
* @var TraceableAdapter[]
*/
- private $instances = array();
+ private $instances = [];
/**
- * @param string $name
- * @param TraceableAdapter $instance
+ * @param string $name
*/
public function addInstance($name, TraceableAdapter $instance)
{
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
- $empty = array('calls' => array(), 'config' => array(), 'options' => array(), 'statistics' => array());
- $this->data = array('instances' => $empty, 'total' => $empty);
+ $empty = ['calls' => [], 'config' => [], 'options' => [], 'statistics' => []];
+ $this->data = ['instances' => $empty, 'total' => $empty];
foreach ($this->instances as $name => $instance) {
$this->data['instances']['calls'][$name] = $instance->getCalls();
}
public function reset()
{
- $this->data = array();
+ $this->data = [];
foreach ($this->instances as $instance) {
$instance->clearCalls();
}
*/
private function calculateStatistics()
{
- $statistics = array();
+ $statistics = [];
foreach ($this->data['instances']['calls'] as $name => $calls) {
- $statistics[$name] = array(
+ $statistics[$name] = [
'calls' => 0,
'time' => 0,
'reads' => 0,
'deletes' => 0,
'hits' => 0,
'misses' => 0,
- );
+ ];
/** @var TraceableAdapterEvent $call */
foreach ($calls as $call) {
- $statistics[$name]['calls'] += 1;
+ ++$statistics[$name]['calls'];
$statistics[$name]['time'] += $call->end - $call->start;
if ('getItem' === $call->name) {
- $statistics[$name]['reads'] += 1;
+ ++$statistics[$name]['reads'];
if ($call->hits) {
- $statistics[$name]['hits'] += 1;
+ ++$statistics[$name]['hits'];
} else {
- $statistics[$name]['misses'] += 1;
+ ++$statistics[$name]['misses'];
}
} elseif ('getItems' === $call->name) {
- $count = $call->hits + $call->misses;
- $statistics[$name]['reads'] += $count;
+ $statistics[$name]['reads'] += $call->hits + $call->misses;
$statistics[$name]['hits'] += $call->hits;
- $statistics[$name]['misses'] += $count - $call->misses;
+ $statistics[$name]['misses'] += $call->misses;
} elseif ('hasItem' === $call->name) {
- $statistics[$name]['reads'] += 1;
+ ++$statistics[$name]['reads'];
if (false === $call->result) {
- $statistics[$name]['misses'] += 1;
+ ++$statistics[$name]['misses'];
} else {
- $statistics[$name]['hits'] += 1;
+ ++$statistics[$name]['hits'];
}
} elseif ('save' === $call->name) {
- $statistics[$name]['writes'] += 1;
+ ++$statistics[$name]['writes'];
} elseif ('deleteItem' === $call->name) {
- $statistics[$name]['deletes'] += 1;
+ ++$statistics[$name]['deletes'];
}
}
if ($statistics[$name]['reads']) {
private function calculateTotalStatistics()
{
$statistics = $this->getStatistics();
- $totals = array(
+ $totals = [
'calls' => 0,
'time' => 0,
'reads' => 0,
'deletes' => 0,
'hits' => 0,
'misses' => 0,
- );
+ ];
foreach ($statistics as $name => $values) {
foreach ($totals as $key => $value) {
$totals[$key] += $statistics[$name][$key];
*/
protected function doFlush()
{
- $this->pool->clear();
+ return $this->pool->clear();
}
/**
*/
protected function doGetStats()
{
+ return null;
}
}
-Copyright (c) 2016-2018 Fabien Potencier
+Copyright (c) 2016-2020 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
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
-use Symfony\Component\Cache\Traits\AbstractTrait;
use Symfony\Component\Cache\ResettableInterface;
+use Symfony\Component\Cache\Traits\AbstractTrait;
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
abstract class AbstractCache implements CacheInterface, LoggerAwareInterface, ResettableInterface
{
+ /**
+ * @internal
+ */
+ const NS_SEPARATOR = ':';
+
use AbstractTrait {
deleteItems as private;
AbstractTrait::deleteItem as delete;
{
$this->defaultLifetime = max(0, (int) $defaultLifetime);
$this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace).':';
- if (null !== $this->maxIdLength && strlen($namespace) > $this->maxIdLength - 24) {
- throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s")', $this->maxIdLength - 24, strlen($namespace), $namespace));
+ if (null !== $this->maxIdLength && \strlen($namespace) > $this->maxIdLength - 24) {
+ throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s").', $this->maxIdLength - 24, \strlen($namespace), $namespace));
}
}
$id = $this->getId($key);
try {
- foreach ($this->doFetch(array($id)) as $value) {
+ foreach ($this->doFetch([$id]) as $value) {
return $value;
}
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to fetch key "{key}"', array('key' => $key, 'exception' => $e));
+ CacheItem::log($this->logger, 'Failed to fetch key "{key}"', ['key' => $key, 'exception' => $e]);
}
return $default;
{
CacheItem::validateKey($key);
- return $this->setMultiple(array($key => $value), $ttl);
+ return $this->setMultiple([$key => $value], $ttl);
}
/**
{
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
- } elseif (!is_array($keys)) {
- throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys)));
+ } elseif (!\is_array($keys)) {
+ throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
}
- $ids = array();
+ $ids = [];
foreach ($keys as $key) {
$ids[] = $this->getId($key);
try {
$values = $this->doFetch($ids);
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to fetch requested values', array('keys' => $keys, 'exception' => $e));
- $values = array();
+ CacheItem::log($this->logger, 'Failed to fetch requested values', ['keys' => $keys, 'exception' => $e]);
+ $values = [];
}
$ids = array_combine($ids, $keys);
*/
public function setMultiple($values, $ttl = null)
{
- if (!is_array($values) && !$values instanceof \Traversable) {
- throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given', is_object($values) ? get_class($values) : gettype($values)));
+ if (!\is_array($values) && !$values instanceof \Traversable) {
+ throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given.', \is_object($values) ? \get_class($values) : \gettype($values)));
}
- $valuesById = array();
+ $valuesById = [];
foreach ($values as $key => $value) {
- if (is_int($key)) {
+ if (\is_int($key)) {
$key = (string) $key;
}
$valuesById[$this->getId($key)] = $value;
$e = $this->doSave($valuesById, $ttl);
} catch (\Exception $e) {
}
- if (true === $e || array() === $e) {
+ if (true === $e || [] === $e) {
return true;
}
- $keys = array();
- foreach (is_array($e) ? $e : array_keys($valuesById) as $id) {
- $keys[] = substr($id, strlen($this->namespace));
+ $keys = [];
+ foreach (\is_array($e) ? $e : array_keys($valuesById) as $id) {
+ $keys[] = substr($id, \strlen($this->namespace));
}
- CacheItem::log($this->logger, 'Failed to save values', array('keys' => $keys, 'exception' => $e instanceof \Exception ? $e : null));
+ CacheItem::log($this->logger, 'Failed to save values', ['keys' => $keys, 'exception' => $e instanceof \Exception ? $e : null]);
return false;
}
{
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
- } elseif (!is_array($keys)) {
- throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys)));
+ } elseif (!\is_array($keys)) {
+ throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
}
return $this->deleteItems($keys);
if ($ttl instanceof \DateInterval) {
$ttl = (int) \DateTime::createFromFormat('U', 0)->add($ttl)->format('U');
}
- if (is_int($ttl)) {
+ if (\is_int($ttl)) {
return 0 < $ttl ? $ttl : false;
}
- throw new InvalidArgumentException(sprintf('Expiration date must be an integer, a DateInterval or null, "%s" given', is_object($ttl) ? get_class($ttl) : gettype($ttl)));
+ throw new InvalidArgumentException(sprintf('Expiration date must be an integer, a DateInterval or null, "%s" given.', \is_object($ttl) ? \get_class($ttl) : \gettype($ttl)));
}
private function generateValues($values, &$keys, $default)
yield $key => $value;
}
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to fetch requested values', array('keys' => array_values($keys), 'exception' => $e));
+ CacheItem::log($this->logger, 'Failed to fetch requested values', ['keys' => array_values($keys), 'exception' => $e]);
}
foreach ($keys as $key) {
*/
public function get($key, $default = null)
{
- foreach ($this->getMultiple(array($key), $default) as $v) {
+ foreach ($this->getMultiple([$key], $default) as $v) {
return $v;
}
}
{
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
- } elseif (!is_array($keys)) {
- throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys)));
+ } elseif (!\is_array($keys)) {
+ throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
}
foreach ($keys as $key) {
CacheItem::validateKey($key);
*/
public function deleteMultiple($keys)
{
- if (!is_array($keys) && !$keys instanceof \Traversable) {
- throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys)));
+ if (!\is_array($keys) && !$keys instanceof \Traversable) {
+ throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
}
foreach ($keys as $key) {
$this->delete($key);
{
CacheItem::validateKey($key);
- return $this->setMultiple(array($key => $value), $ttl);
+ return $this->setMultiple([$key => $value], $ttl);
}
/**
*/
public function setMultiple($values, $ttl = null)
{
- if (!is_array($values) && !$values instanceof \Traversable) {
- throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given', is_object($values) ? get_class($values) : gettype($values)));
+ if (!\is_array($values) && !$values instanceof \Traversable) {
+ throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given.', \is_object($values) ? \get_class($values) : \gettype($values)));
}
- $valuesArray = array();
+ $valuesArray = [];
foreach ($values as $key => $value) {
- is_int($key) || CacheItem::validateKey($key);
+ \is_int($key) || CacheItem::validateKey($key);
$valuesArray[$key] = $value;
}
if (false === $ttl = $this->normalizeTtl($ttl)) {
try {
$valuesArray[$key] = serialize($value);
} catch (\Exception $e) {
- $type = is_object($value) ? get_class($value) : gettype($value);
- CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => $key, 'type' => $type, 'exception' => $e));
+ $type = \is_object($value) ? \get_class($value) : \gettype($value);
+ CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', ['key' => $key, 'type' => $type, 'exception' => $e]);
return false;
}
}
}
- $expiry = 0 < $ttl ? time() + $ttl : PHP_INT_MAX;
+ $expiry = 0 < $ttl ? time() + $ttl : \PHP_INT_MAX;
foreach ($valuesArray as $key => $value) {
$this->values[$key] = $value;
if ($ttl instanceof \DateInterval) {
$ttl = (int) \DateTime::createFromFormat('U', 0)->add($ttl)->format('U');
}
- if (is_int($ttl)) {
+ if (\is_int($ttl)) {
return 0 < $ttl ? $ttl : false;
}
- throw new InvalidArgumentException(sprintf('Expiration date must be an integer, a DateInterval or null, "%s" given', is_object($ttl) ? get_class($ttl) : gettype($ttl)));
+ throw new InvalidArgumentException(sprintf('Expiration date must be an integer, a DateInterval or null, "%s" given.', \is_object($ttl) ? \get_class($ttl) : \gettype($ttl)));
}
}
class ChainCache implements CacheInterface, PruneableInterface, ResettableInterface
{
private $miss;
- private $caches = array();
+ private $caches = [];
private $defaultLifetime;
private $cacheCount;
foreach ($caches as $cache) {
if (!$cache instanceof CacheInterface) {
- throw new InvalidArgumentException(sprintf('The class "%s" does not implement the "%s" interface.', get_class($cache), CacheInterface::class));
+ throw new InvalidArgumentException(sprintf('The class "%s" does not implement the "%s" interface.', \get_class($cache), CacheInterface::class));
}
}
$this->miss = new \stdClass();
$this->caches = array_values($caches);
- $this->cacheCount = count($this->caches);
+ $this->cacheCount = \count($this->caches);
$this->defaultLifetime = 0 < $defaultLifetime ? (int) $defaultLifetime : null;
}
*/
public function get($key, $default = null)
{
- $miss = null !== $default && is_object($default) ? $default : $this->miss;
+ $miss = null !== $default && \is_object($default) ? $default : $this->miss;
foreach ($this->caches as $i => $cache) {
$value = $cache->get($key, $miss);
*/
public function getMultiple($keys, $default = null)
{
- $miss = null !== $default && is_object($default) ? $default : $this->miss;
+ $miss = null !== $default && \is_object($default) ? $default : $this->miss;
return $this->generateItems($this->caches[0]->getMultiple($keys, $miss), 0, $miss, $default);
}
private function generateItems($values, $cacheIndex, $miss, $default)
{
- $missing = array();
+ $missing = [];
$nextCacheIndex = $cacheIndex + 1;
$nextCache = isset($this->caches[$nextCacheIndex]) ? $this->caches[$nextCacheIndex] : null;
if ($values instanceof \Traversable) {
$valuesIterator = $values;
$values = function () use ($valuesIterator, &$values) {
- $generatedValues = array();
+ $generatedValues = [];
foreach ($valuesIterator as $key => $value) {
yield $key => $value;
use DoctrineTrait;
/**
- * @param CacheProvider $provider
- * @param string $namespace
- * @param int $defaultLifetime
+ * @param string $namespace
+ * @param int $defaultLifetime
*/
public function __construct(CacheProvider $provider, $namespace = '', $defaultLifetime = 0)
{
protected $maxIdLength = 250;
/**
- * @param \Memcached $client
- * @param string $namespace
- * @param int $defaultLifetime
+ * @param string $namespace
+ * @param int $defaultLifetime
*/
public function __construct(\Memcached $client, $namespace = '', $defaultLifetime = 0)
{
* * db_time_col: The column where to store the timestamp [default: item_time]
* * db_username: The username when lazy-connect [default: '']
* * db_password: The password when lazy-connect [default: '']
- * * db_connection_options: An array of driver-specific connection options [default: array()]
+ * * db_connection_options: An array of driver-specific connection options [default: []]
*
* @param \PDO|Connection|string $connOrDsn A \PDO or Connection instance or DSN string or null
* @param string $namespace
* @throws InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
* @throws InvalidArgumentException When namespace contains invalid characters
*/
- public function __construct($connOrDsn, $namespace = '', $defaultLifetime = 0, array $options = array())
+ public function __construct($connOrDsn, $namespace = '', $defaultLifetime = 0, array $options = [])
{
$this->init($connOrDsn, $namespace, $defaultLifetime, $options);
}
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
-use Symfony\Component\Cache\Traits\PhpArrayTrait;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Cache\ResettableInterface;
+use Symfony\Component\Cache\Traits\PhpArrayTrait;
/**
* Caches items at warm up time using a PHP array that is stored in shared memory by OPCache since PHP 7.0.
{
$this->file = $file;
$this->pool = $fallbackPool;
- $this->zendDetectUnicode = ini_get('zend.detect_unicode');
+ $this->zendDetectUnicode = filter_var(ini_get('zend.detect_unicode'), \FILTER_VALIDATE_BOOLEAN);
}
/**
* stores arrays in its latest versions. This factory method decorates the given
* fallback pool with this adapter only if the current PHP version is supported.
*
- * @param string $file The PHP file were values are cached
+ * @param string $file The PHP file were values are cached
+ * @param CacheInterface $fallbackPool A pool to fallback on when an item is not hit
*
* @return CacheInterface
*/
public static function create($file, CacheInterface $fallbackPool)
{
- // Shared memory is available in PHP 7.0+ with OPCache enabled and in HHVM
- if ((\PHP_VERSION_ID >= 70000 && ini_get('opcache.enable')) || defined('HHVM_VERSION')) {
+ if (\PHP_VERSION_ID >= 70000) {
return new static($file, $fallbackPool);
}
*/
public function get($key, $default = null)
{
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
if ('N;' === $value) {
$value = null;
- } elseif (is_string($value) && isset($value[2]) && ':' === $value[1]) {
+ } elseif (\is_string($value) && isset($value[2]) && ':' === $value[1]) {
try {
$e = null;
$value = unserialize($value);
{
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
- } elseif (!is_array($keys)) {
- throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys)));
+ } elseif (!\is_array($keys)) {
+ throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
}
foreach ($keys as $key) {
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
}
if (null === $this->values) {
*/
public function has($key)
{
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
*/
public function delete($key)
{
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
*/
public function deleteMultiple($keys)
{
- if (!is_array($keys) && !$keys instanceof \Traversable) {
- throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys)));
+ if (!\is_array($keys) && !$keys instanceof \Traversable) {
+ throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
}
$deleted = true;
- $fallbackKeys = array();
+ $fallbackKeys = [];
foreach ($keys as $key) {
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (isset($this->values[$key])) {
*/
public function set($key, $value, $ttl = null)
{
- if (!is_string($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (null === $this->values) {
$this->initialize();
*/
public function setMultiple($values, $ttl = null)
{
- if (!is_array($values) && !$values instanceof \Traversable) {
- throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given', is_object($values) ? get_class($values) : gettype($values)));
+ if (!\is_array($values) && !$values instanceof \Traversable) {
+ throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given.', \is_object($values) ? \get_class($values) : \gettype($values)));
}
$saved = true;
- $fallbackValues = array();
+ $fallbackValues = [];
foreach ($values as $key => $value) {
- if (!is_string($key) && !is_int($key)) {
- throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', is_object($key) ? get_class($key) : gettype($key)));
+ if (!\is_string($key) && !\is_int($key)) {
+ throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
}
if (isset($this->values[$key])) {
private function generateItems(array $keys, $default)
{
- $fallbackKeys = array();
+ $fallbackKeys = [];
foreach ($keys as $key) {
if (isset($this->values[$key])) {
if ('N;' === $value) {
yield $key => null;
- } elseif (is_string($value) && isset($value[2]) && ':' === $value[1]) {
+ } elseif (\is_string($value) && isset($value[2]) && ':' === $value[1]) {
try {
yield $key => unserialize($value);
} catch (\Error $e) {
public function __construct($namespace = '', $defaultLifetime = 0, $directory = null)
{
if (!static::isSupported()) {
- throw new CacheException('OPcache is not enabled');
+ throw new CacheException('OPcache is not enabled.');
}
parent::__construct('', $defaultLifetime);
$this->init($namespace, $directory);
$e = new \Exception();
$this->includeHandler = function () use ($e) { throw $e; };
- $this->zendDetectUnicode = ini_get('zend.detect_unicode');
+ $this->zendDetectUnicode = filter_var(ini_get('zend.detect_unicode'), \FILTER_VALIDATE_BOOLEAN);
}
}
namespace Symfony\Component\Cache\Simple;
-use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\CacheException as Psr6CacheException;
-use Psr\SimpleCache\CacheInterface;
+use Psr\Cache\CacheItemPoolInterface;
use Psr\SimpleCache\CacheException as SimpleCacheException;
-use Symfony\Component\Cache\Adapter\AbstractAdapter;
+use Psr\SimpleCache\CacheInterface;
+use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\PruneableInterface;
use ProxyTrait;
private $createCacheItem;
+ private $cacheItemPrototype;
public function __construct(CacheItemPoolInterface $pool)
{
$this->pool = $pool;
- if ($pool instanceof AbstractAdapter) {
- $this->createCacheItem = \Closure::bind(
- function ($key, $value, $allowInt = false) {
- if ($allowInt && is_int($key)) {
- $key = (string) $key;
- } else {
- CacheItem::validateKey($key);
- }
- $f = $this->createCacheItem;
-
- return $f($key, $value, false);
- },
- $pool,
- AbstractAdapter::class
- );
+ if (!$pool instanceof AdapterInterface) {
+ return;
}
+ $cacheItemPrototype = &$this->cacheItemPrototype;
+ $createCacheItem = \Closure::bind(
+ static function ($key, $value, $allowInt = false) use (&$cacheItemPrototype) {
+ $item = clone $cacheItemPrototype;
+ $item->key = $allowInt && \is_int($key) ? (string) $key : CacheItem::validateKey($key);
+ $item->value = $value;
+ $item->isHit = false;
+
+ return $item;
+ },
+ null,
+ CacheItem::class
+ );
+ $this->createCacheItem = function ($key, $value, $allowInt = false) use ($createCacheItem) {
+ if (null === $this->cacheItemPrototype) {
+ $this->get($allowInt && \is_int($key) ? (string) $key : $key);
+ }
+ $this->createCacheItem = $createCacheItem;
+
+ return $createCacheItem($key, $value, $allowInt);
+ };
}
/**
} catch (Psr6CacheException $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
+ if (null === $this->cacheItemPrototype) {
+ $this->cacheItemPrototype = clone $item;
+ $this->cacheItemPrototype->set(null);
+ }
return $item->isHit() ? $item->get() : $default;
}
{
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
- } elseif (!is_array($keys)) {
- throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys)));
+ } elseif (!\is_array($keys)) {
+ throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
}
try {
} catch (Psr6CacheException $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
- $values = array();
+ $values = [];
foreach ($items as $key => $item) {
$values[$key] = $item->isHit() ? $item->get() : $default;
*/
public function setMultiple($values, $ttl = null)
{
- $valuesIsArray = is_array($values);
+ $valuesIsArray = \is_array($values);
if (!$valuesIsArray && !$values instanceof \Traversable) {
- throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given', is_object($values) ? get_class($values) : gettype($values)));
+ throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given.', \is_object($values) ? \get_class($values) : \gettype($values)));
}
- $items = array();
+ $items = [];
try {
if (null !== $f = $this->createCacheItem) {
$items[$key] = $f($key, $value, true);
}
} elseif ($valuesIsArray) {
- $items = array();
+ $items = [];
foreach ($values as $key => $value) {
$items[] = (string) $key;
}
$items = $this->pool->getItems($items);
} else {
foreach ($values as $key => $value) {
- if (is_int($key)) {
+ if (\is_int($key)) {
$key = (string) $key;
}
$items[$key] = $this->pool->getItem($key)->set($value);
{
if ($keys instanceof \Traversable) {
$keys = iterator_to_array($keys, false);
- } elseif (!is_array($keys)) {
- throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys)));
+ } elseif (!\is_array($keys)) {
+ throw new InvalidArgumentException(sprintf('Cache keys must be array or Traversable, "%s" given.', \is_object($keys) ? \get_class($keys) : \gettype($keys)));
}
try {
{
private $pool;
private $miss;
- private $calls = array();
+ private $calls = [];
public function __construct(CacheInterface $pool)
{
*/
public function get($key, $default = null)
{
- $miss = null !== $default && is_object($default) ? $default : $this->miss;
+ $miss = null !== $default && \is_object($default) ? $default : $this->miss;
$event = $this->start(__FUNCTION__);
try {
$value = $this->pool->get($key, $miss);
public function setMultiple($values, $ttl = null)
{
$event = $this->start(__FUNCTION__);
- $event->result['keys'] = array();
+ $event->result['keys'] = [];
if ($values instanceof \Traversable) {
$values = function () use ($values, $event) {
}
};
$values = $values();
- } elseif (is_array($values)) {
+ } elseif (\is_array($values)) {
$event->result['keys'] = array_keys($values);
}
*/
public function getMultiple($keys, $default = null)
{
- $miss = null !== $default && is_object($default) ? $default : $this->miss;
+ $miss = null !== $default && \is_object($default) ? $default : $this->miss;
$event = $this->start(__FUNCTION__);
try {
$result = $this->pool->getMultiple($keys, $miss);
$event->end = microtime(true);
}
$f = function () use ($result, $event, $miss, $default) {
- $event->result = array();
+ $event->result = [];
foreach ($result as $key => $value) {
if ($event->result[$key] = $miss !== $value) {
++$event->hits;
try {
return $this->calls;
} finally {
- $this->calls = array();
+ $this->calls = [];
}
}
abstract class AbstractRedisAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testExpiration' => 'Testing expiration slows down the test suite',
'testHasItemReturnsFalseWhenDeferredItemIsExpired' => 'Testing expiration slows down the test suite',
'testDefaultLifeTime' => 'Testing expiration slows down the test suite',
- );
+ ];
protected static $redis;
return new RedisAdapter(self::$redis, str_replace('\\', '.', __CLASS__), $defaultLifetime);
}
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
- if (!extension_loaded('redis')) {
+ if (!\extension_loaded('redis')) {
self::markTestSkipped('Extension redis required.');
}
- if (!@((new \Redis())->connect(getenv('REDIS_HOST')))) {
- $e = error_get_last();
- self::markTestSkipped($e['message']);
+ try {
+ (new \Redis())->connect(getenv('REDIS_HOST'));
+ } catch (\Exception $e) {
+ self::markTestSkipped($e->getMessage());
}
}
{
parent::setUp();
- if (!array_key_exists('testDeferredSaveWithoutCommit', $this->skippedTests) && defined('HHVM_VERSION')) {
+ if (!\array_key_exists('testDeferredSaveWithoutCommit', $this->skippedTests) && \defined('HHVM_VERSION')) {
$this->skippedTests['testDeferredSaveWithoutCommit'] = 'Destructors are called late on HHVM.';
}
- if (!array_key_exists('testPrune', $this->skippedTests) && !$this->createCachePool() instanceof PruneableInterface) {
+ if (!\array_key_exists('testPrune', $this->skippedTests) && !$this->createCachePool() instanceof PruneableInterface) {
$this->skippedTests['testPrune'] = 'Not a pruneable cache pool.';
}
}
$item = $cache->getItem('foo');
$this->assertFalse($item->isHit());
- foreach ($cache->getItems(array('foo')) as $item) {
+ foreach ($cache->getItems(['foo']) as $item) {
}
$cache->save($item->set(new NotUnserializable()));
- foreach ($cache->getItems(array('foo')) as $item) {
+ foreach ($cache->getItems(['foo']) as $item) {
}
$this->assertFalse($item->isHit());
}
class ApcuAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testExpiration' => 'Testing expiration slows down the test suite',
'testHasItemReturnsFalseWhenDeferredItemIsExpired' => 'Testing expiration slows down the test suite',
'testDefaultLifeTime' => 'Testing expiration slows down the test suite',
- );
+ ];
public function createCachePool($defaultLifetime = 0)
{
- if (!function_exists('apcu_fetch') || !ini_get('apc.enabled')) {
+ if (!\function_exists('apcu_fetch') || !filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN)) {
$this->markTestSkipped('APCu extension is required.');
}
- if ('cli' === PHP_SAPI && !ini_get('apc.enable_cli')) {
+ if ('cli' === \PHP_SAPI && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) {
if ('testWithCliSapi' !== $this->getName()) {
$this->markTestSkipped('apc.enable_cli=1 is required.');
}
}
- if ('\\' === DIRECTORY_SEPARATOR) {
+ if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Fails transiently on Windows.');
}
public function testVersion()
{
- $namespace = str_replace('\\', '.', get_class($this));
+ $namespace = str_replace('\\', '.', static::class);
$pool1 = new ApcuAdapter($namespace, 0, 'p1');
public function testNamespace()
{
- $namespace = str_replace('\\', '.', get_class($this));
+ $namespace = str_replace('\\', '.', static::class);
$pool1 = new ApcuAdapter($namespace.'_1', 0, 'p1');
*/
class ArrayAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testDeferredSaveWithoutCommit' => 'Assumes a shared cache which ArrayAdapter is not.',
'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayAdapter is not.',
- );
+ ];
public function createCachePool($defaultLifetime = 0)
{
namespace Symfony\Component\Cache\Tests\Adapter;
+use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Cache\Adapter\AdapterInterface;
-use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\ChainAdapter;
+use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Cache\Tests\Fixtures\ExternalAdapter;
{
public function createCachePool($defaultLifetime = 0)
{
- return new ChainAdapter(array(new ArrayAdapter($defaultLifetime), new ExternalAdapter(), new FilesystemAdapter('', $defaultLifetime)), $defaultLifetime);
+ return new ChainAdapter([new ArrayAdapter($defaultLifetime), new ExternalAdapter($defaultLifetime), new FilesystemAdapter('', $defaultLifetime)], $defaultLifetime);
}
- /**
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage At least one adapter must be specified.
- */
public function testEmptyAdaptersException()
{
- new ChainAdapter(array());
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('At least one adapter must be specified.');
+ new ChainAdapter([]);
}
- /**
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage The class "stdClass" does not implement
- */
public function testInvalidAdapterException()
{
- new ChainAdapter(array(new \stdClass()));
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('The class "stdClass" does not implement');
+ new ChainAdapter([new \stdClass()]);
}
public function testPrune()
$this->markTestSkipped($this->skippedTests[__FUNCTION__]);
}
- $cache = new ChainAdapter(array(
+ $cache = new ChainAdapter([
$this->getPruneableMock(),
$this->getNonPruneableMock(),
$this->getPruneableMock(),
- ));
+ ]);
$this->assertTrue($cache->prune());
- $cache = new ChainAdapter(array(
+ $cache = new ChainAdapter([
$this->getPruneableMock(),
$this->getFailingPruneableMock(),
$this->getPruneableMock(),
- ));
+ ]);
$this->assertFalse($cache->prune());
}
+ public function testMultipleCachesExpirationWhenCommonTtlIsNotSet()
+ {
+ if (isset($this->skippedTests[__FUNCTION__])) {
+ $this->markTestSkipped($this->skippedTests[__FUNCTION__]);
+ }
+
+ $adapter1 = new ArrayAdapter(4);
+ $adapter2 = new ArrayAdapter(2);
+
+ $cache = new ChainAdapter([$adapter1, $adapter2]);
+
+ $cache->save($cache->getItem('key')->set('value'));
+
+ $item = $adapter1->getItem('key');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value', $item->get());
+
+ $item = $adapter2->getItem('key');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value', $item->get());
+
+ sleep(2);
+
+ $item = $adapter1->getItem('key');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value', $item->get());
+
+ $item = $adapter2->getItem('key');
+ $this->assertFalse($item->isHit());
+
+ sleep(2);
+
+ $item = $adapter1->getItem('key');
+ $this->assertFalse($item->isHit());
+
+ $adapter2->save($adapter2->getItem('key1')->set('value1'));
+
+ $item = $cache->getItem('key1');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value1', $item->get());
+
+ sleep(2);
+
+ $item = $adapter1->getItem('key1');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value1', $item->get());
+
+ $item = $adapter2->getItem('key1');
+ $this->assertFalse($item->isHit());
+
+ sleep(2);
+
+ $item = $adapter1->getItem('key1');
+ $this->assertFalse($item->isHit());
+ }
+
+ public function testMultipleCachesExpirationWhenCommonTtlIsSet()
+ {
+ if (isset($this->skippedTests[__FUNCTION__])) {
+ $this->markTestSkipped($this->skippedTests[__FUNCTION__]);
+ }
+
+ $adapter1 = new ArrayAdapter(4);
+ $adapter2 = new ArrayAdapter(2);
+
+ $cache = new ChainAdapter([$adapter1, $adapter2], 6);
+
+ $cache->save($cache->getItem('key')->set('value'));
+
+ $item = $adapter1->getItem('key');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value', $item->get());
+
+ $item = $adapter2->getItem('key');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value', $item->get());
+
+ sleep(2);
+
+ $item = $adapter1->getItem('key');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value', $item->get());
+
+ $item = $adapter2->getItem('key');
+ $this->assertFalse($item->isHit());
+
+ sleep(2);
+
+ $item = $adapter1->getItem('key');
+ $this->assertFalse($item->isHit());
+
+ $adapter2->save($adapter2->getItem('key1')->set('value1'));
+
+ $item = $cache->getItem('key1');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value1', $item->get());
+
+ sleep(2);
+
+ $item = $adapter1->getItem('key1');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value1', $item->get());
+
+ $item = $adapter2->getItem('key1');
+ $this->assertFalse($item->isHit());
+
+ sleep(2);
+
+ $item = $adapter1->getItem('key1');
+ $this->assertTrue($item->isHit());
+ $this->assertEquals('value1', $item->get());
+
+ sleep(2);
+
+ $item = $adapter1->getItem('key1');
+ $this->assertFalse($item->isHit());
+ }
+
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface
+ * @return MockObject|PruneableCacheInterface
*/
private function getPruneableMock()
{
$pruneable
->expects($this->atLeastOnce())
->method('prune')
- ->will($this->returnValue(true));
+ ->willReturn(true);
return $pruneable;
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface
+ * @return MockObject|PruneableCacheInterface
*/
private function getFailingPruneableMock()
{
$pruneable
->expects($this->atLeastOnce())
->method('prune')
- ->will($this->returnValue(false));
+ ->willReturn(false);
return $pruneable;
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|AdapterInterface
+ * @return MockObject|AdapterInterface
*/
private function getNonPruneableMock()
{
*/
class DoctrineAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testDeferredSaveWithoutCommit' => 'Assumes a shared cache which ArrayCache is not.',
'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayCache is not.',
'testNotUnserializable' => 'ArrayCache does not use serialize/unserialize',
- );
+ ];
public function createCachePool($defaultLifetime = 0)
{
if (!file_exists($dir)) {
return;
}
- if (!$dir || 0 !== strpos(dirname($dir), sys_get_temp_dir())) {
+ if (!$dir || 0 !== strpos(\dirname($dir), sys_get_temp_dir())) {
throw new \Exception(__METHOD__."() operates only on subdirs of system's temp dir");
}
$children = new \RecursiveIteratorIterator(
public function testLongKey()
{
$cache = $this->getMockBuilder(MaxIdLengthAdapter::class)
- ->setConstructorArgs(array(str_repeat('-', 10)))
- ->setMethods(array('doHave', 'doFetch', 'doDelete', 'doSave', 'doClear'))
+ ->setConstructorArgs([str_repeat('-', 10)])
+ ->setMethods(['doHave', 'doFetch', 'doDelete', 'doSave', 'doClear'])
->getMock();
$cache->expects($this->exactly(2))
->method('doHave')
->withConsecutive(
- array($this->equalTo('----------:0GTYWa9n4ed8vqNlOT2iEr:')),
- array($this->equalTo('----------:---------------------------------------'))
+ [$this->equalTo('----------:0GTYWa9n4ed8vqNlOT2iEr:')],
+ [$this->equalTo('----------:---------------------------------------')]
);
$cache->hasItem(str_repeat('-', 40));
$cache->hasItem(str_repeat('-', 39));
}
- /**
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage Namespace must be 26 chars max, 40 given ("----------------------------------------")
- */
- public function testTooLongNamespace()
+ public function testLongKeyVersioning()
{
$cache = $this->getMockBuilder(MaxIdLengthAdapter::class)
- ->setConstructorArgs(array(str_repeat('-', 40)))
+ ->setConstructorArgs([str_repeat('-', 26)])
+ ->getMock();
+
+ $cache
+ ->method('doFetch')
+ ->willReturn(['2:']);
+
+ $reflectionClass = new \ReflectionClass(AbstractAdapter::class);
+
+ $reflectionMethod = $reflectionClass->getMethod('getId');
+ $reflectionMethod->setAccessible(true);
+
+ // No versioning enabled
+ $this->assertEquals('--------------------------:------------', $reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)]));
+ $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)])));
+ $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 23)])));
+ $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 40)])));
+
+ $reflectionProperty = $reflectionClass->getProperty('versioningIsEnabled');
+ $reflectionProperty->setAccessible(true);
+ $reflectionProperty->setValue($cache, true);
+
+ // Versioning enabled
+ $this->assertEquals('--------------------------:2:------------', $reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)]));
+ $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)])));
+ $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 23)])));
+ $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 40)])));
+ }
+
+ public function testTooLongNamespace()
+ {
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('Namespace must be 26 chars max, 40 given ("----------------------------------------")');
+ $this->getMockBuilder(MaxIdLengthAdapter::class)
+ ->setConstructorArgs([str_repeat('-', 40)])
->getMock();
}
}
class MemcachedAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testHasItemReturnsFalseWhenDeferredItemIsExpired' => 'Testing expiration slows down the test suite',
'testDefaultLifeTime' => 'Testing expiration slows down the test suite',
- );
+ ];
protected static $client;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
if (!MemcachedAdapter::isSupported()) {
self::markTestSkipped('Extension memcached >=2.2.0 required.');
}
- self::$client = AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST'), array('binary_protocol' => false));
+ self::$client = AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['binary_protocol' => false]);
self::$client->get('foo');
$code = self::$client->getResultCode();
public function testOptions()
{
- $client = MemcachedAdapter::createConnection(array(), array(
+ $client = MemcachedAdapter::createConnection([], [
'libketama_compatible' => false,
'distribution' => 'modula',
'compression' => true,
'serializer' => 'php',
'hash' => 'md5',
- ));
+ ]);
$this->assertSame(\Memcached::SERIALIZER_PHP, $client->getOption(\Memcached::OPT_SERIALIZER));
$this->assertSame(\Memcached::HASH_MD5, $client->getOption(\Memcached::OPT_HASH));
/**
* @dataProvider provideBadOptions
- * @expectedException \ErrorException
- * @expectedExceptionMessage constant(): Couldn't find constant Memcached::
*/
public function testBadOptions($name, $value)
{
- MemcachedAdapter::createConnection(array(), array($name => $value));
+ if (\PHP_VERSION_ID < 80000) {
+ $this->expectException('ErrorException');
+ $this->expectExceptionMessage('constant(): Couldn\'t find constant Memcached::');
+ } else {
+ $this->expectException('Error');
+ $this->expectExceptionMessage('Undefined constant Memcached::');
+ }
+
+ MemcachedAdapter::createConnection([], [$name => $value]);
}
public function provideBadOptions()
{
- return array(
- array('foo', 'bar'),
- array('hash', 'zyx'),
- array('serializer', 'zyx'),
- array('distribution', 'zyx'),
- );
+ return [
+ ['foo', 'bar'],
+ ['hash', 'zyx'],
+ ['serializer', 'zyx'],
+ ['distribution', 'zyx'],
+ ];
}
public function testDefaultOptions()
{
$this->assertTrue(MemcachedAdapter::isSupported());
- $client = MemcachedAdapter::createConnection(array());
+ $client = MemcachedAdapter::createConnection([]);
$this->assertTrue($client->getOption(\Memcached::OPT_COMPRESSION));
$this->assertSame(1, $client->getOption(\Memcached::OPT_BINARY_PROTOCOL));
+ $this->assertSame(1, $client->getOption(\Memcached::OPT_TCP_NODELAY));
$this->assertSame(1, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE));
}
- /**
- * @expectedException \Symfony\Component\Cache\Exception\CacheException
- * @expectedExceptionMessage MemcachedAdapter: "serializer" option must be "php" or "igbinary".
- */
public function testOptionSerializer()
{
+ $this->expectException('Symfony\Component\Cache\Exception\CacheException');
+ $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
if (!\Memcached::HAVE_JSON) {
$this->markTestSkipped('Memcached::HAVE_JSON required');
}
- new MemcachedAdapter(MemcachedAdapter::createConnection(array(), array('serializer' => 'json')));
+ new MemcachedAdapter(MemcachedAdapter::createConnection([], ['serializer' => 'json']));
}
/**
public function testServersSetting($dsn, $host, $port)
{
$client1 = MemcachedAdapter::createConnection($dsn);
- $client2 = MemcachedAdapter::createConnection(array($dsn));
- $client3 = MemcachedAdapter::createConnection(array(array($host, $port)));
- $expect = array(
+ $client2 = MemcachedAdapter::createConnection([$dsn]);
+ $client3 = MemcachedAdapter::createConnection([[$host, $port]]);
+ $expect = [
'host' => $host,
'port' => $port,
- );
+ ];
- $f = function ($s) { return array('host' => $s['host'], 'port' => $s['port']); };
- $this->assertSame(array($expect), array_map($f, $client1->getServerList()));
- $this->assertSame(array($expect), array_map($f, $client2->getServerList()));
- $this->assertSame(array($expect), array_map($f, $client3->getServerList()));
+ $f = function ($s) { return ['host' => $s['host'], 'port' => $s['port']]; };
+ $this->assertSame([$expect], array_map($f, $client1->getServerList()));
+ $this->assertSame([$expect], array_map($f, $client2->getServerList()));
+ $this->assertSame([$expect], array_map($f, $client3->getServerList()));
}
public function provideServersSetting()
{
- yield array(
+ yield [
'memcached://127.0.0.1/50',
'127.0.0.1',
11211,
- );
- yield array(
+ ];
+ yield [
'memcached://localhost:11222?weight=25',
'localhost',
11222,
- );
- if (ini_get('memcached.use_sasl')) {
- yield array(
+ ];
+ if (filter_var(ini_get('memcached.use_sasl'), \FILTER_VALIDATE_BOOLEAN)) {
+ yield [
'memcached://user:password@127.0.0.1?weight=50',
'127.0.0.1',
11211,
- );
+ ];
}
- yield array(
+ yield [
'memcached:///var/run/memcached.sock?weight=25',
'/var/run/memcached.sock',
0,
- );
- yield array(
+ ];
+ yield [
'memcached:///var/local/run/memcached.socket?weight=25',
'/var/local/run/memcached.socket',
0,
- );
- if (ini_get('memcached.use_sasl')) {
- yield array(
+ ];
+ if (filter_var(ini_get('memcached.use_sasl'), \FILTER_VALIDATE_BOOLEAN)) {
+ yield [
'memcached://user:password@/var/local/run/memcached.socket?weight=25',
'/var/local/run/memcached.socket',
0,
- );
+ ];
}
}
self::markTestSkipped('Extension memcached required.');
}
- yield array(
+ yield [
'memcached://localhost:11222?retry_timeout=10',
- array(\Memcached::OPT_RETRY_TIMEOUT => 8),
- array(\Memcached::OPT_RETRY_TIMEOUT => 10),
- );
- yield array(
+ [\Memcached::OPT_RETRY_TIMEOUT => 8],
+ [\Memcached::OPT_RETRY_TIMEOUT => 10],
+ ];
+ yield [
'memcached://localhost:11222?socket_recv_size=1&socket_send_size=2',
- array(\Memcached::OPT_RETRY_TIMEOUT => 8),
- array(\Memcached::OPT_SOCKET_RECV_SIZE => 1, \Memcached::OPT_SOCKET_SEND_SIZE => 2, \Memcached::OPT_RETRY_TIMEOUT => 8),
- );
+ [\Memcached::OPT_RETRY_TIMEOUT => 8],
+ [\Memcached::OPT_SOCKET_RECV_SIZE => 1, \Memcached::OPT_SOCKET_SEND_SIZE => 2, \Memcached::OPT_RETRY_TIMEOUT => 8],
+ ];
+ }
+
+ public function testClear()
+ {
+ $this->assertTrue($this->createCachePool()->clear());
}
}
{
$adapter = $this->createCachePool();
- $keys = array('foo', 'bar', 'baz', 'biz');
+ $keys = ['foo', 'bar', 'baz', 'biz'];
/** @var CacheItemInterface[] $items */
$items = $adapter->getItems($keys);
public function testDeleteItems()
{
- $this->assertTrue($this->createCachePool()->deleteItems(array('key', 'foo', 'bar')));
+ $this->assertTrue($this->createCachePool()->deleteItems(['key', 'foo', 'bar']));
}
public function testSave()
protected static $dbFile;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
- if (!extension_loaded('pdo_sqlite')) {
+ if (!\extension_loaded('pdo_sqlite')) {
self::markTestSkipped('Extension pdo_sqlite required.');
}
protected static $dbFile;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
- if (!extension_loaded('pdo_sqlite')) {
+ if (!\extension_loaded('pdo_sqlite')) {
self::markTestSkipped('Extension pdo_sqlite required.');
}
self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache');
- $pool = new PdoAdapter(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile)));
+ $pool = new PdoAdapter(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile]));
$pool->createTable();
}
public function createCachePool($defaultLifetime = 0)
{
- return new PdoAdapter(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile)), '', $defaultLifetime);
+ return new PdoAdapter(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile]), '', $defaultLifetime);
}
}
*/
class PhpArrayAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testBasicUsage' => 'PhpArrayAdapter is read-only.',
'testBasicUsageWithLongKey' => 'PhpArrayAdapter is read-only.',
'testClear' => 'PhpArrayAdapter is read-only.',
'testDefaultLifeTime' => 'PhpArrayAdapter does not allow configuring a default lifetime.',
'testPrune' => 'PhpArrayAdapter just proxies',
- );
+ ];
protected static $file;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php';
}
protected function tearDown()
{
+ $this->createCachePool()->clear();
+
if (file_exists(sys_get_temp_dir().'/symfony-cache')) {
FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache');
}
public function testStore()
{
- $arrayWithRefs = array();
+ $arrayWithRefs = [];
$arrayWithRefs[0] = 123;
$arrayWithRefs[1] = &$arrayWithRefs[0];
- $object = (object) array(
+ $object = (object) [
'foo' => 'bar',
'foo2' => 'bar2',
- );
+ ];
- $expected = array(
+ $expected = [
'null' => null,
'serializedString' => serialize($object),
'arrayWithRefs' => $arrayWithRefs,
'object' => $object,
- 'arrayWithObject' => array('bar' => $object),
- );
+ 'arrayWithObject' => ['bar' => $object],
+ ];
$adapter = $this->createCachePool();
$adapter->warmUp($expected);
public function testStoredFile()
{
- $expected = array(
+ $expected = [
'integer' => 42,
'float' => 42.42,
'boolean' => true,
- 'array_simple' => array('foo', 'bar'),
- 'array_associative' => array('foo' => 'bar', 'foo2' => 'bar2'),
- );
+ 'array_simple' => ['foo', 'bar'],
+ 'array_associative' => ['foo' => 'bar', 'foo2' => 'bar2'],
+ ];
$adapter = $this->createCachePool();
$adapter->warmUp($expected);
{
public function save(CacheItemInterface $item)
{
- call_user_func(\Closure::bind(function () use ($item) {
+ \call_user_func(\Closure::bind(function () use ($item) {
$this->values[$item->getKey()] = $item->get();
$this->warmUp($this->values);
$this->values = eval(substr(file_get_contents($this->file), 6));
*/
class PhpArrayAdapterWithFallbackTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testGetItemInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.',
'testGetItemsInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.',
'testHasItemInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.',
'testDeleteItemInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.',
'testDeleteItemsInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.',
'testPrune' => 'PhpArrayAdapter just proxies',
- );
+ ];
protected static $file;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php';
}
protected function tearDown()
{
+ $this->createCachePool()->clear();
+
if (file_exists(sys_get_temp_dir().'/symfony-cache')) {
FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache');
}
*/
class PhpFilesAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testDefaultLifeTime' => 'PhpFilesAdapter does not allow configuring a default lifetime.',
- );
+ ];
public function createCachePool()
{
class PredisAdapterTest extends AbstractRedisAdapterTest
{
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
- parent::setupBeforeClass();
- self::$redis = new \Predis\Client(array('host' => getenv('REDIS_HOST')));
+ parent::setUpBeforeClass();
+ self::$redis = new \Predis\Client(['host' => getenv('REDIS_HOST')]);
}
public function testCreateConnection()
{
$redisHost = getenv('REDIS_HOST');
- $redis = RedisAdapter::createConnection('redis://'.$redisHost.'/1', array('class' => \Predis\Client::class, 'timeout' => 3));
+ $redis = RedisAdapter::createConnection('redis://'.$redisHost.'/1', ['class' => \Predis\Client::class, 'timeout' => 3]);
$this->assertInstanceOf(\Predis\Client::class, $redis);
$connection = $redis->getConnection();
$this->assertInstanceOf(StreamConnection::class, $connection);
- $params = array(
+ $params = [
'scheme' => 'tcp',
'host' => $redisHost,
'path' => '',
'lazy' => false,
'database' => '1',
'password' => null,
- );
+ ];
$this->assertSame($params, $connection->getParameters()->toArray());
}
}
class PredisClusterAdapterTest extends AbstractRedisAdapterTest
{
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
- parent::setupBeforeClass();
- self::$redis = new \Predis\Client(array(array('host' => getenv('REDIS_HOST'))));
+ parent::setUpBeforeClass();
+ self::$redis = new \Predis\Client([['host' => getenv('REDIS_HOST')]]);
}
public static function tearDownAfterClass()
--- /dev/null
+<?php
+
+/*
+ * This file is part of the Symfony package.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Component\Cache\Tests\Adapter;
+
+class PredisRedisClusterAdapterTest extends AbstractRedisAdapterTest
+{
+ public static function setUpBeforeClass()
+ {
+ if (!$hosts = getenv('REDIS_CLUSTER_HOSTS')) {
+ self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.');
+ }
+ self::$redis = new \Predis\Client(explode(' ', $hosts), ['cluster' => 'redis']);
+ }
+
+ public static function tearDownAfterClass()
+ {
+ self::$redis = null;
+ }
+}
*/
class ProxyAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testDeferredSaveWithoutCommit' => 'Assumes a shared cache which ArrayAdapter is not.',
'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayAdapter is not.',
'testPrune' => 'ProxyAdapter just proxies',
- );
+ ];
public function createCachePool($defaultLifetime = 0)
{
return new ProxyAdapter(new ArrayAdapter(), '', $defaultLifetime);
}
- /**
- * @expectedException \Exception
- * @expectedExceptionMessage OK bar
- */
public function testProxyfiedItem()
{
+ $this->expectException('Exception');
+ $this->expectExceptionMessage('OK bar');
$item = new CacheItem();
$pool = new ProxyAdapter(new TestingArrayAdapter($item));
class RedisAdapterTest extends AbstractRedisAdapterTest
{
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
- parent::setupBeforeClass();
- self::$redis = AbstractAdapter::createConnection('redis://'.getenv('REDIS_HOST'), array('lazy' => true));
+ parent::setUpBeforeClass();
+ self::$redis = AbstractAdapter::createConnection('redis://'.getenv('REDIS_HOST'), ['lazy' => true]);
}
public function createCachePool($defaultLifetime = 0)
$redis = RedisAdapter::createConnection('redis://'.$redisHost.'/2');
$this->assertSame(2, $redis->getDbNum());
- $redis = RedisAdapter::createConnection('redis://'.$redisHost, array('timeout' => 3));
+ $redis = RedisAdapter::createConnection('redis://'.$redisHost, ['timeout' => 3]);
$this->assertEquals(3, $redis->getTimeout());
$redis = RedisAdapter::createConnection('redis://'.$redisHost.'?timeout=4');
$this->assertEquals(4, $redis->getTimeout());
- $redis = RedisAdapter::createConnection('redis://'.$redisHost, array('read_timeout' => 5));
+ $redis = RedisAdapter::createConnection('redis://'.$redisHost, ['read_timeout' => 5]);
$this->assertEquals(5, $redis->getReadTimeout());
}
/**
* @dataProvider provideFailedCreateConnection
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage Redis connection failed
*/
public function testFailedCreateConnection($dsn)
{
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('Redis connection ');
RedisAdapter::createConnection($dsn);
}
public function provideFailedCreateConnection()
{
- return array(
- array('redis://localhost:1234'),
- array('redis://foo@localhost'),
- array('redis://localhost/123'),
- );
+ return [
+ ['redis://localhost:1234'],
+ ['redis://foo@localhost'],
+ ['redis://localhost/123'],
+ ];
}
/**
* @dataProvider provideInvalidCreateConnection
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage Invalid Redis DSN
*/
public function testInvalidCreateConnection($dsn)
{
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('Invalid Redis DSN');
RedisAdapter::createConnection($dsn);
}
public function provideInvalidCreateConnection()
{
- return array(
- array('foo://localhost'),
- array('redis://'),
- );
+ return [
+ ['foo://localhost'],
+ ['redis://'],
+ ];
}
}
class RedisArrayAdapterTest extends AbstractRedisAdapterTest
{
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
parent::setupBeforeClass();
if (!class_exists('RedisArray')) {
self::markTestSkipped('The RedisArray class is required.');
}
- self::$redis = new \RedisArray(array(getenv('REDIS_HOST')), array('lazy_connect' => true));
+ self::$redis = new \RedisArray([getenv('REDIS_HOST')], ['lazy_connect' => true]);
}
}
--- /dev/null
+<?php
+
+/*
+ * This file is part of the Symfony package.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Component\Cache\Tests\Adapter;
+
+class RedisClusterAdapterTest extends AbstractRedisAdapterTest
+{
+ public static function setUpBeforeClass()
+ {
+ if (!class_exists('RedisCluster')) {
+ self::markTestSkipped('The RedisCluster class is required.');
+ }
+ if (!$hosts = getenv('REDIS_CLUSTER_HOSTS')) {
+ self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.');
+ }
+
+ self::$redis = new \RedisCluster(null, explode(' ', $hosts));
+ }
+}
namespace Symfony\Component\Cache\Tests\Adapter;
-use Symfony\Component\Cache\Simple\FilesystemCache;
use Symfony\Component\Cache\Adapter\SimpleCacheAdapter;
+use Symfony\Component\Cache\Simple\ArrayCache;
+use Symfony\Component\Cache\Simple\FilesystemCache;
/**
* @group time-sensitive
*/
class SimpleCacheAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testPrune' => 'SimpleCache just proxies',
- );
+ ];
public function createCachePool($defaultLifetime = 0)
{
return new SimpleCacheAdapter(new FilesystemCache(), '', $defaultLifetime);
}
+
+ public function testValidCacheKeyWithNamespace()
+ {
+ $cache = new SimpleCacheAdapter(new ArrayCache(), 'some_namespace', 0);
+ $item = $cache->getItem('my_key');
+ $item->set('someValue');
+ $cache->save($item);
+
+ $this->assertTrue($cache->getItem('my_key')->isHit(), 'Stored item is successfully retrieved.');
+ }
}
namespace Symfony\Component\Cache\Tests\Adapter;
+use PHPUnit\Framework\MockObject\MockObject;
+use Psr\Cache\CacheItemInterface;
use Symfony\Component\Cache\Adapter\AdapterInterface;
+use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache');
}
- /**
- * @expectedException \Psr\Cache\InvalidArgumentException
- */
public function testInvalidTag()
{
+ $this->expectException('Psr\Cache\InvalidArgumentException');
$pool = $this->createCachePool();
$item = $pool->getItem('foo');
$item->tag(':');
$pool->save($i3->tag('foo')->tag('baz'));
$pool->save($foo);
- $pool->invalidateTags(array('bar'));
+ $pool->invalidateTags(['bar']);
$this->assertFalse($pool->getItem('i0')->isHit());
$this->assertTrue($pool->getItem('i1')->isHit());
$this->assertTrue($pool->getItem('i3')->isHit());
$this->assertTrue($pool->getItem('foo')->isHit());
- $pool->invalidateTags(array('foo'));
+ $pool->invalidateTags(['foo']);
$this->assertFalse($pool->getItem('i1')->isHit());
$this->assertFalse($pool->getItem('i3')->isHit());
$this->assertTrue($pool->getItem('foo')->isHit());
+
+ $anotherPoolInstance = $this->createCachePool();
+
+ $this->assertFalse($anotherPoolInstance->getItem('i1')->isHit());
+ $this->assertFalse($anotherPoolInstance->getItem('i3')->isHit());
+ $this->assertTrue($anotherPoolInstance->getItem('foo')->isHit());
+ }
+
+ public function testInvalidateCommits()
+ {
+ $pool1 = $this->createCachePool();
+
+ $foo = $pool1->getItem('foo');
+ $foo->tag('tag');
+
+ $pool1->saveDeferred($foo->set('foo'));
+ $pool1->invalidateTags(['tag']);
+
+ $pool2 = $this->createCachePool();
+ $foo = $pool2->getItem('foo');
+
+ $this->assertTrue($foo->isHit());
}
public function testTagsAreCleanedOnSave()
$i = $pool->getItem('k');
$pool->save($i->tag('bar'));
- $pool->invalidateTags(array('foo'));
+ $pool->invalidateTags(['foo']);
$this->assertTrue($pool->getItem('k')->isHit());
}
$pool->deleteItem('k');
$pool->save($pool->getItem('k'));
- $pool->invalidateTags(array('foo'));
+ $pool->invalidateTags(['foo']);
$this->assertTrue($pool->getItem('k')->isHit());
}
$pool = $this->createCachePool(10);
$item = $pool->getItem('foo');
- $item->tag(array('baz'));
+ $item->tag(['baz']);
$item->expiresAfter(100);
$pool->save($item);
- $pool->invalidateTags(array('baz'));
+ $pool->invalidateTags(['baz']);
$this->assertFalse($pool->getItem('foo')->isHit());
sleep(20);
$pool->save($i->tag('foo'));
$i = $pool->getItem('k');
- $this->assertSame(array('foo' => 'foo'), $i->getPreviousTags());
+ $this->assertSame(['foo' => 'foo'], $i->getPreviousTags());
}
public function testPrune()
$this->assertFalse($cache->prune());
}
+ public function testKnownTagVersionsTtl()
+ {
+ $itemsPool = new FilesystemAdapter('', 10);
+ $tagsPool = $this
+ ->getMockBuilder(AdapterInterface::class)
+ ->getMock();
+
+ $pool = new TagAwareAdapter($itemsPool, $tagsPool, 10);
+
+ $item = $pool->getItem('foo');
+ $item->tag(['baz']);
+ $item->expiresAfter(100);
+
+ $tag = $this->getMockBuilder(CacheItemInterface::class)->getMock();
+ $tag->expects(self::exactly(2))->method('get')->willReturn(10);
+
+ $tagsPool->expects(self::exactly(2))->method('getItems')->willReturn([
+ 'baz'.TagAwareAdapter::TAGS_PREFIX => $tag,
+ ]);
+
+ $pool->save($item);
+ $this->assertTrue($pool->getItem('foo')->isHit());
+ $this->assertTrue($pool->getItem('foo')->isHit());
+
+ sleep(20);
+
+ $this->assertTrue($pool->getItem('foo')->isHit());
+
+ sleep(5);
+
+ $this->assertTrue($pool->getItem('foo')->isHit());
+ }
+
+ public function testTagEntryIsCreatedForItemWithoutTags()
+ {
+ $pool = $this->createCachePool();
+
+ $itemKey = 'foo';
+ $item = $pool->getItem($itemKey);
+ $pool->save($item);
+
+ $adapter = new FilesystemAdapter();
+ $this->assertTrue($adapter->hasItem(TagAwareAdapter::TAGS_PREFIX.$itemKey));
+ }
+
+ public function testHasItemReturnsFalseWhenPoolDoesNotHaveItemTags()
+ {
+ $pool = $this->createCachePool();
+
+ $itemKey = 'foo';
+ $item = $pool->getItem($itemKey);
+ $pool->save($item);
+
+ $anotherPool = $this->createCachePool();
+
+ $adapter = new FilesystemAdapter();
+ $adapter->deleteItem(TagAwareAdapter::TAGS_PREFIX.$itemKey); //simulate item losing tags pair
+
+ $this->assertFalse($anotherPool->hasItem($itemKey));
+ }
+
+ public function testGetItemReturnsCacheMissWhenPoolDoesNotHaveItemTags()
+ {
+ $pool = $this->createCachePool();
+
+ $itemKey = 'foo';
+ $item = $pool->getItem($itemKey);
+ $pool->save($item);
+
+ $anotherPool = $this->createCachePool();
+
+ $adapter = new FilesystemAdapter();
+ $adapter->deleteItem(TagAwareAdapter::TAGS_PREFIX.$itemKey); //simulate item losing tags pair
+
+ $item = $anotherPool->getItem($itemKey);
+ $this->assertFalse($item->isHit());
+ }
+
+ public function testHasItemReturnsFalseWhenPoolDoesNotHaveItemAndOnlyHasTags()
+ {
+ $pool = $this->createCachePool();
+
+ $itemKey = 'foo';
+ $item = $pool->getItem($itemKey);
+ $pool->save($item);
+
+ $anotherPool = $this->createCachePool();
+
+ $adapter = new FilesystemAdapter();
+ $adapter->deleteItem($itemKey); //simulate losing item but keeping tags
+
+ $this->assertFalse($anotherPool->hasItem($itemKey));
+ }
+
+ public function testInvalidateTagsWithArrayAdapter()
+ {
+ $adapter = new TagAwareAdapter(new ArrayAdapter());
+
+ $item = $adapter->getItem('foo');
+
+ $this->assertFalse($item->isHit());
+
+ $item->tag('bar');
+ $item->expiresAfter(100);
+ $adapter->save($item);
+
+ $this->assertTrue($adapter->getItem('foo')->isHit());
+
+ $adapter->invalidateTags(['bar']);
+
+ $this->assertFalse($adapter->getItem('foo')->isHit());
+ }
+
+ public function testGetItemReturnsCacheMissWhenPoolDoesNotHaveItemAndOnlyHasTags()
+ {
+ $pool = $this->createCachePool();
+
+ $itemKey = 'foo';
+ $item = $pool->getItem($itemKey);
+ $pool->save($item);
+
+ $anotherPool = $this->createCachePool();
+
+ $adapter = new FilesystemAdapter();
+ $adapter->deleteItem($itemKey); //simulate losing item but keeping tags
+
+ $item = $anotherPool->getItem($itemKey);
+ $this->assertFalse($item->isHit());
+ }
+
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface
+ * @return MockObject|PruneableCacheInterface
*/
private function getPruneableMock()
{
$pruneable
->expects($this->atLeastOnce())
->method('prune')
- ->will($this->returnValue(true));
+ ->willReturn(true);
return $pruneable;
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface
+ * @return MockObject|PruneableCacheInterface
*/
private function getFailingPruneableMock()
{
$pruneable
->expects($this->atLeastOnce())
->method('prune')
- ->will($this->returnValue(false));
+ ->willReturn(false);
return $pruneable;
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|AdapterInterface
+ * @return MockObject|AdapterInterface
*/
private function getNonPruneableMock()
{
--- /dev/null
+<?php
+
+namespace Symfony\Component\Cache\Tests\Adapter;
+
+use PHPUnit\Framework\TestCase;
+use Psr\Cache\CacheItemPoolInterface;
+use Symfony\Component\Cache\Adapter\ArrayAdapter;
+use Symfony\Component\Cache\Adapter\ProxyAdapter;
+use Symfony\Component\Cache\Adapter\TagAwareAdapter;
+use Symfony\Component\Cache\Tests\Fixtures\ExternalAdapter;
+
+class TagAwareAndProxyAdapterIntegrationTest extends TestCase
+{
+ /**
+ * @dataProvider dataProvider
+ */
+ public function testIntegrationUsingProxiedAdapter(CacheItemPoolInterface $proxiedAdapter)
+ {
+ $cache = new TagAwareAdapter(new ProxyAdapter($proxiedAdapter));
+
+ $item = $cache->getItem('foo');
+ $item->tag(['tag1', 'tag2']);
+ $item->set('bar');
+ $cache->save($item);
+
+ $this->assertSame('bar', $cache->getItem('foo')->get());
+ }
+
+ public function dataProvider()
+ {
+ return [
+ [new ArrayAdapter()],
+ // also testing with a non-AdapterInterface implementation
+ // because the ProxyAdapter behaves slightly different for those
+ [new ExternalAdapter()],
+ ];
+ }
+}
*/
class TraceableAdapterTest extends AdapterTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testPrune' => 'TraceableAdapter just proxies',
- );
+ ];
public function createCachePool($defaultLifetime = 0)
{
$call = $calls[0];
$this->assertSame('getItem', $call->name);
- $this->assertSame(array('k' => false), $call->result);
+ $this->assertSame(['k' => false], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(1, $call->misses);
$this->assertNotEmpty($call->start);
public function testGetItemsMissTrace()
{
$pool = $this->createCachePool();
- $arg = array('k0', 'k1');
+ $arg = ['k0', 'k1'];
$items = $pool->getItems($arg);
foreach ($items as $item) {
}
$call = $calls[0];
$this->assertSame('getItems', $call->name);
- $this->assertSame(array('k0' => false, 'k1' => false), $call->result);
+ $this->assertSame(['k0' => false, 'k1' => false], $call->result);
$this->assertSame(2, $call->misses);
$this->assertNotEmpty($call->start);
$this->assertNotEmpty($call->end);
$call = $calls[0];
$this->assertSame('hasItem', $call->name);
- $this->assertSame(array('k' => false), $call->result);
+ $this->assertSame(['k' => false], $call->result);
$this->assertNotEmpty($call->start);
$this->assertNotEmpty($call->end);
}
$call = $calls[2];
$this->assertSame('hasItem', $call->name);
- $this->assertSame(array('k' => true), $call->result);
+ $this->assertSame(['k' => true], $call->result);
$this->assertNotEmpty($call->start);
$this->assertNotEmpty($call->end);
}
$call = $calls[0];
$this->assertSame('deleteItem', $call->name);
- $this->assertSame(array('k' => true), $call->result);
+ $this->assertSame(['k' => true], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(0, $call->misses);
$this->assertNotEmpty($call->start);
public function testDeleteItemsTrace()
{
$pool = $this->createCachePool();
- $arg = array('k0', 'k1');
+ $arg = ['k0', 'k1'];
$pool->deleteItems($arg);
$calls = $pool->getCalls();
$this->assertCount(1, $calls);
$call = $calls[0];
$this->assertSame('deleteItems', $call->name);
- $this->assertSame(array('keys' => $arg, 'result' => true), $call->result);
+ $this->assertSame(['keys' => $arg, 'result' => true], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(0, $call->misses);
$this->assertNotEmpty($call->start);
$call = $calls[1];
$this->assertSame('save', $call->name);
- $this->assertSame(array('k' => true), $call->result);
+ $this->assertSame(['k' => true], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(0, $call->misses);
$this->assertNotEmpty($call->start);
$call = $calls[1];
$this->assertSame('saveDeferred', $call->name);
- $this->assertSame(array('k' => true), $call->result);
+ $this->assertSame(['k' => true], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(0, $call->misses);
$this->assertNotEmpty($call->start);
public function testInvalidateTags()
{
$pool = new TraceableTagAwareAdapter(new TagAwareAdapter(new FilesystemAdapter()));
- $pool->invalidateTags(array('foo'));
+ $pool->invalidateTags(['foo']);
$calls = $pool->getCalls();
$this->assertCount(1, $calls);
/**
* @dataProvider provideInvalidKey
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage Cache key
*/
public function testInvalidKey($key)
{
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('Cache key');
CacheItem::validateKey($key);
}
public function provideInvalidKey()
{
- return array(
- array(''),
- array('{'),
- array('}'),
- array('('),
- array(')'),
- array('/'),
- array('\\'),
- array('@'),
- array(':'),
- array(true),
- array(null),
- array(1),
- array(1.1),
- array(array(array())),
- array(new \Exception('foo')),
- );
+ return [
+ [''],
+ ['{'],
+ ['}'],
+ ['('],
+ [')'],
+ ['/'],
+ ['\\'],
+ ['@'],
+ [':'],
+ [true],
+ [null],
+ [1],
+ [1.1],
+ [[[]]],
+ [new \Exception('foo')],
+ ];
}
public function testTag()
$item = new CacheItem();
$this->assertSame($item, $item->tag('foo'));
- $this->assertSame($item, $item->tag(array('bar', 'baz')));
+ $this->assertSame($item, $item->tag(['bar', 'baz']));
- call_user_func(\Closure::bind(function () use ($item) {
- $this->assertSame(array('foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'), $item->tags);
+ \call_user_func(\Closure::bind(function () use ($item) {
+ $this->assertSame(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'], $item->tags);
}, $this, CacheItem::class));
}
/**
* @dataProvider provideInvalidKey
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage Cache tag
*/
public function testInvalidTag($tag)
{
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('Cache tag');
$item = new CacheItem();
$item->tag($tag);
}
class ArrayCache extends CacheProvider
{
- private $data = array();
+ private $data = [];
protected function doFetch($id)
{
$expiry = $this->data[$id][1];
- return !$expiry || time() <= $expiry || !$this->doDelete($id);
+ return !$expiry || time() < $expiry || !$this->doDelete($id);
}
protected function doSave($id, $data, $lifeTime = 0)
{
- $this->data[$id] = array($data, $lifeTime ? time() + $lifeTime : false);
+ $this->data[$id] = [$data, $lifeTime ? time() + $lifeTime : false];
return true;
}
protected function doFlush()
{
- $this->data = array();
+ $this->data = [];
return true;
}
{
private $cache;
- public function __construct()
+ public function __construct($defaultLifetime = 0)
{
- $this->cache = new ArrayAdapter();
+ $this->cache = new ArrayAdapter($defaultLifetime);
}
public function getItem($key)
return $this->cache->getItem($key);
}
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
return $this->cache->getItems($keys);
}
abstract class AbstractRedisCacheTest extends CacheTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testSetTtl' => 'Testing expiration slows down the test suite',
'testSetMultipleTtl' => 'Testing expiration slows down the test suite',
'testDefaultLifeTime' => 'Testing expiration slows down the test suite',
- );
+ ];
protected static $redis;
return new RedisCache(self::$redis, str_replace('\\', '.', __CLASS__), $defaultLifetime);
}
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
- if (!extension_loaded('redis')) {
+ if (!\extension_loaded('redis')) {
self::markTestSkipped('Extension redis required.');
}
- if (!@((new \Redis())->connect(getenv('REDIS_HOST')))) {
- $e = error_get_last();
- self::markTestSkipped($e['message']);
+ try {
+ (new \Redis())->connect(getenv('REDIS_HOST'));
+ } catch (\Exception $e) {
+ self::markTestSkipped($e->getMessage());
}
}
class ApcuCacheTest extends CacheTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testSetTtl' => 'Testing expiration slows down the test suite',
'testSetMultipleTtl' => 'Testing expiration slows down the test suite',
'testDefaultLifeTime' => 'Testing expiration slows down the test suite',
- );
+ ];
public function createSimpleCache($defaultLifetime = 0)
{
- if (!function_exists('apcu_fetch') || !ini_get('apc.enabled') || ('cli' === PHP_SAPI && !ini_get('apc.enable_cli'))) {
+ if (!\function_exists('apcu_fetch') || !filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN) || ('cli' === \PHP_SAPI && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN))) {
$this->markTestSkipped('APCu extension is required.');
}
- if ('\\' === DIRECTORY_SEPARATOR) {
+ if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Fails transiently on Windows.');
}
{
parent::setUp();
- if (!array_key_exists('testPrune', $this->skippedTests) && !$this->createSimpleCache() instanceof PruneableInterface) {
+ if (!\array_key_exists('testPrune', $this->skippedTests) && !$this->createSimpleCache() instanceof PruneableInterface) {
$this->skippedTests['testPrune'] = 'Not a pruneable cache pool.';
}
}
public static function validKeys()
{
- if (defined('HHVM_VERSION')) {
+ if (\defined('HHVM_VERSION')) {
return parent::validKeys();
}
- return array_merge(parent::validKeys(), array(array("a\0b")));
+ return array_merge(parent::validKeys(), [["a\0b"]]);
}
public function testDefaultLifeTime()
}
$cache = $this->createSimpleCache(2);
+ $cache->clear();
$cache->set('key.dlt', 'value');
sleep(1);
sleep(2);
$this->assertNull($cache->get('key.dlt'));
+
+ $cache->clear();
}
public function testNotUnserializable()
}
$cache = $this->createSimpleCache();
+ $cache->clear();
$cache->set('foo', new NotUnserializable());
$this->assertNull($cache->get('foo'));
- $cache->setMultiple(array('foo' => new NotUnserializable()));
+ $cache->setMultiple(['foo' => new NotUnserializable()]);
- foreach ($cache->getMultiple(array('foo')) as $value) {
+ foreach ($cache->getMultiple(['foo']) as $value) {
}
$this->assertNull($value);
+
+ $cache->clear();
}
public function testPrune()
/** @var PruneableInterface|CacheInterface $cache */
$cache = $this->createSimpleCache();
+ $cache->clear();
$cache->set('foo', 'foo-val', new \DateInterval('PT05S'));
$cache->set('bar', 'bar-val', new \DateInterval('PT10S'));
$cache->prune();
$this->assertFalse($this->isPruned($cache, 'foo'));
$this->assertTrue($this->isPruned($cache, 'qux'));
+
+ $cache->clear();
}
}
namespace Symfony\Component\Cache\Tests\Simple;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Cache\Simple\ArrayCache;
{
public function createSimpleCache($defaultLifetime = 0)
{
- return new ChainCache(array(new ArrayCache($defaultLifetime), new FilesystemCache('', $defaultLifetime)), $defaultLifetime);
+ return new ChainCache([new ArrayCache($defaultLifetime), new FilesystemCache('', $defaultLifetime)], $defaultLifetime);
}
- /**
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage At least one cache must be specified.
- */
public function testEmptyCachesException()
{
- new ChainCache(array());
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('At least one cache must be specified.');
+ new ChainCache([]);
}
- /**
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage The class "stdClass" does not implement
- */
public function testInvalidCacheException()
{
- new ChainCache(array(new \stdClass()));
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('The class "stdClass" does not implement');
+ new ChainCache([new \stdClass()]);
}
public function testPrune()
$this->markTestSkipped($this->skippedTests[__FUNCTION__]);
}
- $cache = new ChainCache(array(
+ $cache = new ChainCache([
$this->getPruneableMock(),
$this->getNonPruneableMock(),
$this->getPruneableMock(),
- ));
+ ]);
$this->assertTrue($cache->prune());
- $cache = new ChainCache(array(
+ $cache = new ChainCache([
$this->getPruneableMock(),
$this->getFailingPruneableMock(),
$this->getPruneableMock(),
- ));
+ ]);
$this->assertFalse($cache->prune());
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface
+ * @return MockObject|PruneableCacheInterface
*/
private function getPruneableMock()
{
$pruneable
->expects($this->atLeastOnce())
->method('prune')
- ->will($this->returnValue(true));
+ ->willReturn(true);
return $pruneable;
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface
+ * @return MockObject|PruneableCacheInterface
*/
private function getFailingPruneableMock()
{
$pruneable
->expects($this->atLeastOnce())
->method('prune')
- ->will($this->returnValue(false));
+ ->willReturn(false);
return $pruneable;
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|CacheInterface
+ * @return MockObject|CacheInterface
*/
private function getNonPruneableMock()
{
*/
class DoctrineCacheTest extends CacheTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testObjectDoesNotChangeInCache' => 'ArrayCache does not use serialize/unserialize',
'testNotUnserializable' => 'ArrayCache does not use serialize/unserialize',
- );
+ ];
public function createSimpleCache($defaultLifetime = 0)
{
class MemcachedCacheTest extends CacheTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testSetTtl' => 'Testing expiration slows down the test suite',
'testSetMultipleTtl' => 'Testing expiration slows down the test suite',
'testDefaultLifeTime' => 'Testing expiration slows down the test suite',
- );
+ ];
protected static $client;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
if (!MemcachedCache::isSupported()) {
self::markTestSkipped('Extension memcached >=2.2.0 required.');
public function createSimpleCache($defaultLifetime = 0)
{
- $client = $defaultLifetime ? AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST'), array('binary_protocol' => false)) : self::$client;
+ $client = $defaultLifetime ? AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['binary_protocol' => false]) : self::$client;
return new MemcachedCache($client, str_replace('\\', '.', __CLASS__), $defaultLifetime);
}
+ public function testCreatePersistentConnectionShouldNotDupServerList()
+ {
+ $instance = MemcachedCache::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['persistent_id' => 'persistent']);
+ $this->assertCount(1, $instance->getServerList());
+
+ $instance = MemcachedCache::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['persistent_id' => 'persistent']);
+ $this->assertCount(1, $instance->getServerList());
+ }
+
public function testOptions()
{
- $client = MemcachedCache::createConnection(array(), array(
+ $client = MemcachedCache::createConnection([], [
'libketama_compatible' => false,
'distribution' => 'modula',
'compression' => true,
'serializer' => 'php',
'hash' => 'md5',
- ));
+ ]);
$this->assertSame(\Memcached::SERIALIZER_PHP, $client->getOption(\Memcached::OPT_SERIALIZER));
$this->assertSame(\Memcached::HASH_MD5, $client->getOption(\Memcached::OPT_HASH));
/**
* @dataProvider provideBadOptions
- * @expectedException \ErrorException
- * @expectedExceptionMessage constant(): Couldn't find constant Memcached::
*/
public function testBadOptions($name, $value)
{
- MemcachedCache::createConnection(array(), array($name => $value));
+ if (\PHP_VERSION_ID < 80000) {
+ $this->expectException('ErrorException');
+ $this->expectExceptionMessage('constant(): Couldn\'t find constant Memcached::');
+ } else {
+ $this->expectException('Error');
+ $this->expectExceptionMessage('Undefined constant Memcached::');
+ }
+
+ MemcachedCache::createConnection([], [$name => $value]);
}
public function provideBadOptions()
{
- return array(
- array('foo', 'bar'),
- array('hash', 'zyx'),
- array('serializer', 'zyx'),
- array('distribution', 'zyx'),
- );
+ return [
+ ['foo', 'bar'],
+ ['hash', 'zyx'],
+ ['serializer', 'zyx'],
+ ['distribution', 'zyx'],
+ ];
}
public function testDefaultOptions()
{
$this->assertTrue(MemcachedCache::isSupported());
- $client = MemcachedCache::createConnection(array());
+ $client = MemcachedCache::createConnection([]);
$this->assertTrue($client->getOption(\Memcached::OPT_COMPRESSION));
$this->assertSame(1, $client->getOption(\Memcached::OPT_BINARY_PROTOCOL));
$this->assertSame(1, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE));
}
- /**
- * @expectedException \Symfony\Component\Cache\Exception\CacheException
- * @expectedExceptionMessage MemcachedAdapter: "serializer" option must be "php" or "igbinary".
- */
public function testOptionSerializer()
{
+ $this->expectException('Symfony\Component\Cache\Exception\CacheException');
+ $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
if (!\Memcached::HAVE_JSON) {
$this->markTestSkipped('Memcached::HAVE_JSON required');
}
- new MemcachedCache(MemcachedCache::createConnection(array(), array('serializer' => 'json')));
+ new MemcachedCache(MemcachedCache::createConnection([], ['serializer' => 'json']));
}
/**
public function testServersSetting($dsn, $host, $port)
{
$client1 = MemcachedCache::createConnection($dsn);
- $client2 = MemcachedCache::createConnection(array($dsn));
- $client3 = MemcachedCache::createConnection(array(array($host, $port)));
- $expect = array(
+ $client2 = MemcachedCache::createConnection([$dsn]);
+ $client3 = MemcachedCache::createConnection([[$host, $port]]);
+ $expect = [
'host' => $host,
'port' => $port,
- );
+ ];
- $f = function ($s) { return array('host' => $s['host'], 'port' => $s['port']); };
- $this->assertSame(array($expect), array_map($f, $client1->getServerList()));
- $this->assertSame(array($expect), array_map($f, $client2->getServerList()));
- $this->assertSame(array($expect), array_map($f, $client3->getServerList()));
+ $f = function ($s) { return ['host' => $s['host'], 'port' => $s['port']]; };
+ $this->assertSame([$expect], array_map($f, $client1->getServerList()));
+ $this->assertSame([$expect], array_map($f, $client2->getServerList()));
+ $this->assertSame([$expect], array_map($f, $client3->getServerList()));
}
public function provideServersSetting()
{
- yield array(
+ yield [
'memcached://127.0.0.1/50',
'127.0.0.1',
11211,
- );
- yield array(
+ ];
+ yield [
'memcached://localhost:11222?weight=25',
'localhost',
11222,
- );
- if (ini_get('memcached.use_sasl')) {
- yield array(
+ ];
+ if (filter_var(ini_get('memcached.use_sasl'), \FILTER_VALIDATE_BOOLEAN)) {
+ yield [
'memcached://user:password@127.0.0.1?weight=50',
'127.0.0.1',
11211,
- );
+ ];
}
- yield array(
+ yield [
'memcached:///var/run/memcached.sock?weight=25',
'/var/run/memcached.sock',
0,
- );
- yield array(
+ ];
+ yield [
'memcached:///var/local/run/memcached.socket?weight=25',
'/var/local/run/memcached.socket',
0,
- );
- if (ini_get('memcached.use_sasl')) {
- yield array(
+ ];
+ if (filter_var(ini_get('memcached.use_sasl'), \FILTER_VALIDATE_BOOLEAN)) {
+ yield [
'memcached://user:password@/var/local/run/memcached.socket?weight=25',
'/var/local/run/memcached.socket',
0,
- );
+ ];
}
}
}
--- /dev/null
+<?php
+
+/*
+ * This file is part of the Symfony package.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Component\Cache\Tests\Simple;
+
+use Symfony\Component\Cache\Adapter\AbstractAdapter;
+use Symfony\Component\Cache\Simple\MemcachedCache;
+
+class MemcachedCacheTextModeTest extends MemcachedCacheTest
+{
+ public function createSimpleCache($defaultLifetime = 0)
+ {
+ $client = AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['binary_protocol' => false]);
+
+ return new MemcachedCache($client, str_replace('\\', '.', __CLASS__), $defaultLifetime);
+ }
+}
{
$cache = $this->createCachePool();
- $keys = array('foo', 'bar', 'baz', 'biz');
+ $keys = ['foo', 'bar', 'baz', 'biz'];
$default = new \stdClass();
$items = $cache->getMultiple($keys, $default);
public function testDeleteMultiple()
{
- $this->assertTrue($this->createCachePool()->deleteMultiple(array('key', 'foo', 'bar')));
+ $this->assertTrue($this->createCachePool()->deleteMultiple(['key', 'foo', 'bar']));
}
public function testSet()
{
$cache = $this->createCachePool();
- $this->assertFalse($cache->setMultiple(array('key' => 'val')));
+ $this->assertFalse($cache->setMultiple(['key' => 'val']));
$this->assertNull($cache->get('key'));
}
}
protected static $dbFile;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
- if (!extension_loaded('pdo_sqlite')) {
+ if (!\extension_loaded('pdo_sqlite')) {
self::markTestSkipped('Extension pdo_sqlite required.');
}
protected static $dbFile;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
- if (!extension_loaded('pdo_sqlite')) {
+ if (!\extension_loaded('pdo_sqlite')) {
self::markTestSkipped('Extension pdo_sqlite required.');
}
self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache');
- $pool = new PdoCache(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile)));
+ $pool = new PdoCache(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile]));
$pool->createTable();
}
public function createSimpleCache($defaultLifetime = 0)
{
- return new PdoCache(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile)), '', $defaultLifetime);
+ return new PdoCache(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile]), '', $defaultLifetime);
}
}
namespace Symfony\Component\Cache\Tests\Simple;
-use Symfony\Component\Cache\Tests\Adapter\FilesystemAdapterTest;
use Symfony\Component\Cache\Simple\NullCache;
use Symfony\Component\Cache\Simple\PhpArrayCache;
+use Symfony\Component\Cache\Tests\Adapter\FilesystemAdapterTest;
/**
* @group time-sensitive
*/
class PhpArrayCacheTest extends CacheTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testBasicUsageWithLongKey' => 'PhpArrayCache does no writes',
'testDelete' => 'PhpArrayCache does no writes',
'testDefaultLifeTime' => 'PhpArrayCache does not allow configuring a default lifetime.',
'testPrune' => 'PhpArrayCache just proxies',
- );
+ ];
protected static $file;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php';
}
protected function tearDown()
{
+ $this->createSimpleCache()->clear();
+
if (file_exists(sys_get_temp_dir().'/symfony-cache')) {
FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache');
}
public function testStore()
{
- $arrayWithRefs = array();
+ $arrayWithRefs = [];
$arrayWithRefs[0] = 123;
$arrayWithRefs[1] = &$arrayWithRefs[0];
- $object = (object) array(
+ $object = (object) [
'foo' => 'bar',
'foo2' => 'bar2',
- );
+ ];
- $expected = array(
+ $expected = [
'null' => null,
'serializedString' => serialize($object),
'arrayWithRefs' => $arrayWithRefs,
'object' => $object,
- 'arrayWithObject' => array('bar' => $object),
- );
+ 'arrayWithObject' => ['bar' => $object],
+ ];
$cache = new PhpArrayCache(self::$file, new NullCache());
$cache->warmUp($expected);
public function testStoredFile()
{
- $expected = array(
+ $expected = [
'integer' => 42,
'float' => 42.42,
'boolean' => true,
- 'array_simple' => array('foo', 'bar'),
- 'array_associative' => array('foo' => 'bar', 'foo2' => 'bar2'),
- );
+ 'array_simple' => ['foo', 'bar'],
+ 'array_associative' => ['foo' => 'bar', 'foo2' => 'bar2'],
+ ];
$cache = new PhpArrayCache(self::$file, new NullCache());
$cache->warmUp($expected);
{
public function set($key, $value, $ttl = null)
{
- call_user_func(\Closure::bind(function () use ($key, $value) {
+ \call_user_func(\Closure::bind(function () use ($key, $value) {
$this->values[$key] = $value;
$this->warmUp($this->values);
$this->values = eval(substr(file_get_contents($this->file), 6));
public function setMultiple($values, $ttl = null)
{
- if (!is_array($values) && !$values instanceof \Traversable) {
+ if (!\is_array($values) && !$values instanceof \Traversable) {
return parent::setMultiple($values, $ttl);
}
- call_user_func(\Closure::bind(function () use ($values) {
+ \call_user_func(\Closure::bind(function () use ($values) {
foreach ($values as $key => $value) {
$this->values[$key] = $value;
}
*/
class PhpArrayCacheWithFallbackTest extends CacheTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testGetInvalidKeys' => 'PhpArrayCache does no validation',
'testGetMultipleInvalidKeys' => 'PhpArrayCache does no validation',
'testDeleteInvalidKeys' => 'PhpArrayCache does no validation',
'testSetMultipleInvalidTtl' => 'PhpArrayCache does no validation',
'testHasInvalidKeys' => 'PhpArrayCache does no validation',
'testPrune' => 'PhpArrayCache just proxies',
- );
+ ];
protected static $file;
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php';
}
protected function tearDown()
{
+ $this->createSimpleCache()->clear();
+
if (file_exists(sys_get_temp_dir().'/symfony-cache')) {
FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache');
}
*/
class PhpFilesCacheTest extends CacheTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testDefaultLifeTime' => 'PhpFilesCache does not allow configuring a default lifetime.',
- );
+ ];
public function createSimpleCache()
{
*/
class Psr6CacheTest extends CacheTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testPrune' => 'Psr6Cache just proxies',
- );
+ ];
public function createSimpleCache($defaultLifetime = 0)
{
class RedisArrayCacheTest extends AbstractRedisCacheTest
{
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
parent::setupBeforeClass();
if (!class_exists('RedisArray')) {
self::markTestSkipped('The RedisArray class is required.');
}
- self::$redis = new \RedisArray(array(getenv('REDIS_HOST')), array('lazy_connect' => true));
+ self::$redis = new \RedisArray([getenv('REDIS_HOST')], ['lazy_connect' => true]);
}
}
class RedisCacheTest extends AbstractRedisCacheTest
{
- public static function setupBeforeClass()
+ public static function setUpBeforeClass()
{
parent::setupBeforeClass();
self::$redis = RedisCache::createConnection('redis://'.getenv('REDIS_HOST'));
$redis = RedisCache::createConnection('redis://'.$redisHost.'/2');
$this->assertSame(2, $redis->getDbNum());
- $redis = RedisCache::createConnection('redis://'.$redisHost, array('timeout' => 3));
+ $redis = RedisCache::createConnection('redis://'.$redisHost, ['timeout' => 3]);
$this->assertEquals(3, $redis->getTimeout());
$redis = RedisCache::createConnection('redis://'.$redisHost.'?timeout=4');
$this->assertEquals(4, $redis->getTimeout());
- $redis = RedisCache::createConnection('redis://'.$redisHost, array('read_timeout' => 5));
+ $redis = RedisCache::createConnection('redis://'.$redisHost, ['read_timeout' => 5]);
$this->assertEquals(5, $redis->getReadTimeout());
}
/**
* @dataProvider provideFailedCreateConnection
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage Redis connection failed
*/
public function testFailedCreateConnection($dsn)
{
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('Redis connection ');
RedisCache::createConnection($dsn);
}
public function provideFailedCreateConnection()
{
- return array(
- array('redis://localhost:1234'),
- array('redis://foo@localhost'),
- array('redis://localhost/123'),
- );
+ return [
+ ['redis://localhost:1234'],
+ ['redis://foo@localhost'],
+ ['redis://localhost/123'],
+ ];
}
/**
* @dataProvider provideInvalidCreateConnection
- * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException
- * @expectedExceptionMessage Invalid Redis DSN
*/
public function testInvalidCreateConnection($dsn)
{
+ $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
+ $this->expectExceptionMessage('Invalid Redis DSN');
RedisCache::createConnection($dsn);
}
public function provideInvalidCreateConnection()
{
- return array(
- array('foo://localhost'),
- array('redis://'),
- );
+ return [
+ ['foo://localhost'],
+ ['redis://'],
+ ];
}
}
--- /dev/null
+<?php
+
+/*
+ * This file is part of the Symfony package.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Component\Cache\Tests\Simple;
+
+class RedisClusterCacheTest extends AbstractRedisCacheTest
+{
+ public static function setUpBeforeClass()
+ {
+ if (!class_exists('RedisCluster')) {
+ self::markTestSkipped('The RedisCluster class is required.');
+ }
+ if (!$hosts = getenv('REDIS_CLUSTER_HOSTS')) {
+ self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.');
+ }
+
+ self::$redis = new \RedisCluster(null, explode(' ', $hosts));
+ }
+}
*/
class TraceableCacheTest extends CacheTestCase
{
- protected $skippedTests = array(
+ protected $skippedTests = [
'testPrune' => 'TraceableCache just proxies',
- );
+ ];
public function createSimpleCache($defaultLifetime = 0)
{
$call = $calls[0];
$this->assertSame('get', $call->name);
- $this->assertSame(array('k' => false), $call->result);
+ $this->assertSame(['k' => false], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(1, $call->misses);
$this->assertNotEmpty($call->start);
{
$pool = $this->createSimpleCache();
$pool->set('k1', 123);
- $values = $pool->getMultiple(array('k0', 'k1'));
+ $values = $pool->getMultiple(['k0', 'k1']);
foreach ($values as $value) {
}
$calls = $pool->getCalls();
$call = $calls[1];
$this->assertSame('getMultiple', $call->name);
- $this->assertSame(array('k1' => true, 'k0' => false), $call->result);
+ $this->assertSame(['k1' => true, 'k0' => false], $call->result);
$this->assertSame(1, $call->misses);
$this->assertNotEmpty($call->start);
$this->assertNotEmpty($call->end);
$call = $calls[0];
$this->assertSame('has', $call->name);
- $this->assertSame(array('k' => false), $call->result);
+ $this->assertSame(['k' => false], $call->result);
$this->assertNotEmpty($call->start);
$this->assertNotEmpty($call->end);
}
$call = $calls[1];
$this->assertSame('has', $call->name);
- $this->assertSame(array('k' => true), $call->result);
+ $this->assertSame(['k' => true], $call->result);
$this->assertNotEmpty($call->start);
$this->assertNotEmpty($call->end);
}
$call = $calls[0];
$this->assertSame('delete', $call->name);
- $this->assertSame(array('k' => true), $call->result);
+ $this->assertSame(['k' => true], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(0, $call->misses);
$this->assertNotEmpty($call->start);
public function testDeleteMultipleTrace()
{
$pool = $this->createSimpleCache();
- $arg = array('k0', 'k1');
+ $arg = ['k0', 'k1'];
$pool->deleteMultiple($arg);
$calls = $pool->getCalls();
$this->assertCount(1, $calls);
$call = $calls[0];
$this->assertSame('deleteMultiple', $call->name);
- $this->assertSame(array('keys' => $arg, 'result' => true), $call->result);
+ $this->assertSame(['keys' => $arg, 'result' => true], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(0, $call->misses);
$this->assertNotEmpty($call->start);
$call = $calls[0];
$this->assertSame('set', $call->name);
- $this->assertSame(array('k' => true), $call->result);
+ $this->assertSame(['k' => true], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(0, $call->misses);
$this->assertNotEmpty($call->start);
public function testSetMultipleTrace()
{
$pool = $this->createSimpleCache();
- $pool->setMultiple(array('k' => 'foo'));
+ $pool->setMultiple(['k' => 'foo']);
$calls = $pool->getCalls();
$this->assertCount(1, $calls);
$call = $calls[0];
$this->assertSame('setMultiple', $call->name);
- $this->assertSame(array('keys' => array('k'), 'result' => true), $call->result);
+ $this->assertSame(['keys' => ['k'], 'result' => true], $call->result);
$this->assertSame(0, $call->hits);
$this->assertSame(0, $call->misses);
$this->assertNotEmpty($call->start);
$getPdoConn = $o->getMethod('getConnection');
$getPdoConn->setAccessible(true);
- /** @var \Doctrine\DBAL\Statement $select */
+ /** @var \Doctrine\DBAL\Statement|\PDOStatement $select */
$select = $getPdoConn->invoke($cache)->prepare('SELECT 1 FROM cache_items WHERE item_id LIKE :id');
$select->bindValue(':id', sprintf('%%%s', $name));
- $select->execute();
+ $result = $select->execute();
- return 0 === count($select->fetchAll(\PDO::FETCH_COLUMN));
+ return 1 !== (int) (\is_object($result) ? $result->fetchOne() : $select->fetch(\PDO::FETCH_COLUMN));
}
}
private $namespace;
private $namespaceVersion = '';
private $versioningIsEnabled = false;
- private $deferred = array();
+ private $deferred = [];
/**
* @var int|null The maximum length to enforce for identifiers or null when no limit applies
/**
* Deletes all items in the pool.
*
- * @param string The prefix used for all identifiers managed by this pool
+ * @param string $namespace The prefix used for all identifiers managed by this pool
*
* @return bool True if the pool was successfully cleared, false otherwise
*/
try {
return $this->doHave($id);
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached', array('key' => $key, 'exception' => $e));
+ CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached', ['key' => $key, 'exception' => $e]);
return false;
}
*/
public function clear()
{
+ $this->deferred = [];
if ($cleared = $this->versioningIsEnabled) {
- $this->namespaceVersion = 2;
- foreach ($this->doFetch(array('@'.$this->namespace)) as $v) {
- $this->namespaceVersion = 1 + (int) $v;
+ $namespaceVersion = substr_replace(base64_encode(pack('V', mt_rand())), static::NS_SEPARATOR, 5);
+ try {
+ $cleared = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
+ } catch (\Exception $e) {
+ $cleared = false;
+ }
+ if ($cleared = true === $cleared || [] === $cleared) {
+ $this->namespaceVersion = $namespaceVersion;
}
- $this->namespaceVersion .= ':';
- $cleared = $this->doSave(array('@'.$this->namespace => $this->namespaceVersion), 0);
}
- $this->deferred = array();
try {
return $this->doClear($this->namespace) || $cleared;
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to clear the cache', array('exception' => $e));
+ CacheItem::log($this->logger, 'Failed to clear the cache', ['exception' => $e]);
return false;
}
*/
public function deleteItem($key)
{
- return $this->deleteItems(array($key));
+ return $this->deleteItems([$key]);
}
/**
*/
public function deleteItems(array $keys)
{
- $ids = array();
+ $ids = [];
foreach ($keys as $key) {
$ids[$key] = $this->getId($key);
foreach ($ids as $key => $id) {
try {
$e = null;
- if ($this->doDelete(array($id))) {
+ if ($this->doDelete([$id])) {
continue;
}
} catch (\Exception $e) {
}
- CacheItem::log($this->logger, 'Failed to delete key "{key}"', array('key' => $key, 'exception' => $e));
+ CacheItem::log($this->logger, 'Failed to delete key "{key}"', ['key' => $key, 'exception' => $e]);
$ok = false;
}
if (false !== $value = unserialize($value)) {
return $value;
}
- throw new \DomainException('Failed to unserialize cached value');
+ throw new \DomainException('Failed to unserialize cached value.');
} catch (\Error $e) {
- throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
+ throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
} finally {
ini_set('unserialize_callback_func', $unserializeCallbackHandler);
}
CacheItem::validateKey($key);
if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
- $this->namespaceVersion = '1:';
- foreach ($this->doFetch(array('@'.$this->namespace)) as $v) {
- $this->namespaceVersion = $v;
+ $this->namespaceVersion = '1'.static::NS_SEPARATOR;
+ try {
+ foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
+ $this->namespaceVersion = $v;
+ }
+ if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
+ $this->namespaceVersion = substr_replace(base64_encode(pack('V', time())), static::NS_SEPARATOR, 5);
+ $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
+ }
+ } catch (\Exception $e) {
}
}
if (null === $this->maxIdLength) {
return $this->namespace.$this->namespaceVersion.$key;
}
- if (strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
- $id = $this->namespace.$this->namespaceVersion.substr_replace(base64_encode(hash('sha256', $key, true)), ':', -22);
+ if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
+ $id = $this->namespace.$this->namespaceVersion.substr_replace(base64_encode(hash('sha256', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 22));
}
return $id;
{
public static function isSupported()
{
- return function_exists('apcu_fetch') && ini_get('apc.enabled');
+ return \function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN);
}
private function init($namespace, $defaultLifetime, $version)
{
if (!static::isSupported()) {
- throw new CacheException('APCu is not enabled');
+ throw new CacheException('APCu is not enabled.');
}
- if ('cli' === PHP_SAPI) {
+ if ('cli' === \PHP_SAPI) {
ini_set('apc.use_request_time', 0);
}
parent::__construct($namespace, $defaultLifetime);
protected function doFetch(array $ids)
{
try {
- foreach (apcu_fetch($ids, $ok) ?: array() as $k => $v) {
+ foreach (apcu_fetch($ids, $ok) ?: [] as $k => $v) {
if (null !== $v || $ok) {
yield $k => $v;
}
}
} catch (\Error $e) {
- throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
+ throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
}
}
*/
protected function doClear($namespace)
{
- return isset($namespace[0]) && class_exists('APCuIterator', false) && ('cli' !== PHP_SAPI || ini_get('apc.enable_cli'))
- ? apcu_delete(new \APCuIterator(sprintf('/^%s/', preg_quote($namespace, '/')), APC_ITER_KEY))
+ return isset($namespace[0]) && class_exists('APCuIterator', false) && ('cli' !== \PHP_SAPI || filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN))
+ ? apcu_delete(new \APCuIterator(sprintf('/^%s/', preg_quote($namespace, '/')), \APC_ITER_KEY))
: apcu_clear_cache();
}
} catch (\Exception $e) {
}
- if (1 === count($values)) {
+ if (1 === \count($values)) {
// Workaround https://github.com/krakjoe/apcu/issues/170
apcu_delete(key($values));
}
use LoggerAwareTrait;
private $storeSerialized;
- private $values = array();
- private $expiries = array();
+ private $values = [];
+ private $expiries = [];
/**
* Returns all cached values, with cache miss as null.
{
CacheItem::validateKey($key);
- return isset($this->expiries[$key]) && ($this->expiries[$key] >= time() || !$this->deleteItem($key));
+ return isset($this->expiries[$key]) && ($this->expiries[$key] > time() || !$this->deleteItem($key));
}
/**
*/
public function clear()
{
- $this->values = $this->expiries = array();
+ $this->values = $this->expiries = [];
return true;
}
{
foreach ($keys as $i => $key) {
try {
- if (!$isHit = isset($this->expiries[$key]) && ($this->expiries[$key] >= $now || !$this->deleteItem($key))) {
+ if (!$isHit = isset($this->expiries[$key]) && ($this->expiries[$key] > $now || !$this->deleteItem($key))) {
$this->values[$key] = $value = null;
} elseif (!$this->storeSerialized) {
$value = $this->values[$key];
$isHit = false;
}
} catch (\Exception $e) {
- CacheItem::log($this->logger, 'Failed to unserialize key "{key}"', array('key' => $key, 'exception' => $e));
+ CacheItem::log($this->logger, 'Failed to unserialize key "{key}"', ['key' => $key, 'exception' => $e]);
$this->values[$key] = $value = null;
$isHit = false;
}
case 'unserialize':
case 'apcu_fetch':
case 'apc_fetch':
- throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
+ throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
}
}
if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
throw new InvalidArgumentException(sprintf('Namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
- $directory .= DIRECTORY_SEPARATOR.$namespace;
+ $directory .= \DIRECTORY_SEPARATOR.$namespace;
}
if (!file_exists($directory)) {
@mkdir($directory, 0777, true);
}
- $directory .= DIRECTORY_SEPARATOR;
+ $directory .= \DIRECTORY_SEPARATOR;
// On Windows the whole path is limited to 258 chars
- if ('\\' === DIRECTORY_SEPARATOR && strlen($directory) > 234) {
- throw new InvalidArgumentException(sprintf('Cache directory too long (%s)', $directory));
+ if ('\\' === \DIRECTORY_SEPARATOR && \strlen($directory) > 234) {
+ throw new InvalidArgumentException(sprintf('Cache directory too long (%s).', $directory));
}
$this->directory = $directory;
private function getFile($id, $mkdir = false)
{
$hash = str_replace('/', '-', base64_encode(hash('sha256', static::class.$id, true)));
- $dir = $this->directory.strtoupper($hash[0].DIRECTORY_SEPARATOR.$hash[1].DIRECTORY_SEPARATOR);
+ $dir = $this->directory.strtoupper($hash[0].\DIRECTORY_SEPARATOR.$hash[1].\DIRECTORY_SEPARATOR);
if ($mkdir && !file_exists($dir)) {
@mkdir($dir, 0777, true);
throw new \ErrorException($message, 0, $type, $file, $line);
}
+ public function __sleep()
+ {
+ throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
+ }
+
+ public function __wakeup()
+ {
+ throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
+ }
+
public function __destruct()
{
if (method_exists(parent::class, '__destruct')) {
*/
protected function doFetch(array $ids)
{
- $values = array();
+ $values = [];
$now = time();
foreach ($ids as $id) {
{
$file = $this->getFile($id);
- return file_exists($file) && (@filemtime($file) > time() || $this->doFetch(array($id)));
+ return file_exists($file) && (@filemtime($file) > time() || $this->doFetch([$id]));
}
/**
}
if (!$ok && !is_writable($this->directory)) {
- throw new CacheException(sprintf('Cache directory is not writable (%s)', $this->directory));
+ throw new CacheException(sprintf('Cache directory is not writable (%s).', $this->directory));
}
return $ok;
*/
trait MemcachedTrait
{
- private static $defaultClientOptions = array(
+ private static $defaultClientOptions = [
'persistent_id' => null,
'username' => null,
'password' => null,
- 'serializer' => 'php',
- );
+ \Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_PHP,
+ ];
private $client;
private $lazyClient;
public static function isSupported()
{
- return extension_loaded('memcached') && version_compare(phpversion('memcached'), '2.2.0', '>=');
+ return \extension_loaded('memcached') && version_compare(phpversion('memcached'), '2.2.0', '>=');
}
private function init(\Memcached $client, $namespace, $defaultLifetime)
{
if (!static::isSupported()) {
- throw new CacheException('Memcached >= 2.2.0 is required');
+ throw new CacheException('Memcached >= 2.2.0 is required.');
}
- if ('Memcached' === get_class($client)) {
+ if ('Memcached' === \get_class($client)) {
$opt = $client->getOption(\Memcached::OPT_SERIALIZER);
if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
}
- $this->maxIdLength -= strlen($client->getOption(\Memcached::OPT_PREFIX_KEY));
+ $this->maxIdLength -= \strlen($client->getOption(\Memcached::OPT_PREFIX_KEY));
$this->client = $client;
} else {
$this->lazyClient = $client;
*
* Examples for servers:
* - 'memcached://user:pass@localhost?weight=33'
- * - array(array('localhost', 11211, 33))
+ * - [['localhost', 11211, 33]]
*
- * @param array[]|string|string[] An array of servers, a DSN, or an array of DSNs
- * @param array An array of options
+ * @param array[]|string|string[] $servers An array of servers, a DSN, or an array of DSNs
+ * @param array $options An array of options
*
* @return \Memcached
*
* @throws \ErrorException When invalid options or servers are provided
*/
- public static function createConnection($servers, array $options = array())
+ public static function createConnection($servers, array $options = [])
{
- if (is_string($servers)) {
- $servers = array($servers);
- } elseif (!is_array($servers)) {
- throw new InvalidArgumentException(sprintf('MemcachedAdapter::createClient() expects array or string as first argument, %s given.', gettype($servers)));
+ if (\is_string($servers)) {
+ $servers = [$servers];
+ } elseif (!\is_array($servers)) {
+ throw new InvalidArgumentException(sprintf('MemcachedAdapter::createClient() expects array or string as first argument, "%s" given.', \gettype($servers)));
}
if (!static::isSupported()) {
- throw new CacheException('Memcached >= 2.2.0 is required');
+ throw new CacheException('Memcached >= 2.2.0 is required.');
}
set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); });
try {
// parse any DSN in $servers
foreach ($servers as $i => $dsn) {
- if (is_array($dsn)) {
+ if (\is_array($dsn)) {
continue;
}
if (0 !== strpos($dsn, 'memcached://')) {
- throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s does not start with "memcached://"', $dsn));
+ throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s" does not start with "memcached://".', $dsn));
}
$params = preg_replace_callback('#^memcached://(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) {
if (!empty($m[1])) {
- list($username, $password) = explode(':', $m[1], 2) + array(1 => null);
+ list($username, $password) = explode(':', $m[1], 2) + [1 => null];
}
return 'file://';
}, $dsn);
if (false === $params = parse_url($params)) {
- throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn));
+ throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s".', $dsn));
}
if (!isset($params['host']) && !isset($params['path'])) {
- throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn));
+ throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s".', $dsn));
}
if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
$params['weight'] = $m[1];
- $params['path'] = substr($params['path'], 0, -strlen($m[0]));
+ $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
}
- $params += array(
+ $params += [
'host' => isset($params['host']) ? $params['host'] : $params['path'],
'port' => isset($params['host']) ? 11211 : null,
'weight' => 0,
- );
+ ];
if (isset($params['query'])) {
parse_str($params['query'], $query);
$params += $query;
$options = $query + $options;
}
- $servers[$i] = array($params['host'], $params['port'], $params['weight']);
+ $servers[$i] = [$params['host'], $params['port'], $params['weight']];
}
// set client's options
unset($options['persistent_id'], $options['username'], $options['password'], $options['weight'], $options['lazy']);
- $options = array_change_key_case($options, CASE_UPPER);
+ $options = array_change_key_case($options, \CASE_UPPER);
$client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
$client->setOption(\Memcached::OPT_NO_BLOCK, true);
- if (!array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) {
+ $client->setOption(\Memcached::OPT_TCP_NODELAY, true);
+ if (!\array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !\array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) {
$client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
}
foreach ($options as $name => $value) {
- if (is_int($name)) {
+ if (\is_int($name)) {
continue;
}
if ('HASH' === $name || 'SERIALIZER' === $name || 'DISTRIBUTION' === $name) {
- $value = constant('Memcached::'.$name.'_'.strtoupper($value));
+ $value = \constant('Memcached::'.$name.'_'.strtoupper($value));
}
- $opt = constant('Memcached::OPT_'.$name);
+ $opt = \constant('Memcached::OPT_'.$name);
unset($options[$name]);
$options[$opt] = $value;
// set client's servers, taking care of persistent connections
if (!$client->isPristine()) {
- $oldServers = array();
+ $oldServers = [];
foreach ($client->getServerList() as $server) {
- $oldServers[] = array($server['host'], $server['port']);
+ $oldServers[] = [$server['host'], $server['port']];
}
- $newServers = array();
+ $newServers = [];
foreach ($servers as $server) {
- if (1 < count($server)) {
+ if (1 < \count($server)) {
$server = array_values($server);
unset($server[2]);
$server[1] = (int) $server[1];
}
if ($oldServers !== $newServers) {
- // before resetting, ensure $servers is valid
- $client->addServers($servers);
$client->resetServerList();
+ $client->addServers($servers);
}
+ } else {
+ $client->addServers($servers);
}
- $client->addServers($servers);
if (null !== $username || null !== $password) {
if (!method_exists($client, 'setSaslAuthData')) {
$lifetime += time();
}
- return $this->checkResultCode($this->getClient()->setMulti($values, $lifetime));
+ $encodedValues = [];
+ foreach ($values as $key => $value) {
+ $encodedValues[rawurlencode($key)] = $value;
+ }
+
+ return $this->checkResultCode($this->getClient()->setMulti($encodedValues, $lifetime));
}
/**
{
$unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
try {
- return $this->checkResultCode($this->getClient()->getMulti($ids));
+ $encodedIds = array_map('rawurlencode', $ids);
+
+ $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds));
+
+ $result = [];
+ foreach ($encodedResult as $key => $value) {
+ $result[rawurldecode($key)] = $value;
+ }
+
+ return $result;
} catch (\Error $e) {
- throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
+ throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
} finally {
ini_set('unserialize_callback_func', $unserializeCallbackHandler);
}
*/
protected function doHave($id)
{
- return false !== $this->getClient()->get($id) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode());
+ return false !== $this->getClient()->get(rawurlencode($id)) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode());
}
/**
protected function doDelete(array $ids)
{
$ok = true;
- foreach ($this->checkResultCode($this->getClient()->deleteMulti($ids)) as $result) {
+ $encodedIds = array_map('rawurlencode', $ids);
+ foreach ($this->checkResultCode($this->getClient()->deleteMulti($encodedIds)) as $result) {
if (\Memcached::RES_SUCCESS !== $result && \Memcached::RES_NOTFOUND !== $result) {
$ok = false;
+ break;
}
}
*/
protected function doClear($namespace)
{
- return false;
+ return '' === $namespace && $this->getClient()->flush();
}
private function checkResultCode($result)
return $result;
}
- throw new CacheException(sprintf('MemcachedAdapter client error: %s.', strtolower($this->client->getResultMessage())));
+ throw new CacheException('MemcachedAdapter client error: '.strtolower($this->client->getResultMessage()));
}
/**
namespace Symfony\Component\Cache\Traits;
use Doctrine\DBAL\Connection;
-use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
use Doctrine\DBAL\DBALException;
+use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
use Doctrine\DBAL\Schema\Schema;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
private $timeCol = 'item_time';
private $username = '';
private $password = '';
- private $connectionOptions = array();
+ private $connectionOptions = [];
private $namespace;
private function init($connOrDsn, $namespace, $defaultLifetime, array $options)
if ($connOrDsn instanceof \PDO) {
if (\PDO::ERRMODE_EXCEPTION !== $connOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
- throw new InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION))', __CLASS__));
+ throw new InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)).', __CLASS__));
}
$this->conn = $connOrDsn;
} elseif ($connOrDsn instanceof Connection) {
$this->conn = $connOrDsn;
- } elseif (is_string($connOrDsn)) {
+ } elseif (\is_string($connOrDsn)) {
$this->dsn = $connOrDsn;
} else {
- throw new InvalidArgumentException(sprintf('"%s" requires PDO or Doctrine\DBAL\Connection instance or DSN string as first argument, "%s" given.', __CLASS__, is_object($connOrDsn) ? get_class($connOrDsn) : gettype($connOrDsn)));
+ throw new InvalidArgumentException(sprintf('"%s" requires PDO or Doctrine\DBAL\Connection instance or DSN string as first argument, "%s" given.', __CLASS__, \is_object($connOrDsn) ? \get_class($connOrDsn) : \gettype($connOrDsn)));
}
$this->table = isset($options['db_table']) ? $options['db_table'] : $this->table;
$conn = $this->getConnection();
if ($conn instanceof Connection) {
- $types = array(
+ $types = [
'mysql' => 'binary',
'sqlite' => 'text',
'pgsql' => 'string',
'oci' => 'string',
'sqlsrv' => 'string',
- );
+ ];
if (!isset($types[$this->driver])) {
throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver));
}
$schema = new Schema();
$table = $schema->createTable($this->table);
- $table->addColumn($this->idCol, $types[$this->driver], array('length' => 255));
- $table->addColumn($this->dataCol, 'blob', array('length' => 16777215));
- $table->addColumn($this->lifetimeCol, 'integer', array('unsigned' => true, 'notnull' => false));
- $table->addColumn($this->timeCol, 'integer', array('unsigned' => true));
- $table->setPrimaryKey(array($this->idCol));
+ $table->addColumn($this->idCol, $types[$this->driver], ['length' => 255]);
+ $table->addColumn($this->dataCol, 'blob', ['length' => 16777215]);
+ $table->addColumn($this->lifetimeCol, 'integer', ['unsigned' => true, 'notnull' => false]);
+ $table->addColumn($this->timeCol, 'integer', ['unsigned' => true]);
+ $table->setPrimaryKey([$this->idCol]);
foreach ($schema->toSql($conn->getDatabasePlatform()) as $sql) {
- $conn->exec($sql);
+ if (method_exists($conn, 'executeStatement')) {
+ $conn->executeStatement($sql);
+ } else {
+ $conn->exec($sql);
+ }
}
return;
throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver));
}
- $conn->exec($sql);
+ if (method_exists($conn, 'executeStatement')) {
+ $conn->executeStatement($sql);
+ } else {
+ $conn->exec($sql);
+ }
}
/**
protected function doFetch(array $ids)
{
$now = time();
- $expired = array();
+ $expired = [];
- $sql = str_pad('', (count($ids) << 1) - 1, '?,');
+ $sql = str_pad('', (\count($ids) << 1) - 1, '?,');
$sql = "SELECT $this->idCol, CASE WHEN $this->lifetimeCol IS NULL OR $this->lifetimeCol + $this->timeCol > ? THEN $this->dataCol ELSE NULL END FROM $this->table WHERE $this->idCol IN ($sql)";
$stmt = $this->getConnection()->prepare($sql);
$stmt->bindValue($i = 1, $now, \PDO::PARAM_INT);
foreach ($ids as $id) {
$stmt->bindValue(++$i, $id);
}
- $stmt->execute();
+ $result = $stmt->execute();
+
+ if (\is_object($result)) {
+ $result = $result->iterateNumeric();
+ } else {
+ $stmt->setFetchMode(\PDO::FETCH_NUM);
+ $result = $stmt;
+ }
- while ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
+ foreach ($result as $row) {
if (null === $row[1]) {
$expired[] = $row[0];
} else {
- yield $row[0] => parent::unserialize(is_resource($row[1]) ? stream_get_contents($row[1]) : $row[1]);
+ yield $row[0] => parent::unserialize(\is_resource($row[1]) ? stream_get_contents($row[1]) : $row[1]);
}
}
if ($expired) {
- $sql = str_pad('', (count($expired) << 1) - 1, '?,');
+ $sql = str_pad('', (\count($expired) << 1) - 1, '?,');
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol <= ? AND $this->idCol IN ($sql)";
$stmt = $this->getConnection()->prepare($sql);
$stmt->bindValue($i = 1, $now, \PDO::PARAM_INT);
$stmt->bindValue(':id', $id);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
- $stmt->execute();
+ $result = $stmt->execute();
- return (bool) $stmt->fetchColumn();
+ return (bool) (\is_object($result) ? $result->fetchOne() : $stmt->fetchColumn());
}
/**
$sql = "DELETE FROM $this->table WHERE $this->idCol LIKE '$namespace%'";
}
- $conn->exec($sql);
+ if (method_exists($conn, 'executeStatement')) {
+ $conn->executeStatement($sql);
+ } else {
+ $conn->exec($sql);
+ }
return true;
}
*/
protected function doDelete(array $ids)
{
- $sql = str_pad('', (count($ids) << 1) - 1, '?,');
+ $sql = str_pad('', (\count($ids) << 1) - 1, '?,');
$sql = "DELETE FROM $this->table WHERE $this->idCol IN ($sql)";
$stmt = $this->getConnection()->prepare($sql);
$stmt->execute(array_values($ids));
*/
protected function doSave(array $values, $lifetime)
{
- $serialized = array();
- $failed = array();
+ $serialized = [];
+ $failed = [];
foreach ($values as $id => $value) {
try {
}
foreach ($serialized as $id => $data) {
- $stmt->execute();
+ $result = $stmt->execute();
- if (null === $driver && !$stmt->rowCount()) {
+ if (null === $driver && !(\is_object($result) ? $result->rowCount() : $stmt->rowCount())) {
try {
$insertStmt->execute();
} catch (DBALException $e) {
if ($this->conn instanceof \PDO) {
$this->driver = $this->conn->getAttribute(\PDO::ATTR_DRIVER_NAME);
} else {
- switch ($this->driver = $this->conn->getDriver()->getName()) {
- case 'mysqli':
- case 'pdo_mysql':
- case 'drizzle_pdo_mysql':
+ $driver = $this->conn->getDriver();
+
+ switch (true) {
+ case $driver instanceof \Doctrine\DBAL\Driver\AbstractMySQLDriver:
+ case $driver instanceof \Doctrine\DBAL\Driver\DrizzlePDOMySql\Driver:
+ case $driver instanceof \Doctrine\DBAL\Driver\Mysqli\Driver:
+ case $driver instanceof \Doctrine\DBAL\Driver\PDOMySql\Driver:
+ case $driver instanceof \Doctrine\DBAL\Driver\PDO\MySQL\Driver:
$this->driver = 'mysql';
break;
- case 'pdo_sqlite':
+ case $driver instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver:
+ case $driver instanceof \Doctrine\DBAL\Driver\PDO\SQLite\Driver:
$this->driver = 'sqlite';
break;
- case 'pdo_pgsql':
+ case $driver instanceof \Doctrine\DBAL\Driver\PDOPgSql\Driver:
+ case $driver instanceof \Doctrine\DBAL\Driver\PDO\PgSQL\Driver:
$this->driver = 'pgsql';
break;
- case 'oci8':
- case 'pdo_oracle':
+ case $driver instanceof \Doctrine\DBAL\Driver\OCI8\Driver:
+ case $driver instanceof \Doctrine\DBAL\Driver\PDOOracle\Driver:
+ case $driver instanceof \Doctrine\DBAL\Driver\PDO\OCI\Driver:
$this->driver = 'oci';
break;
- case 'pdo_sqlsrv':
+ case $driver instanceof \Doctrine\DBAL\Driver\SQLSrv\Driver:
+ case $driver instanceof \Doctrine\DBAL\Driver\PDOSqlsrv\Driver:
+ case $driver instanceof \Doctrine\DBAL\Driver\PDO\SQLSrv\Driver:
$this->driver = 'sqlsrv';
break;
+ default:
+ $this->driver = \get_class($driver);
+ break;
}
}
}
private $values;
private $zendDetectUnicode;
+ private static $valuesCache = [];
+
/**
* Store an array of cached values.
*
{
if (file_exists($this->file)) {
if (!is_file($this->file)) {
- throw new InvalidArgumentException(sprintf('Cache path exists and is not a file: %s.', $this->file));
+ throw new InvalidArgumentException(sprintf('Cache path exists and is not a file: "%s".', $this->file));
}
if (!is_writable($this->file)) {
- throw new InvalidArgumentException(sprintf('Cache file is not writable: %s.', $this->file));
+ throw new InvalidArgumentException(sprintf('Cache file is not writable: "%s".', $this->file));
}
} else {
- $directory = dirname($this->file);
+ $directory = \dirname($this->file);
if (!is_dir($directory) && !@mkdir($directory, 0777, true)) {
- throw new InvalidArgumentException(sprintf('Cache directory does not exist and cannot be created: %s.', $directory));
+ throw new InvalidArgumentException(sprintf('Cache directory does not exist and cannot be created: "%s".', $directory));
}
if (!is_writable($directory)) {
- throw new InvalidArgumentException(sprintf('Cache directory is not writable: %s.', $directory));
+ throw new InvalidArgumentException(sprintf('Cache directory is not writable: "%s".', $directory));
}
}
// This file has been auto-generated by the Symfony Cache Component.
-return array(
+return [
EOF;
foreach ($values as $key => $value) {
- CacheItem::validateKey(is_int($key) ? (string) $key : $key);
+ CacheItem::validateKey(\is_int($key) ? (string) $key : $key);
- if (null === $value || is_object($value)) {
+ if (null === $value || \is_object($value)) {
try {
$value = serialize($value);
} catch (\Exception $e) {
- throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable %s value.', $key, get_class($value)), 0, $e);
+ throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable "%s" value.', $key, \get_class($value)), 0, $e);
}
- } elseif (is_array($value)) {
+ } elseif (\is_array($value)) {
try {
$serialized = serialize($value);
$unserialized = unserialize($serialized);
if ($unserialized !== $value || (false !== strpos($serialized, ';R:') && preg_match('/;R:[1-9]/', $serialized))) {
$value = $serialized;
}
- } elseif (is_string($value)) {
+ } elseif (\is_string($value)) {
// Serialize strings if they could be confused with serialized objects or arrays
if ('N;' === $value || (isset($value[2]) && ':' === $value[1])) {
$value = serialize($value);
}
} elseif (!is_scalar($value)) {
- throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable %s value.', $key, gettype($value)));
+ throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable "%s" value.', $key, \gettype($value)));
}
$dump .= var_export($key, true).' => '.var_export($value, true).",\n";
}
- $dump .= "\n);\n";
+ $dump .= "\n];\n";
$dump = str_replace("' . \"\\0\" . '", "\0", $dump);
$tmpFile = uniqid($this->file, true);
unset($serialized, $unserialized, $value, $dump);
@rename($tmpFile, $this->file);
+ unset(self::$valuesCache[$this->file]);
$this->initialize();
}
*/
public function clear()
{
- $this->values = array();
+ $this->values = [];
$cleared = @unlink($this->file) || !file_exists($this->file);
+ unset(self::$valuesCache[$this->file]);
return $this->pool->clear() && $cleared;
}
*/
private function initialize()
{
+ if (isset(self::$valuesCache[$this->file])) {
+ $this->values = self::$valuesCache[$this->file];
+
+ return;
+ }
+
if ($this->zendDetectUnicode) {
$zmb = ini_set('zend.detect_unicode', 0);
}
try {
- $this->values = file_exists($this->file) ? (include $this->file ?: array()) : array();
+ $this->values = self::$valuesCache[$this->file] = file_exists($this->file) ? (include $this->file ?: []) : [];
} finally {
if ($this->zendDetectUnicode) {
ini_set('zend.detect_unicode', $zmb);
public static function isSupported()
{
- return function_exists('opcache_invalidate') && ini_get('opcache.enable');
+ return \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN);
}
/**
{
$time = time();
$pruned = true;
- $allowCompile = 'cli' !== PHP_SAPI || ini_get('opcache.enable_cli');
+ $allowCompile = 'cli' !== \PHP_SAPI || filter_var(ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN);
set_error_handler($this->includeHandler);
try {
*/
protected function doFetch(array $ids)
{
- $values = array();
+ $values = [];
$now = time();
if ($this->zendDetectUnicode) {
foreach ($values as $id => $value) {
if ('N;' === $value) {
$values[$id] = null;
- } elseif (is_string($value) && isset($value[2]) && ':' === $value[1]) {
+ } elseif (\is_string($value) && isset($value[2]) && ':' === $value[1]) {
$values[$id] = parent::unserialize($value);
}
}
*/
protected function doHave($id)
{
- return (bool) $this->doFetch(array($id));
+ return (bool) $this->doFetch([$id]);
}
/**
protected function doSave(array $values, $lifetime)
{
$ok = true;
- $data = array($lifetime ? time() + $lifetime : PHP_INT_MAX, '');
- $allowCompile = 'cli' !== PHP_SAPI || ini_get('opcache.enable_cli');
+ $data = [$lifetime ? time() + $lifetime : \PHP_INT_MAX, ''];
+ $allowCompile = 'cli' !== \PHP_SAPI || filter_var(ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN);
foreach ($values as $key => $value) {
- if (null === $value || is_object($value)) {
+ if (null === $value || \is_object($value)) {
$value = serialize($value);
- } elseif (is_array($value)) {
+ } elseif (\is_array($value)) {
$serialized = serialize($value);
$unserialized = parent::unserialize($serialized);
// Store arrays serialized if they contain any objects or references
if ($unserialized !== $value || (false !== strpos($serialized, ';R:') && preg_match('/;R:[1-9]/', $serialized))) {
$value = $serialized;
}
- } elseif (is_string($value)) {
+ } elseif (\is_string($value)) {
// Serialize strings if they could be confused with serialized objects or arrays
if ('N;' === $value || (isset($value[2]) && ':' === $value[1])) {
$value = serialize($value);
}
} elseif (!is_scalar($value)) {
- throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable %s value.', $key, gettype($value)));
+ throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable "%s" value.', $key, \gettype($value)));
}
$data[1] = $value;
}
if (!$ok && !is_writable($this->directory)) {
- throw new CacheException(sprintf('Cache directory is not writable (%s)', $this->directory));
+ throw new CacheException(sprintf('Cache directory is not writable (%s).', $this->directory));
}
return $ok;
/**
* @author Nicolas Grekas <p@tchwork.com>
+ *
+ * @internal
*/
trait ProxyTrait
{
{
$this->ready ?: $this->ready = $this->initializer->__invoke($this->redis);
- return \call_user_func_array(array($this->redis, $method), $args);
+ return \call_user_func_array([$this->redis, $method], $args);
}
public function hscan($strKey, &$iIterator, $strPattern = null, $iCount = null)
namespace Symfony\Component\Cache\Traits;
-use Predis\Connection\Factory;
use Predis\Connection\Aggregate\ClusterInterface;
-use Predis\Connection\Aggregate\PredisCluster;
use Predis\Connection\Aggregate\RedisCluster;
+use Predis\Connection\Factory;
use Predis\Response\Status;
use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
*/
trait RedisTrait
{
- private static $defaultConnectionOptions = array(
+ private static $defaultConnectionOptions = [
'class' => null,
'persistent' => 0,
'persistent_id' => null,
'read_timeout' => 0,
'retry_interval' => 0,
'lazy' => false,
- );
+ ];
private $redis;
/**
* @param \Redis|\RedisArray|\RedisCluster|\Predis\Client $redisClient
*/
- public function init($redisClient, $namespace = '', $defaultLifetime = 0)
+ private function init($redisClient, $namespace = '', $defaultLifetime = 0)
{
parent::__construct($namespace, $defaultLifetime);
if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
throw new InvalidArgumentException(sprintf('RedisAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
- if ($redisClient instanceof \RedisCluster) {
- $this->enableVersioning();
- } elseif (!$redisClient instanceof \Redis && !$redisClient instanceof \RedisArray && !$redisClient instanceof \Predis\Client && !$redisClient instanceof RedisProxy) {
- throw new InvalidArgumentException(sprintf('%s() expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\Client, %s given', __METHOD__, is_object($redisClient) ? get_class($redisClient) : gettype($redisClient)));
+ if (!$redisClient instanceof \Redis && !$redisClient instanceof \RedisArray && !$redisClient instanceof \RedisCluster && !$redisClient instanceof \Predis\Client && !$redisClient instanceof RedisProxy) {
+ throw new InvalidArgumentException(sprintf('"%s()" expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\Client, "%s" given.', __METHOD__, \is_object($redisClient) ? \get_class($redisClient) : \gettype($redisClient)));
}
$this->redis = $redisClient;
}
*
* @return \Redis|\Predis\Client According to the "class" option
*/
- public static function createConnection($dsn, array $options = array())
+ public static function createConnection($dsn, array $options = [])
{
if (0 !== strpos($dsn, 'redis://')) {
- throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s does not start with "redis://"', $dsn));
+ throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s" does not start with "redis://".', $dsn));
}
$params = preg_replace_callback('#^redis://(?:(?:[^:@]*+:)?([^@]*+)@)?#', function ($m) use (&$auth) {
if (isset($m[1])) {
return 'file://';
}, $dsn);
if (false === $params = parse_url($params)) {
- throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s', $dsn));
+ throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
}
if (!isset($params['host']) && !isset($params['path'])) {
- throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s', $dsn));
+ throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
}
if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
$params['dbindex'] = $m[1];
- $params['path'] = substr($params['path'], 0, -strlen($m[0]));
+ $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
}
if (isset($params['host'])) {
$scheme = 'tcp';
} else {
$scheme = 'unix';
}
- $params += array(
+ $params += [
'host' => isset($params['host']) ? $params['host'] : $params['path'],
'port' => isset($params['host']) ? 6379 : null,
'dbindex' => 0,
- );
+ ];
if (isset($params['query'])) {
parse_str($params['query'], $query);
$params += $query;
}
$params += $options + self::$defaultConnectionOptions;
- if (null === $params['class'] && !extension_loaded('redis') && !class_exists(\Predis\Client::class)) {
- throw new CacheException(sprintf('Cannot find the "redis" extension, and "predis/predis" is not installed: %s', $dsn));
+ if (null === $params['class'] && !\extension_loaded('redis') && !class_exists(\Predis\Client::class)) {
+ throw new CacheException(sprintf('Cannot find the "redis" extension, and "predis/predis" is not installed: "%s".', $dsn));
}
- $class = null === $params['class'] ? (extension_loaded('redis') ? \Redis::class : \Predis\Client::class) : $params['class'];
+ $class = null === $params['class'] ? (\extension_loaded('redis') ? \Redis::class : \Predis\Client::class) : $params['class'];
if (is_a($class, \Redis::class, true)) {
$connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
$initializer = function ($redis) use ($connect, $params, $dsn, $auth) {
try {
@$redis->{$connect}($params['host'], $params['port'], $params['timeout'], $params['persistent_id'], $params['retry_interval']);
- } catch (\RedisException $e) {
- throw new InvalidArgumentException(sprintf('Redis connection failed (%s): %s', $e->getMessage(), $dsn));
- }
-
- if (@!$redis->isConnected()) {
- $e = ($e = error_get_last()) && preg_match('/^Redis::p?connect\(\): (.*)/', $e['message'], $e) ? sprintf(' (%s)', $e[1]) : '';
- throw new InvalidArgumentException(sprintf('Redis connection failed%s: %s', $e, $dsn));
- }
- if ((null !== $auth && !$redis->auth($auth))
- || ($params['dbindex'] && !$redis->select($params['dbindex']))
- || ($params['read_timeout'] && !$redis->setOption(\Redis::OPT_READ_TIMEOUT, $params['read_timeout']))
- ) {
- $e = preg_replace('/^ERR /', '', $redis->getLastError());
- throw new InvalidArgumentException(sprintf('Redis connection failed (%s): %s', $e, $dsn));
+ set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
+ $isConnected = $redis->isConnected();
+ restore_error_handler();
+ if (!$isConnected) {
+ $error = preg_match('/^Redis::p?connect\(\): (.*)/', $error, $error) ? sprintf(' (%s)', $error[1]) : '';
+ throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$error.'.');
+ }
+
+ if ((null !== $auth && !$redis->auth($auth))
+ || ($params['dbindex'] && !$redis->select($params['dbindex']))
+ || ($params['read_timeout'] && !$redis->setOption(\Redis::OPT_READ_TIMEOUT, $params['read_timeout']))
+ ) {
+ $e = preg_replace('/^ERR /', '', $redis->getLastError());
+ throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e.'.');
+ }
+ } catch (\RedisException $e) {
+ throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e->getMessage());
}
return true;
$params['password'] = $auth;
$redis = new $class((new Factory())->create($params));
} elseif (class_exists($class, false)) {
- throw new InvalidArgumentException(sprintf('"%s" is not a subclass of "Redis" or "Predis\Client"', $class));
+ throw new InvalidArgumentException(sprintf('"%s" is not a subclass of "Redis" or "Predis\Client".', $class));
} else {
- throw new InvalidArgumentException(sprintf('Class "%s" does not exist', $class));
+ throw new InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
}
return $redis;
*/
protected function doFetch(array $ids)
{
- if ($ids) {
+ if (!$ids) {
+ return [];
+ }
+
+ $result = [];
+
+ if ($this->redis instanceof \Predis\Client && $this->redis->getConnection() instanceof ClusterInterface) {
$values = $this->pipeline(function () use ($ids) {
foreach ($ids as $id) {
- yield 'get' => array($id);
+ yield 'get' => [$id];
}
});
- foreach ($values as $id => $v) {
- if ($v) {
- yield $id => parent::unserialize($v);
- }
+ } else {
+ $values = $this->redis->mget($ids);
+
+ if (!\is_array($values) || \count($values) !== \count($ids)) {
+ return [];
}
+
+ $values = array_combine($ids, $values);
}
+
+ foreach ($values as $id => $v) {
+ if ($v) {
+ $result[$id] = parent::unserialize($v);
+ }
+ }
+
+ return $result;
}
/**
*/
protected function doClear($namespace)
{
- // When using a native Redis cluster, clearing the cache is done by versioning in AbstractTrait::clear().
- // This means old keys are not really removed until they expire and may need gargage collection.
-
$cleared = true;
- $hosts = array($this->redis);
- $evalArgs = array(array($namespace), 0);
+ $hosts = [$this->redis];
+ $evalArgs = [[$namespace], 0];
if ($this->redis instanceof \Predis\Client) {
- $evalArgs = array(0, $namespace);
+ $evalArgs = [0, $namespace];
$connection = $this->redis->getConnection();
- if ($connection instanceof PredisCluster) {
- $hosts = array();
+ if ($connection instanceof ClusterInterface && $connection instanceof \Traversable) {
+ $hosts = [];
foreach ($connection as $c) {
$hosts[] = new \Predis\Client($c);
}
- } elseif ($connection instanceof RedisCluster) {
- return false;
}
} elseif ($this->redis instanceof \RedisArray) {
- $hosts = array();
+ $hosts = [];
foreach ($this->redis->_hosts() as $host) {
$hosts[] = $this->redis->_instance($host);
}
} elseif ($this->redis instanceof \RedisCluster) {
- return false;
+ $hosts = [];
+ foreach ($this->redis->_masters() as $host) {
+ $hosts[] = $h = new \Redis();
+ $h->connect($host[0], $host[1]);
+ }
}
foreach ($hosts as $host) {
if (!isset($namespace[0])) {
$cursor = null;
do {
$keys = $host instanceof \Predis\Client ? $host->scan($cursor, 'MATCH', $namespace.'*', 'COUNT', 1000) : $host->scan($cursor, $namespace.'*', 1000);
- if (isset($keys[1]) && is_array($keys[1])) {
+ if (isset($keys[1]) && \is_array($keys[1])) {
$cursor = $keys[0];
$keys = $keys[1];
}
if ($keys) {
- $host->del($keys);
+ $this->doDelete($keys);
}
} while ($cursor = (int) $cursor);
}
*/
protected function doDelete(array $ids)
{
- if ($ids) {
+ if (!$ids) {
+ return true;
+ }
+
+ if ($this->redis instanceof \Predis\Client && $this->redis->getConnection() instanceof ClusterInterface) {
+ $this->pipeline(function () use ($ids) {
+ foreach ($ids as $id) {
+ yield 'del' => [$id];
+ }
+ })->rewind();
+ } else {
$this->redis->del($ids);
}
*/
protected function doSave(array $values, $lifetime)
{
- $serialized = array();
- $failed = array();
+ $serialized = [];
+ $failed = [];
foreach ($values as $id => $value) {
try {
$results = $this->pipeline(function () use ($serialized, $lifetime) {
foreach ($serialized as $id => $value) {
if (0 >= $lifetime) {
- yield 'set' => array($id, $value);
+ yield 'set' => [$id, $value];
} else {
- yield 'setEx' => array($id, $lifetime, $value);
+ yield 'setEx' => [$id, $lifetime, $value];
}
}
});
private function pipeline(\Closure $generator)
{
- $ids = array();
+ $ids = [];
- if ($this->redis instanceof \Predis\Client && !$this->redis->getConnection() instanceof ClusterInterface) {
+ if ($this->redis instanceof \RedisCluster || ($this->redis instanceof \Predis\Client && $this->redis->getConnection() instanceof RedisCluster)) {
+ // phpredis & predis don't support pipelining with RedisCluster
+ // see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining
+ // see https://github.com/nrk/predis/issues/267#issuecomment-123781423
+ $results = [];
+ foreach ($generator() as $command => $args) {
+ $results[] = \call_user_func_array([$this->redis, $command], $args);
+ $ids[] = $args[0];
+ }
+ } elseif ($this->redis instanceof \Predis\Client) {
$results = $this->redis->pipeline(function ($redis) use ($generator, &$ids) {
foreach ($generator() as $command => $args) {
- call_user_func_array(array($redis, $command), $args);
+ \call_user_func_array([$redis, $command], $args);
$ids[] = $args[0];
}
});
} elseif ($this->redis instanceof \RedisArray) {
- $connections = $results = $ids = array();
+ $connections = $results = $ids = [];
foreach ($generator() as $command => $args) {
if (!isset($connections[$h = $this->redis->_target($args[0])])) {
- $connections[$h] = array($this->redis->_instance($h), -1);
+ $connections[$h] = [$this->redis->_instance($h), -1];
$connections[$h][0]->multi(\Redis::PIPELINE);
}
- call_user_func_array(array($connections[$h][0], $command), $args);
- $results[] = array($h, ++$connections[$h][1]);
+ \call_user_func_array([$connections[$h][0], $command], $args);
+ $results[] = [$h, ++$connections[$h][1]];
$ids[] = $args[0];
}
foreach ($connections as $h => $c) {
foreach ($results as $k => list($h, $c)) {
$results[$k] = $connections[$h][$c];
}
- } elseif ($this->redis instanceof \RedisCluster || ($this->redis instanceof \Predis\Client && $this->redis->getConnection() instanceof ClusterInterface)) {
- // phpredis & predis don't support pipelining with RedisCluster
- // see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining
- // see https://github.com/nrk/predis/issues/267#issuecomment-123781423
- $results = array();
- foreach ($generator() as $command => $args) {
- $results[] = call_user_func_array(array($this->redis, $command), $args);
- $ids[] = $args[0];
- }
} else {
$this->redis->multi(\Redis::PIPELINE);
foreach ($generator() as $command => $args) {
- call_user_func_array(array($this->redis, $command), $args);
+ \call_user_func_array([$this->redis, $command], $args);
$ids[] = $args[0];
}
$results = $this->redis->exec();
},
"require-dev": {
"cache/integration-tests": "dev-master",
- "doctrine/cache": "~1.6",
- "doctrine/dbal": "~2.4",
- "predis/predis": "~1.0"
+ "doctrine/cache": "^1.6",
+ "doctrine/dbal": "^2.4|^3.0",
+ "predis/predis": "^1.0"
},
"conflict": {
"symfony/var-dumper": "<3.3"
"/Tests/"
]
},
- "minimum-stability": "dev",
- "extra": {
- "branch-alias": {
- "dev-master": "3.4-dev"
- }
- }
+ "minimum-stability": "dev"
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
+ xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.2/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
<array>
<element key="time-sensitive">
<array>
- <element><string>Cache\IntegrationTests</string></element>
- <element><string>Doctrine\Common\Cache</string></element>
- <element><string>Symfony\Component\Cache</string></element>
- <element><string>Symfony\Component\Cache\Tests\Fixtures</string></element>
- <element><string>Symfony\Component\Cache\Traits</string></element>
+ <element key="0"><string>Cache\IntegrationTests</string></element>
+ <element key="1"><string>Doctrine\Common\Cache</string></element>
+ <element key="2"><string>Symfony\Component\Cache</string></element>
+ <element key="3"><string>Symfony\Component\Cache\Tests\Fixtures</string></element>
+ <element key="4"><string>Symfony\Component\Cache\Traits</string></element>
</array>
</element>
</array>
*/
public function repr($value)
{
- if (is_int($value) || is_float($value)) {
- if (false !== $locale = setlocale(LC_NUMERIC, 0)) {
- setlocale(LC_NUMERIC, 'C');
+ if (\is_int($value) || \is_float($value)) {
+ if (false !== $locale = setlocale(\LC_NUMERIC, 0)) {
+ setlocale(\LC_NUMERIC, 'C');
}
$this->raw($value);
if (false !== $locale) {
- setlocale(LC_NUMERIC, $locale);
+ setlocale(\LC_NUMERIC, $locale);
}
} elseif (null === $value) {
$this->raw('null');
- } elseif (is_bool($value)) {
+ } elseif (\is_bool($value)) {
$this->raw($value ? 'true' : 'false');
- } elseif (is_array($value)) {
- $this->raw('array(');
+ } elseif (\is_array($value)) {
+ $this->raw('[');
$first = true;
foreach ($value as $key => $value) {
if (!$first) {
$this->raw(' => ');
$this->repr($value);
}
- $this->raw(')');
+ $this->raw(']');
} else {
$this->string($value);
}
public static function fromPhp($phpFunctionName, $expressionFunctionName = null)
{
$phpFunctionName = ltrim($phpFunctionName, '\\');
- if (!function_exists($phpFunctionName)) {
+ if (!\function_exists($phpFunctionName)) {
throw new \InvalidArgumentException(sprintf('PHP function "%s" does not exist.', $phpFunctionName));
}
$parts = explode('\\', $phpFunctionName);
- if (!$expressionFunctionName && count($parts) > 1) {
+ if (!$expressionFunctionName && \count($parts) > 1) {
throw new \InvalidArgumentException(sprintf('An expression function name must be defined when PHP function "%s" is namespaced.', $phpFunctionName));
}
$compiler = function () use ($phpFunctionName) {
- return sprintf('\%s(%s)', $phpFunctionName, implode(', ', func_get_args()));
+ return sprintf('\%s(%s)', $phpFunctionName, implode(', ', \func_get_args()));
};
$evaluator = function () use ($phpFunctionName) {
- $args = func_get_args();
+ $args = \func_get_args();
- return call_user_func_array($phpFunctionName, array_splice($args, 1));
+ return \call_user_func_array($phpFunctionName, array_splice($args, 1));
};
return new self($expressionFunctionName ?: end($parts), $compiler, $evaluator);
private $parser;
private $compiler;
- protected $functions = array();
+ protected $functions = [];
/**
* @param CacheItemPoolInterface $cache
* @param ExpressionFunctionProviderInterface[] $providers
*/
- public function __construct($cache = null, array $providers = array())
+ public function __construct($cache = null, array $providers = [])
{
if (null !== $cache) {
if ($cache instanceof ParserCacheInterface) {
- @trigger_error(sprintf('Passing an instance of %s as constructor argument for %s is deprecated as of 3.2 and will be removed in 4.0. Pass an instance of %s instead.', ParserCacheInterface::class, self::class, CacheItemPoolInterface::class), E_USER_DEPRECATED);
+ @trigger_error(sprintf('Passing an instance of %s as constructor argument for %s is deprecated as of 3.2 and will be removed in 4.0. Pass an instance of %s instead.', ParserCacheInterface::class, self::class, CacheItemPoolInterface::class), \E_USER_DEPRECATED);
$cache = new ParserCacheAdapter($cache);
} elseif (!$cache instanceof CacheItemPoolInterface) {
- throw new \InvalidArgumentException(sprintf('Cache argument has to implement %s.', CacheItemPoolInterface::class));
+ throw new \InvalidArgumentException(sprintf('Cache argument has to implement "%s".', CacheItemPoolInterface::class));
}
}
*
* @return string The compiled PHP source code
*/
- public function compile($expression, $names = array())
+ public function compile($expression, $names = [])
{
return $this->getCompiler()->compile($this->parse($expression, $names)->getNodes())->getSource();
}
* @param Expression|string $expression The expression to compile
* @param array $values An array of values
*
- * @return string The result of the evaluation of the expression
+ * @return mixed The result of the evaluation of the expression
*/
- public function evaluate($expression, $values = array())
+ public function evaluate($expression, $values = [])
{
return $this->parse($expression, array_keys($values))->getNodes()->evaluate($this->functions, $values);
}
}
asort($names);
- $cacheKeyItems = array();
+ $cacheKeyItems = [];
foreach ($names as $nameKey => $name) {
- $cacheKeyItems[] = is_int($nameKey) ? $name : $nameKey.':'.$name;
+ $cacheKeyItems[] = \is_int($nameKey) ? $name : $nameKey.':'.$name;
}
$cacheItem = $this->cache->getItem(rawurlencode($expression.'//'.implode('|', $cacheKeyItems)));
throw new \LogicException('Registering functions after calling evaluate(), compile() or parse() is not supported.');
}
- $this->functions[$name] = array('compiler' => $compiler, 'evaluator' => $evaluator);
+ $this->functions[$name] = ['compiler' => $compiler, 'evaluator' => $evaluator];
}
public function addFunction(ExpressionFunction $function)
-Copyright (c) 2004-2018 Fabien Potencier
+Copyright (c) 2004-2020 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
*/
public function tokenize($expression)
{
- $expression = str_replace(array("\r", "\n", "\t", "\v", "\f"), ' ', $expression);
+ $expression = str_replace(["\r", "\n", "\t", "\v", "\f"], ' ', $expression);
$cursor = 0;
- $tokens = array();
- $brackets = array();
- $end = strlen($expression);
+ $tokens = [];
+ $brackets = [];
+ $end = \strlen($expression);
while ($cursor < $end) {
if (' ' == $expression[$cursor]) {
if (preg_match('/[0-9]+(?:\.[0-9]+)?/A', $expression, $match, 0, $cursor)) {
// numbers
$number = (float) $match[0]; // floats
- if (preg_match('/^[0-9]+$/', $match[0]) && $number <= PHP_INT_MAX) {
+ if (preg_match('/^[0-9]+$/', $match[0]) && $number <= \PHP_INT_MAX) {
$number = (int) $match[0]; // integers lower than the maximum
}
$tokens[] = new Token(Token::NUMBER_TYPE, $number, $cursor + 1);
- $cursor += strlen($match[0]);
+ $cursor += \strlen($match[0]);
} elseif (false !== strpos('([{', $expression[$cursor])) {
// opening bracket
- $brackets[] = array($expression[$cursor], $cursor);
+ $brackets[] = [$expression[$cursor], $cursor];
$tokens[] = new Token(Token::PUNCTUATION_TYPE, $expression[$cursor], $cursor + 1);
++$cursor;
} elseif (false !== strpos(')]}', $expression[$cursor])) {
// closing bracket
if (empty($brackets)) {
- throw new SyntaxError(sprintf('Unexpected "%s"', $expression[$cursor]), $cursor, $expression);
+ throw new SyntaxError(sprintf('Unexpected "%s".', $expression[$cursor]), $cursor, $expression);
}
list($expect, $cur) = array_pop($brackets);
if ($expression[$cursor] != strtr($expect, '([{', ')]}')) {
- throw new SyntaxError(sprintf('Unclosed "%s"', $expect), $cur, $expression);
+ throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $cur, $expression);
}
$tokens[] = new Token(Token::PUNCTUATION_TYPE, $expression[$cursor], $cursor + 1);
} elseif (preg_match('/"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As', $expression, $match, 0, $cursor)) {
// strings
$tokens[] = new Token(Token::STRING_TYPE, stripcslashes(substr($match[0], 1, -1)), $cursor + 1);
- $cursor += strlen($match[0]);
- } elseif (preg_match('/not in(?=[\s(])|\!\=\=|not(?=[\s(])|and(?=[\s(])|\=\=\=|\>\=|or(?=[\s(])|\<\=|\*\*|\.\.|in(?=[\s(])|&&|\|\||matches|\=\=|\!\=|\*|~|%|\/|\>|\||\!|\^|&|\+|\<|\-/A', $expression, $match, 0, $cursor)) {
+ $cursor += \strlen($match[0]);
+ } elseif (preg_match('/(?<=^|[\s(])not in(?=[\s(])|\!\=\=|(?<=^|[\s(])not(?=[\s(])|(?<=^|[\s(])and(?=[\s(])|\=\=\=|\>\=|(?<=^|[\s(])or(?=[\s(])|\<\=|\*\*|\.\.|(?<=^|[\s(])in(?=[\s(])|&&|\|\||(?<=^|[\s(])matches|\=\=|\!\=|\*|~|%|\/|\>|\||\!|\^|&|\+|\<|\-/A', $expression, $match, 0, $cursor)) {
// operators
$tokens[] = new Token(Token::OPERATOR_TYPE, $match[0], $cursor + 1);
- $cursor += strlen($match[0]);
+ $cursor += \strlen($match[0]);
} elseif (false !== strpos('.,?:', $expression[$cursor])) {
// punctuation
$tokens[] = new Token(Token::PUNCTUATION_TYPE, $expression[$cursor], $cursor + 1);
} elseif (preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A', $expression, $match, 0, $cursor)) {
// names
$tokens[] = new Token(Token::NAME_TYPE, $match[0], $cursor + 1);
- $cursor += strlen($match[0]);
+ $cursor += \strlen($match[0]);
} else {
// unlexable
- throw new SyntaxError(sprintf('Unexpected character "%s"', $expression[$cursor]), $cursor, $expression);
+ throw new SyntaxError(sprintf('Unexpected character "%s".', $expression[$cursor]), $cursor, $expression);
}
}
if (!empty($brackets)) {
list($expect, $cur) = array_pop($brackets);
- throw new SyntaxError(sprintf('Unclosed "%s"', $expect), $cur, $expression);
+ throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $cur, $expression);
}
return new TokenStream($tokens, $expression);
public function toArray()
{
- $array = array();
+ $array = [];
foreach ($this->getKeyValuePairs() as $pair) {
$array[] = $pair['value'];
*/
public function compile(Compiler $compiler)
{
- $compiler->raw('array(');
+ $compiler->raw('[');
$this->compileArguments($compiler);
- $compiler->raw(')');
+ $compiler->raw(']');
}
public function evaluate($functions, $values)
{
- $result = array();
+ $result = [];
foreach ($this->getKeyValuePairs() as $pair) {
$result[$pair['key']->evaluate($functions, $values)] = $pair['value']->evaluate($functions, $values);
}
public function toArray()
{
- $value = array();
+ $value = [];
foreach ($this->getKeyValuePairs() as $pair) {
$value[$pair['key']->attributes['value']] = $pair['value'];
}
- $array = array();
+ $array = [];
if ($this->isHash($value)) {
foreach ($value as $k => $v) {
protected function getKeyValuePairs()
{
- $pairs = array();
+ $pairs = [];
foreach (array_chunk($this->nodes, 2) as $pair) {
- $pairs[] = array('key' => $pair[0], 'value' => $pair[1]);
+ $pairs[] = ['key' => $pair[0], 'value' => $pair[1]];
}
return $pairs;
*/
class BinaryNode extends Node
{
- private static $operators = array(
+ private static $operators = [
'~' => '.',
'and' => '&&',
'or' => '||',
- );
+ ];
- private static $functions = array(
+ private static $functions = [
'**' => 'pow',
'..' => 'range',
'in' => 'in_array',
'not in' => '!in_array',
- );
+ ];
public function __construct($operator, Node $left, Node $right)
{
parent::__construct(
- array('left' => $left, 'right' => $right),
- array('operator' => $operator)
+ ['left' => $left, 'right' => $right],
+ ['operator' => $operator]
);
}
$right = $this->nodes['right']->evaluate($functions, $values);
if ('not in' === $operator) {
- return !in_array($left, $right);
+ return !\in_array($left, $right);
}
$f = self::$functions[$operator];
case '<=':
return $left <= $right;
case 'not in':
- return !in_array($left, $right);
+ return !\in_array($left, $right);
case 'in':
- return in_array($left, $right);
+ return \in_array($left, $right);
case '+':
return $left + $right;
case '-':
case '*':
return $left * $right;
case '/':
+ if (0 == $right) {
+ throw new \DivisionByZeroError('Division by zero.');
+ }
+
return $left / $right;
case '%':
+ if (0 == $right) {
+ throw new \DivisionByZeroError('Modulo by zero.');
+ }
+
return $left % $right;
case 'matches':
return preg_match($right, $left);
public function toArray()
{
- return array('(', $this->nodes['left'], ' '.$this->attributes['operator'].' ', $this->nodes['right'], ')');
+ return ['(', $this->nodes['left'], ' '.$this->attributes['operator'].' ', $this->nodes['right'], ')'];
}
}
public function __construct(Node $expr1, Node $expr2, Node $expr3)
{
parent::__construct(
- array('expr1' => $expr1, 'expr2' => $expr2, 'expr3' => $expr3)
+ ['expr1' => $expr1, 'expr2' => $expr2, 'expr3' => $expr3]
);
}
public function toArray()
{
- return array('(', $this->nodes['expr1'], ' ? ', $this->nodes['expr2'], ' : ', $this->nodes['expr3'], ')');
+ return ['(', $this->nodes['expr1'], ' ? ', $this->nodes['expr2'], ' : ', $this->nodes['expr3'], ')'];
}
}
{
$this->isIdentifier = $isIdentifier;
parent::__construct(
- array(),
- array('value' => $value)
+ [],
+ ['value' => $value]
);
}
public function toArray()
{
- $array = array();
+ $array = [];
$value = $this->attributes['value'];
if ($this->isIdentifier) {
$array[] = 'null';
} elseif (is_numeric($value)) {
$array[] = $value;
- } elseif (!is_array($value)) {
+ } elseif (!\is_array($value)) {
$array[] = $this->dumpString($value);
} elseif ($this->isHash($value)) {
foreach ($value as $k => $v) {
public function __construct($name, Node $arguments)
{
parent::__construct(
- array('arguments' => $arguments),
- array('name' => $name)
+ ['arguments' => $arguments],
+ ['name' => $name]
);
}
public function compile(Compiler $compiler)
{
- $arguments = array();
+ $arguments = [];
foreach ($this->nodes['arguments']->nodes as $node) {
$arguments[] = $compiler->subcompile($node);
}
$function = $compiler->getFunction($this->attributes['name']);
- $compiler->raw(call_user_func_array($function['compiler'], $arguments));
+ $compiler->raw(\call_user_func_array($function['compiler'], $arguments));
}
public function evaluate($functions, $values)
{
- $arguments = array($values);
+ $arguments = [$values];
foreach ($this->nodes['arguments']->nodes as $node) {
$arguments[] = $node->evaluate($functions, $values);
}
- return call_user_func_array($functions[$this->attributes['name']]['evaluator'], $arguments);
+ return \call_user_func_array($functions[$this->attributes['name']]['evaluator'], $arguments);
}
public function toArray()
{
- $array = array();
+ $array = [];
$array[] = $this->attributes['name'];
foreach ($this->nodes['arguments']->nodes as $node) {
public function __construct(Node $node, Node $attribute, ArrayNode $arguments, $type)
{
parent::__construct(
- array('node' => $node, 'attribute' => $attribute, 'arguments' => $arguments),
- array('type' => $type)
+ ['node' => $node, 'attribute' => $attribute, 'arguments' => $arguments],
+ ['type' => $type]
);
}
switch ($this->attributes['type']) {
case self::PROPERTY_CALL:
$obj = $this->nodes['node']->evaluate($functions, $values);
- if (!is_object($obj)) {
+ if (!\is_object($obj)) {
throw new \RuntimeException('Unable to get a property on a non-object.');
}
case self::METHOD_CALL:
$obj = $this->nodes['node']->evaluate($functions, $values);
- if (!is_object($obj)) {
+ if (!\is_object($obj)) {
throw new \RuntimeException('Unable to get a property on a non-object.');
}
- if (!is_callable($toCall = array($obj, $this->nodes['attribute']->attributes['value']))) {
- throw new \RuntimeException(sprintf('Unable to call method "%s" of object "%s".', $this->nodes['attribute']->attributes['value'], get_class($obj)));
+ if (!\is_callable($toCall = [$obj, $this->nodes['attribute']->attributes['value']])) {
+ throw new \RuntimeException(sprintf('Unable to call method "%s" of object "%s".', $this->nodes['attribute']->attributes['value'], \get_class($obj)));
}
- return call_user_func_array($toCall, $this->nodes['arguments']->evaluate($functions, $values));
+ $arguments = $this->nodes['arguments']->evaluate($functions, $values);
+
+ if (\PHP_VERSION_ID >= 80000) {
+ $arguments = array_values($arguments);
+ }
+
+ return \call_user_func_array($toCall, $arguments);
case self::ARRAY_CALL:
$array = $this->nodes['node']->evaluate($functions, $values);
- if (!is_array($array) && !$array instanceof \ArrayAccess) {
+ if (!\is_array($array) && !$array instanceof \ArrayAccess) {
throw new \RuntimeException('Unable to get an item on a non-array.');
}
{
switch ($this->attributes['type']) {
case self::PROPERTY_CALL:
- return array($this->nodes['node'], '.', $this->nodes['attribute']);
+ return [$this->nodes['node'], '.', $this->nodes['attribute']];
case self::METHOD_CALL:
- return array($this->nodes['node'], '.', $this->nodes['attribute'], '(', $this->nodes['arguments'], ')');
+ return [$this->nodes['node'], '.', $this->nodes['attribute'], '(', $this->nodes['arguments'], ')'];
case self::ARRAY_CALL:
- return array($this->nodes['node'], '[', $this->nodes['attribute'], ']');
+ return [$this->nodes['node'], '[', $this->nodes['attribute'], ']'];
}
}
}
public function __construct($name)
{
parent::__construct(
- array(),
- array('name' => $name)
+ [],
+ ['name' => $name]
);
}
public function toArray()
{
- return array($this->attributes['name']);
+ return [$this->attributes['name']];
}
}
*/
class Node
{
- public $nodes = array();
- public $attributes = array();
+ public $nodes = [];
+ public $attributes = [];
/**
* @param array $nodes An array of nodes
* @param array $attributes An array of attributes
*/
- public function __construct(array $nodes = array(), array $attributes = array())
+ public function __construct(array $nodes = [], array $attributes = [])
{
$this->nodes = $nodes;
$this->attributes = $attributes;
public function __toString()
{
- $attributes = array();
+ $attributes = [];
foreach ($this->attributes as $name => $value) {
$attributes[] = sprintf('%s: %s', $name, str_replace("\n", '', var_export($value, true)));
}
- $repr = array(str_replace('Symfony\Component\ExpressionLanguage\Node\\', '', get_class($this)).'('.implode(', ', $attributes));
+ $repr = [str_replace('Symfony\Component\ExpressionLanguage\Node\\', '', static::class).'('.implode(', ', $attributes)];
- if (count($this->nodes)) {
+ if (\count($this->nodes)) {
foreach ($this->nodes as $node) {
foreach (explode("\n", (string) $node) as $line) {
$repr[] = ' '.$line;
public function evaluate($functions, $values)
{
- $results = array();
+ $results = [];
foreach ($this->nodes as $node) {
$results[] = $node->evaluate($functions, $values);
}
public function toArray()
{
- throw new \BadMethodCallException(sprintf('Dumping a "%s" instance is not supported yet.', get_class($this)));
+ throw new \BadMethodCallException(sprintf('Dumping a "%s" instance is not supported yet.', static::class));
}
public function dump()
*/
class UnaryNode extends Node
{
- private static $operators = array(
+ private static $operators = [
'!' => '!',
'not' => '!',
'+' => '+',
'-' => '-',
- );
+ ];
public function __construct($operator, Node $node)
{
parent::__construct(
- array('node' => $node),
- array('operator' => $operator)
+ ['node' => $node],
+ ['operator' => $operator]
);
}
public function toArray()
{
- return array('(', $this->attributes['operator'].' ', $this->nodes['node'], ')');
+ return ['(', $this->attributes['operator'].' ', $this->nodes['node'], ')'];
}
}
{
$this->functions = $functions;
- $this->unaryOperators = array(
- 'not' => array('precedence' => 50),
- '!' => array('precedence' => 50),
- '-' => array('precedence' => 500),
- '+' => array('precedence' => 500),
- );
- $this->binaryOperators = array(
- 'or' => array('precedence' => 10, 'associativity' => self::OPERATOR_LEFT),
- '||' => array('precedence' => 10, 'associativity' => self::OPERATOR_LEFT),
- 'and' => array('precedence' => 15, 'associativity' => self::OPERATOR_LEFT),
- '&&' => array('precedence' => 15, 'associativity' => self::OPERATOR_LEFT),
- '|' => array('precedence' => 16, 'associativity' => self::OPERATOR_LEFT),
- '^' => array('precedence' => 17, 'associativity' => self::OPERATOR_LEFT),
- '&' => array('precedence' => 18, 'associativity' => self::OPERATOR_LEFT),
- '==' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- '===' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- '!=' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- '!==' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- '<' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- '>' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- '>=' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- '<=' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- 'not in' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- 'in' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- 'matches' => array('precedence' => 20, 'associativity' => self::OPERATOR_LEFT),
- '..' => array('precedence' => 25, 'associativity' => self::OPERATOR_LEFT),
- '+' => array('precedence' => 30, 'associativity' => self::OPERATOR_LEFT),
- '-' => array('precedence' => 30, 'associativity' => self::OPERATOR_LEFT),
- '~' => array('precedence' => 40, 'associativity' => self::OPERATOR_LEFT),
- '*' => array('precedence' => 60, 'associativity' => self::OPERATOR_LEFT),
- '/' => array('precedence' => 60, 'associativity' => self::OPERATOR_LEFT),
- '%' => array('precedence' => 60, 'associativity' => self::OPERATOR_LEFT),
- '**' => array('precedence' => 200, 'associativity' => self::OPERATOR_RIGHT),
- );
+ $this->unaryOperators = [
+ 'not' => ['precedence' => 50],
+ '!' => ['precedence' => 50],
+ '-' => ['precedence' => 500],
+ '+' => ['precedence' => 500],
+ ];
+ $this->binaryOperators = [
+ 'or' => ['precedence' => 10, 'associativity' => self::OPERATOR_LEFT],
+ '||' => ['precedence' => 10, 'associativity' => self::OPERATOR_LEFT],
+ 'and' => ['precedence' => 15, 'associativity' => self::OPERATOR_LEFT],
+ '&&' => ['precedence' => 15, 'associativity' => self::OPERATOR_LEFT],
+ '|' => ['precedence' => 16, 'associativity' => self::OPERATOR_LEFT],
+ '^' => ['precedence' => 17, 'associativity' => self::OPERATOR_LEFT],
+ '&' => ['precedence' => 18, 'associativity' => self::OPERATOR_LEFT],
+ '==' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ '===' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ '!=' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ '!==' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ '<' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ '>' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ '>=' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ '<=' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ 'not in' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ 'in' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ 'matches' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
+ '..' => ['precedence' => 25, 'associativity' => self::OPERATOR_LEFT],
+ '+' => ['precedence' => 30, 'associativity' => self::OPERATOR_LEFT],
+ '-' => ['precedence' => 30, 'associativity' => self::OPERATOR_LEFT],
+ '~' => ['precedence' => 40, 'associativity' => self::OPERATOR_LEFT],
+ '*' => ['precedence' => 60, 'associativity' => self::OPERATOR_LEFT],
+ '/' => ['precedence' => 60, 'associativity' => self::OPERATOR_LEFT],
+ '%' => ['precedence' => 60, 'associativity' => self::OPERATOR_LEFT],
+ '**' => ['precedence' => 200, 'associativity' => self::OPERATOR_RIGHT],
+ ];
}
/**
*
* @throws SyntaxError
*/
- public function parse(TokenStream $stream, $names = array())
+ public function parse(TokenStream $stream, $names = [])
{
$this->stream = $stream;
$this->names = $names;
$node = $this->parseExpression();
if (!$stream->isEOF()) {
- throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s"', $stream->current->type, $stream->current->value), $stream->current->cursor, $stream->getExpression());
+ throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s".', $stream->current->type, $stream->current->value), $stream->current->cursor, $stream->getExpression());
}
return $node;
default:
if ('(' === $this->stream->current->value) {
if (false === isset($this->functions[$token->value])) {
- throw new SyntaxError(sprintf('The function "%s" does not exist', $token->value), $token->cursor, $this->stream->getExpression(), $token->value, array_keys($this->functions));
+ throw new SyntaxError(sprintf('The function "%s" does not exist.', $token->value), $token->cursor, $this->stream->getExpression(), $token->value, array_keys($this->functions));
}
$node = new Node\FunctionNode($token->value, $this->parseArguments());
} else {
- if (!in_array($token->value, $this->names, true)) {
- throw new SyntaxError(sprintf('Variable "%s" is not valid', $token->value), $token->cursor, $this->stream->getExpression(), $token->value, $this->names);
+ if (!\in_array($token->value, $this->names, true)) {
+ throw new SyntaxError(sprintf('Variable "%s" is not valid.', $token->value), $token->cursor, $this->stream->getExpression(), $token->value, $this->names);
}
// is the name used in the compiled code different
// from the name used in the expression?
- if (is_int($name = array_search($token->value, $this->names))) {
+ if (\is_int($name = array_search($token->value, $this->names))) {
$name = $token->value;
}
} elseif ($token->test(Token::PUNCTUATION_TYPE, '{')) {
$node = $this->parseHashExpression();
} else {
- throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s"', $token->type, $token->value), $token->cursor, $this->stream->getExpression());
+ throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s".', $token->type, $token->value), $token->cursor, $this->stream->getExpression());
}
}
} else {
$current = $this->stream->current;
- throw new SyntaxError(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s"', $current->type, $current->value), $current->cursor, $this->stream->getExpression());
+ throw new SyntaxError(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s".', $current->type, $current->value), $current->cursor, $this->stream->getExpression());
}
$this->stream->expect(Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)');
// As a result, if $token is NOT an operator OR $token->value is NOT a valid property or method name, an exception shall be thrown.
(Token::OPERATOR_TYPE !== $token->type || !preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A', $token->value))
) {
- throw new SyntaxError('Expected name', $token->cursor, $this->stream->getExpression());
+ throw new SyntaxError('Expected name.', $token->cursor, $this->stream->getExpression());
}
$arg = new Node\ConstantNode($token->value, true);
*/
public function parseArguments()
{
- $args = array();
+ $args = [];
$this->stream->expect(Token::PUNCTUATION_TYPE, '(', 'A list of arguments must begin with an opening parenthesis');
while (!$this->stream->current->test(Token::PUNCTUATION_TYPE, ')')) {
if (!empty($args)) {
namespace Symfony\Component\ExpressionLanguage\ParserCache;
-@trigger_error('The '.__NAMESPACE__.'\ArrayParserCache class is deprecated since Symfony 3.2 and will be removed in 4.0. Use the Symfony\Component\Cache\Adapter\ArrayAdapter class instead.', E_USER_DEPRECATED);
+@trigger_error('The '.__NAMESPACE__.'\ArrayParserCache class is deprecated since Symfony 3.2 and will be removed in 4.0. Use the Symfony\Component\Cache\Adapter\ArrayAdapter class instead.', \E_USER_DEPRECATED);
use Symfony\Component\ExpressionLanguage\ParsedExpression;
*/
class ArrayParserCache implements ParserCacheInterface
{
- private $cache = array();
+ private $cache = [];
/**
* {@inheritdoc}
$this->pool = $pool;
$this->createCacheItem = \Closure::bind(
- function ($key, $value, $isHit) {
+ static function ($key, $value, $isHit) {
$item = new CacheItem();
$item->key = $key;
$item->value = $value;
/**
* {@inheritdoc}
*/
- public function getItems(array $keys = array())
+ public function getItems(array $keys = [])
{
- throw new \BadMethodCallException('Not implemented');
+ throw new \BadMethodCallException('Not implemented.');
}
/**
*/
public function hasItem($key)
{
- throw new \BadMethodCallException('Not implemented');
+ throw new \BadMethodCallException('Not implemented.');
}
/**
*/
public function clear()
{
- throw new \BadMethodCallException('Not implemented');
+ throw new \BadMethodCallException('Not implemented.');
}
/**
*/
public function deleteItem($key)
{
- throw new \BadMethodCallException('Not implemented');
+ throw new \BadMethodCallException('Not implemented.');
}
/**
*/
public function deleteItems(array $keys)
{
- throw new \BadMethodCallException('Not implemented');
+ throw new \BadMethodCallException('Not implemented.');
}
/**
*/
public function saveDeferred(CacheItemInterface $item)
{
- throw new \BadMethodCallException('Not implemented');
+ throw new \BadMethodCallException('Not implemented.');
}
/**
*/
public function commit()
{
- throw new \BadMethodCallException('Not implemented');
+ throw new \BadMethodCallException('Not implemented.');
}
}
namespace Symfony\Component\ExpressionLanguage\ParserCache;
-@trigger_error('The '.__NAMESPACE__.'\ParserCacheInterface interface is deprecated since Symfony 3.2 and will be removed in 4.0. Use Psr\Cache\CacheItemPoolInterface instead.', E_USER_DEPRECATED);
+@trigger_error('The '.__NAMESPACE__.'\ParserCacheInterface interface is deprecated since Symfony 3.2 and will be removed in 4.0. Use Psr\Cache\CacheItemPoolInterface instead.', \E_USER_DEPRECATED);
use Symfony\Component\ExpressionLanguage\ParsedExpression;
* file that was distributed with this source code.
*/
-$operators = array('not', '!', 'or', '||', '&&', 'and', '|', '^', '&', '==', '===', '!=', '!==', '<', '>', '>=', '<=', 'not in', 'in', '..', '+', '-', '~', '*', '/', '%', 'matches', '**');
+$operators = ['not', '!', 'or', '||', '&&', 'and', '|', '^', '&', '==', '===', '!=', '!==', '<', '>', '>=', '<=', 'not in', 'in', '..', '+', '-', '~', '*', '/', '%', 'matches', '**'];
$operators = array_combine($operators, array_map('strlen', $operators));
arsort($operators);
-$regex = array();
+$regex = [];
foreach ($operators as $operator => $length) {
- // an operator that ends with a character must be followed by
- // a whitespace or a parenthesis
- $regex[] = preg_quote($operator, '/').(ctype_alpha($operator[$length - 1]) ? '(?=[\s(])' : '');
+ // Collisions of character operators:
+ // - an operator that begins with a character must have a space or a parenthesis before or starting at the beginning of a string
+ // - an operator that ends with a character must be followed by a whitespace or a parenthesis
+ $regex[] =
+ (ctype_alpha($operator[0]) ? '(?<=^|[\s(])' : '')
+ .preg_quote($operator, '/')
+ .(ctype_alpha($operator[$length - 1]) ? '(?=[\s(])' : '');
}
echo '/'.implode('|', $regex).'/A';
{
public function __construct($message, $cursor = 0, $expression = '', $subject = null, array $proposals = null)
{
- $message = sprintf('%s around position %d', $message, $cursor);
+ $message = sprintf('%s around position %d', rtrim($message, '.'), $cursor);
if ($expression) {
$message = sprintf('%s for expression `%s`', $message, $expression);
}
$message .= '.';
if (null !== $subject && null !== $proposals) {
- $minScore = INF;
+ $minScore = \INF;
foreach ($proposals as $proposal) {
$distance = levenshtein($subject, $proposal);
if ($distance < $minScore) {
*/
class ExpressionFunctionTest extends TestCase
{
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage PHP function "fn_does_not_exist" does not exist.
- */
public function testFunctionDoesNotExist()
{
+ $this->expectException('InvalidArgumentException');
+ $this->expectExceptionMessage('PHP function "fn_does_not_exist" does not exist.');
ExpressionFunction::fromPhp('fn_does_not_exist');
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage An expression function name must be defined when PHP function "Symfony\Component\ExpressionLanguage\Tests\fn_namespaced" is namespaced.
- */
public function testFunctionNamespaced()
{
+ $this->expectException('InvalidArgumentException');
+ $this->expectExceptionMessage('An expression function name must be defined when PHP function "Symfony\Component\ExpressionLanguage\Tests\fn_namespaced" is namespaced.');
ExpressionFunction::fromPhp('Symfony\Component\ExpressionLanguage\Tests\fn_namespaced');
}
}
namespace Symfony\Component\ExpressionLanguage\Tests;
-use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use PHPUnit\Framework\TestCase;
+use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\ParsedExpression;
use Symfony\Component\ExpressionLanguage\Tests\Fixtures\TestProvider;
$cacheItemMock
->expects($this->exactly(2))
->method('get')
- ->will($this->returnCallback(function () use (&$savedParsedExpression) {
+ ->willReturnCallback(function () use (&$savedParsedExpression) {
return $savedParsedExpression;
- }))
+ })
;
$cacheItemMock
->expects($this->exactly(1))
->method('set')
->with($this->isInstanceOf(ParsedExpression::class))
- ->will($this->returnCallback(function ($parsedExpression) use (&$savedParsedExpression) {
+ ->willReturnCallback(function ($parsedExpression) use (&$savedParsedExpression) {
$savedParsedExpression = $parsedExpression;
- }))
+ })
;
$cacheMock
->with($cacheItemMock)
;
- $parsedExpression = $expressionLanguage->parse('1 + 1', array());
+ $parsedExpression = $expressionLanguage->parse('1 + 1', []);
$this->assertSame($savedParsedExpression, $parsedExpression);
- $parsedExpression = $expressionLanguage->parse('1 + 1', array());
+ $parsedExpression = $expressionLanguage->parse('1 + 1', []);
$this->assertSame($savedParsedExpression, $parsedExpression);
}
{
$cacheMock = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface')->getMock();
- $cacheItemMock = $this->getMockBuilder('Psr\Cache\CacheItemInterface')->getMock();
$savedParsedExpression = null;
$expressionLanguage = new ExpressionLanguage($cacheMock);
->expects($this->exactly(1))
->method('save')
->with('1%20%2B%201%2F%2F', $this->isInstanceOf(ParsedExpression::class))
- ->will($this->returnCallback(function ($key, $expression) use (&$savedParsedExpression) {
+ ->willReturnCallback(function ($key, $expression) use (&$savedParsedExpression) {
$savedParsedExpression = $expression;
- }))
+ })
;
- $parsedExpression = $expressionLanguage->parse('1 + 1', array());
+ $parsedExpression = $expressionLanguage->parse('1 + 1', []);
$this->assertSame($savedParsedExpression, $parsedExpression);
}
- /**
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage Cache argument has to implement Psr\Cache\CacheItemPoolInterface.
- */
public function testWrongCacheImplementation()
{
+ $this->expectException('InvalidArgumentException');
+ $this->expectExceptionMessage('Cache argument has to implement "Psr\Cache\CacheItemPoolInterface".');
$cacheMock = $this->getMockBuilder('Psr\Cache\CacheItemSpoolInterface')->getMock();
- $expressionLanguage = new ExpressionLanguage($cacheMock);
+ new ExpressionLanguage($cacheMock);
}
public function testConstantFunction()
{
$expressionLanguage = new ExpressionLanguage();
- $this->assertEquals(PHP_VERSION, $expressionLanguage->evaluate('constant("PHP_VERSION")'));
+ $this->assertEquals(\PHP_VERSION, $expressionLanguage->evaluate('constant("PHP_VERSION")'));
$expressionLanguage = new ExpressionLanguage();
$this->assertEquals('\constant("PHP_VERSION")', $expressionLanguage->compile('constant("PHP_VERSION")'));
public function testProviders()
{
- $expressionLanguage = new ExpressionLanguage(null, array(new TestProvider()));
+ $expressionLanguage = new ExpressionLanguage(null, [new TestProvider()]);
$this->assertEquals('foo', $expressionLanguage->evaluate('identity("foo")'));
$this->assertEquals('"foo"', $expressionLanguage->compile('identity("foo")'));
$this->assertEquals('FOO', $expressionLanguage->evaluate('strtoupper("foo")'));
$this->assertSame($expected, $result);
}
- /**
- * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError
- * @expectedExceptionMessage Unexpected end of expression around position 6 for expression `node.`.
- */
public function testParseThrowsInsteadOfNotice()
{
+ $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError');
+ $this->expectExceptionMessage('Unexpected end of expression around position 6 for expression `node.`.');
$expressionLanguage = new ExpressionLanguage();
- $expressionLanguage->parse('node.', array('node'));
+ $expressionLanguage->parse('node.', ['node']);
}
public function shortCircuitProviderEvaluate()
{
- $object = $this->getMockBuilder('stdClass')->setMethods(array('foo'))->getMock();
+ $object = $this->getMockBuilder('stdClass')->setMethods(['foo'])->getMock();
$object->expects($this->never())->method('foo');
- return array(
- array('false and object.foo()', array('object' => $object), false),
- array('false && object.foo()', array('object' => $object), false),
- array('true || object.foo()', array('object' => $object), true),
- array('true or object.foo()', array('object' => $object), true),
- );
+ return [
+ ['false and object.foo()', ['object' => $object], false],
+ ['false && object.foo()', ['object' => $object], false],
+ ['true || object.foo()', ['object' => $object], true],
+ ['true or object.foo()', ['object' => $object], true],
+ ];
}
public function shortCircuitProviderCompile()
{
- return array(
- array('false and foo', array('foo' => 'foo'), false),
- array('false && foo', array('foo' => 'foo'), false),
- array('true || foo', array('foo' => 'foo'), true),
- array('true or foo', array('foo' => 'foo'), true),
- );
+ return [
+ ['false and foo', ['foo' => 'foo'], false],
+ ['false && foo', ['foo' => 'foo'], false],
+ ['true || foo', ['foo' => 'foo'], true],
+ ['true or foo', ['foo' => 'foo'], true],
+ ];
}
public function testCachingForOverriddenVariableNames()
{
$expressionLanguage = new ExpressionLanguage();
$expression = 'a + b';
- $expressionLanguage->evaluate($expression, array('a' => 1, 'b' => 1));
- $result = $expressionLanguage->compile($expression, array('a', 'B' => 'b'));
+ $expressionLanguage->evaluate($expression, ['a' => 1, 'b' => 1]);
+ $result = $expressionLanguage->compile($expression, ['a', 'B' => 'b']);
$this->assertSame('($a + $B)', $result);
}
{
$expressionLanguage = new ExpressionLanguage();
$expression = '123 === a';
- $result = $expressionLanguage->compile($expression, array('a'));
+ $result = $expressionLanguage->compile($expression, ['a']);
$this->assertSame('(123 === $a)', $result);
}
$cacheMock = $this->getMockBuilder('Psr\Cache\CacheItemPoolInterface')->getMock();
$cacheItemMock = $this->getMockBuilder('Psr\Cache\CacheItemInterface')->getMock();
$expressionLanguage = new ExpressionLanguage($cacheMock);
- $savedParsedExpressions = array();
+ $savedParsedExpression = null;
$cacheMock
->expects($this->exactly(2))
$cacheItemMock
->expects($this->exactly(2))
->method('get')
- ->will($this->returnCallback(function () use (&$savedParsedExpression) {
+ ->willReturnCallback(function () use (&$savedParsedExpression) {
return $savedParsedExpression;
- }))
+ })
;
$cacheItemMock
->expects($this->exactly(1))
->method('set')
->with($this->isInstanceOf(ParsedExpression::class))
- ->will($this->returnCallback(function ($parsedExpression) use (&$savedParsedExpression) {
+ ->willReturnCallback(function ($parsedExpression) use (&$savedParsedExpression) {
$savedParsedExpression = $parsedExpression;
- }))
+ })
;
$cacheMock
;
$expression = 'a + b';
- $expressionLanguage->compile($expression, array('a', 'B' => 'b'));
- $expressionLanguage->compile($expression, array('B' => 'b', 'a'));
+ $expressionLanguage->compile($expression, ['a', 'B' => 'b']);
+ $expressionLanguage->compile($expression, ['B' => 'b', 'a']);
+ }
+
+ public function testOperatorCollisions()
+ {
+ $expressionLanguage = new ExpressionLanguage();
+ $expression = 'foo.not in [bar]';
+ $compiled = $expressionLanguage->compile($expression, ['foo', 'bar']);
+ $this->assertSame('in_array($foo->not, [0 => $bar])', $compiled);
+
+ $result = $expressionLanguage->evaluate($expression, ['foo' => (object) ['not' => 'test'], 'bar' => 'test']);
+ $this->assertTrue($result);
}
/**
* @dataProvider getRegisterCallbacks
- * @expectedException \LogicException
*/
public function testRegisterAfterParse($registerCallback)
{
+ $this->expectException('LogicException');
$el = new ExpressionLanguage();
- $el->parse('1 + 1', array());
+ $el->parse('1 + 1', []);
$registerCallback($el);
}
/**
* @dataProvider getRegisterCallbacks
- * @expectedException \LogicException
*/
public function testRegisterAfterEval($registerCallback)
{
+ $this->expectException('LogicException');
$el = new ExpressionLanguage();
$el->evaluate('1 + 1');
$registerCallback($el);
}
- /**
- * @expectedException \RuntimeException
- * @expectedExceptionMessageRegExp /Unable to call method "\w+" of object "\w+"./
- */
public function testCallBadCallable()
{
+ $this->expectException('RuntimeException');
+ $this->expectExceptionMessageMatches('/Unable to call method "\w+" of object "\w+"./');
$el = new ExpressionLanguage();
- $el->evaluate('foo.myfunction()', array('foo' => new \stdClass()));
+ $el->evaluate('foo.myfunction()', ['foo' => new \stdClass()]);
}
/**
* @dataProvider getRegisterCallbacks
- * @expectedException \LogicException
*/
public function testRegisterAfterCompile($registerCallback)
{
+ $this->expectException('LogicException');
$el = new ExpressionLanguage();
$el->compile('1 + 1');
$registerCallback($el);
public function getRegisterCallbacks()
{
- return array(
- array(
+ return [
+ [
function (ExpressionLanguage $el) {
$el->register('fn', function () {}, function () {});
},
- ),
- array(
+ ],
+ [
function (ExpressionLanguage $el) {
$el->addFunction(new ExpressionFunction('fn', function () {}, function () {}));
},
- ),
- array(
+ ],
+ [
function (ExpressionLanguage $el) {
$el->registerProvider(new TestProvider());
},
- ),
- );
+ ],
+ ];
}
}
{
public function getFunctions()
{
- return array(
+ return [
new ExpressionFunction('identity', function ($input) {
return $input;
}, function (array $values, $input) {
ExpressionFunction::fromPhp('\strtolower'),
ExpressionFunction::fromPhp('Symfony\Component\ExpressionLanguage\Tests\Fixtures\fn_namespaced', 'fn_namespaced'),
- );
+ ];
}
}
*/
public function testTokenize($tokens, $expression)
{
- $tokens[] = new Token('end of expression', null, strlen($expression) + 1);
+ $tokens[] = new Token('end of expression', null, \strlen($expression) + 1);
$this->assertEquals(new TokenStream($tokens, $expression), $this->lexer->tokenize($expression));
}
- /**
- * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError
- * @expectedExceptionMessage Unexpected character "'" around position 33 for expression `service(faulty.expression.example').dummyMethod()`.
- */
public function testTokenizeThrowsErrorWithMessage()
{
+ $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError');
+ $this->expectExceptionMessage('Unexpected character "\'" around position 33 for expression `service(faulty.expression.example\').dummyMethod()`.');
$expression = "service(faulty.expression.example').dummyMethod()";
$this->lexer->tokenize($expression);
}
- /**
- * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError
- * @expectedExceptionMessage Unclosed "(" around position 7 for expression `service(unclosed.expression.dummyMethod()`.
- */
public function testTokenizeThrowsErrorOnUnclosedBrace()
{
+ $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError');
+ $this->expectExceptionMessage('Unclosed "(" around position 7 for expression `service(unclosed.expression.dummyMethod()`.');
$expression = 'service(unclosed.expression.dummyMethod()';
$this->lexer->tokenize($expression);
}
public function getTokenizeData()
{
- return array(
- array(
- array(new Token('name', 'a', 3)),
+ return [
+ [
+ [new Token('name', 'a', 3)],
' a ',
- ),
- array(
- array(new Token('name', 'a', 1)),
+ ],
+ [
+ [new Token('name', 'a', 1)],
'a',
- ),
- array(
- array(new Token('string', 'foo', 1)),
+ ],
+ [
+ [new Token('string', 'foo', 1)],
'"foo"',
- ),
- array(
- array(new Token('number', '3', 1)),
+ ],
+ [
+ [new Token('number', '3', 1)],
'3',
- ),
- array(
- array(new Token('operator', '+', 1)),
+ ],
+ [
+ [new Token('operator', '+', 1)],
'+',
- ),
- array(
- array(new Token('punctuation', '.', 1)),
+ ],
+ [
+ [new Token('punctuation', '.', 1)],
'.',
- ),
- array(
- array(
+ ],
+ [
+ [
new Token('punctuation', '(', 1),
new Token('number', '3', 2),
new Token('operator', '+', 4),
new Token('punctuation', '[', 25),
new Token('number', '4', 26),
new Token('punctuation', ']', 27),
- ),
+ ],
'(3 + 5) ~ foo("bar").baz[4]',
- ),
- array(
- array(new Token('operator', '..', 1)),
+ ],
+ [
+ [new Token('operator', '..', 1)],
'..',
- ),
- array(
- array(new Token('string', '#foo', 1)),
+ ],
+ [
+ [new Token('string', '#foo', 1)],
"'#foo'",
- ),
- array(
- array(new Token('string', '#foo', 1)),
+ ],
+ [
+ [new Token('string', '#foo', 1)],
'"#foo"',
- ),
- );
+ ],
+ [
+ [
+ new Token('name', 'foo', 1),
+ new Token('punctuation', '.', 4),
+ new Token('name', 'not', 5),
+ new Token('operator', 'in', 9),
+ new Token('punctuation', '[', 12),
+ new Token('name', 'bar', 13),
+ new Token('punctuation', ']', 16),
+ ],
+ 'foo.not in [bar]',
+ ],
+ ];
}
}
/**
* @dataProvider getEvaluateData
*/
- public function testEvaluate($expected, $node, $variables = array(), $functions = array())
+ public function testEvaluate($expected, $node, $variables = [], $functions = [])
{
$this->assertSame($expected, $node->evaluate($functions, $variables));
}
/**
* @dataProvider getCompileData
*/
- public function testCompile($expected, $node, $functions = array())
+ public function testCompile($expected, $node, $functions = [])
{
$compiler = new Compiler($functions);
$node->compile($compiler);
{
public function getCompileData()
{
- return array(
- array('"a", "b"', $this->getArrayNode()),
- );
+ return [
+ ['"a", "b"', $this->getArrayNode()],
+ ];
}
public function getDumpData()
{
- return array(
- array('"a", "b"', $this->getArrayNode()),
- );
+ return [
+ ['"a", "b"', $this->getArrayNode()],
+ ];
}
protected function createArrayNode()
public function getEvaluateData()
{
- return array(
- array(array('b' => 'a', 'b'), $this->getArrayNode()),
- );
+ return [
+ [['b' => 'a', 'b'], $this->getArrayNode()],
+ ];
}
public function getCompileData()
{
- return array(
- array('array("b" => "a", 0 => "b")', $this->getArrayNode()),
- );
+ return [
+ ['["b" => "a", 0 => "b"]', $this->getArrayNode()],
+ ];
}
public function getDumpData()
{
- yield array('{"b": "a", 0: "b"}', $this->getArrayNode());
+ yield ['{"b": "a", 0: "b"}', $this->getArrayNode()];
$array = $this->createArrayNode();
$array->addElement(new ConstantNode('c'), new ConstantNode('a"b'));
$array->addElement(new ConstantNode('d'), new ConstantNode('a\b'));
- yield array('{"a\\"b": "c", "a\\\\b": "d"}', $array);
+ yield ['{"a\\"b": "c", "a\\\\b": "d"}', $array];
$array = $this->createArrayNode();
$array->addElement(new ConstantNode('c'));
$array->addElement(new ConstantNode('d'));
- yield array('["c", "d"]', $array);
+ yield ['["c", "d"]', $array];
}
protected function getArrayNode()
namespace Symfony\Component\ExpressionLanguage\Tests\Node;
-use Symfony\Component\ExpressionLanguage\Node\BinaryNode;
use Symfony\Component\ExpressionLanguage\Node\ArrayNode;
+use Symfony\Component\ExpressionLanguage\Node\BinaryNode;
use Symfony\Component\ExpressionLanguage\Node\ConstantNode;
class BinaryNodeTest extends AbstractNodeTest
$array->addElement(new ConstantNode('a'));
$array->addElement(new ConstantNode('b'));
- return array(
- array(true, new BinaryNode('or', new ConstantNode(true), new ConstantNode(false))),
- array(true, new BinaryNode('||', new ConstantNode(true), new ConstantNode(false))),
- array(false, new BinaryNode('and', new ConstantNode(true), new ConstantNode(false))),
- array(false, new BinaryNode('&&', new ConstantNode(true), new ConstantNode(false))),
+ return [
+ [true, new BinaryNode('or', new ConstantNode(true), new ConstantNode(false))],
+ [true, new BinaryNode('||', new ConstantNode(true), new ConstantNode(false))],
+ [false, new BinaryNode('and', new ConstantNode(true), new ConstantNode(false))],
+ [false, new BinaryNode('&&', new ConstantNode(true), new ConstantNode(false))],
- array(0, new BinaryNode('&', new ConstantNode(2), new ConstantNode(4))),
- array(6, new BinaryNode('|', new ConstantNode(2), new ConstantNode(4))),
- array(6, new BinaryNode('^', new ConstantNode(2), new ConstantNode(4))),
+ [0, new BinaryNode('&', new ConstantNode(2), new ConstantNode(4))],
+ [6, new BinaryNode('|', new ConstantNode(2), new ConstantNode(4))],
+ [6, new BinaryNode('^', new ConstantNode(2), new ConstantNode(4))],
- array(true, new BinaryNode('<', new ConstantNode(1), new ConstantNode(2))),
- array(true, new BinaryNode('<=', new ConstantNode(1), new ConstantNode(2))),
- array(true, new BinaryNode('<=', new ConstantNode(1), new ConstantNode(1))),
+ [true, new BinaryNode('<', new ConstantNode(1), new ConstantNode(2))],
+ [true, new BinaryNode('<=', new ConstantNode(1), new ConstantNode(2))],
+ [true, new BinaryNode('<=', new ConstantNode(1), new ConstantNode(1))],
- array(false, new BinaryNode('>', new ConstantNode(1), new ConstantNode(2))),
- array(false, new BinaryNode('>=', new ConstantNode(1), new ConstantNode(2))),
- array(true, new BinaryNode('>=', new ConstantNode(1), new ConstantNode(1))),
+ [false, new BinaryNode('>', new ConstantNode(1), new ConstantNode(2))],
+ [false, new BinaryNode('>=', new ConstantNode(1), new ConstantNode(2))],
+ [true, new BinaryNode('>=', new ConstantNode(1), new ConstantNode(1))],
- array(true, new BinaryNode('===', new ConstantNode(true), new ConstantNode(true))),
- array(false, new BinaryNode('!==', new ConstantNode(true), new ConstantNode(true))),
+ [true, new BinaryNode('===', new ConstantNode(true), new ConstantNode(true))],
+ [false, new BinaryNode('!==', new ConstantNode(true), new ConstantNode(true))],
- array(false, new BinaryNode('==', new ConstantNode(2), new ConstantNode(1))),
- array(true, new BinaryNode('!=', new ConstantNode(2), new ConstantNode(1))),
+ [false, new BinaryNode('==', new ConstantNode(2), new ConstantNode(1))],
+ [true, new BinaryNode('!=', new ConstantNode(2), new ConstantNode(1))],
- array(-1, new BinaryNode('-', new ConstantNode(1), new ConstantNode(2))),
- array(3, new BinaryNode('+', new ConstantNode(1), new ConstantNode(2))),
- array(4, new BinaryNode('*', new ConstantNode(2), new ConstantNode(2))),
- array(1, new BinaryNode('/', new ConstantNode(2), new ConstantNode(2))),
- array(1, new BinaryNode('%', new ConstantNode(5), new ConstantNode(2))),
- array(25, new BinaryNode('**', new ConstantNode(5), new ConstantNode(2))),
- array('ab', new BinaryNode('~', new ConstantNode('a'), new ConstantNode('b'))),
+ [-1, new BinaryNode('-', new ConstantNode(1), new ConstantNode(2))],
+ [3, new BinaryNode('+', new ConstantNode(1), new ConstantNode(2))],
+ [4, new BinaryNode('*', new ConstantNode(2), new ConstantNode(2))],
+ [1, new BinaryNode('/', new ConstantNode(2), new ConstantNode(2))],
+ [1, new BinaryNode('%', new ConstantNode(5), new ConstantNode(2))],
+ [25, new BinaryNode('**', new ConstantNode(5), new ConstantNode(2))],
+ ['ab', new BinaryNode('~', new ConstantNode('a'), new ConstantNode('b'))],
- array(true, new BinaryNode('in', new ConstantNode('a'), $array)),
- array(false, new BinaryNode('in', new ConstantNode('c'), $array)),
- array(true, new BinaryNode('not in', new ConstantNode('c'), $array)),
- array(false, new BinaryNode('not in', new ConstantNode('a'), $array)),
+ [true, new BinaryNode('in', new ConstantNode('a'), $array)],
+ [false, new BinaryNode('in', new ConstantNode('c'), $array)],
+ [true, new BinaryNode('not in', new ConstantNode('c'), $array)],
+ [false, new BinaryNode('not in', new ConstantNode('a'), $array)],
- array(array(1, 2, 3), new BinaryNode('..', new ConstantNode(1), new ConstantNode(3))),
+ [[1, 2, 3], new BinaryNode('..', new ConstantNode(1), new ConstantNode(3))],
- array(1, new BinaryNode('matches', new ConstantNode('abc'), new ConstantNode('/^[a-z]+$/'))),
- );
+ [1, new BinaryNode('matches', new ConstantNode('abc'), new ConstantNode('/^[a-z]+$/'))],
+ ];
}
public function getCompileData()
$array->addElement(new ConstantNode('a'));
$array->addElement(new ConstantNode('b'));
- return array(
- array('(true || false)', new BinaryNode('or', new ConstantNode(true), new ConstantNode(false))),
- array('(true || false)', new BinaryNode('||', new ConstantNode(true), new ConstantNode(false))),
- array('(true && false)', new BinaryNode('and', new ConstantNode(true), new ConstantNode(false))),
- array('(true && false)', new BinaryNode('&&', new ConstantNode(true), new ConstantNode(false))),
+ return [
+ ['(true || false)', new BinaryNode('or', new ConstantNode(true), new ConstantNode(false))],
+ ['(true || false)', new BinaryNode('||', new ConstantNode(true), new ConstantNode(false))],
+ ['(true && false)', new BinaryNode('and', new ConstantNode(true), new ConstantNode(false))],
+ ['(true && false)', new BinaryNode('&&', new ConstantNode(true), new ConstantNode(false))],
- array('(2 & 4)', new BinaryNode('&', new ConstantNode(2), new ConstantNode(4))),
- array('(2 | 4)', new BinaryNode('|', new ConstantNode(2), new ConstantNode(4))),
- array('(2 ^ 4)', new BinaryNode('^', new ConstantNode(2), new ConstantNode(4))),
+ ['(2 & 4)', new BinaryNode('&', new ConstantNode(2), new ConstantNode(4))],
+ ['(2 | 4)', new BinaryNode('|', new ConstantNode(2), new ConstantNode(4))],
+ ['(2 ^ 4)', new BinaryNode('^', new ConstantNode(2), new ConstantNode(4))],
- array('(1 < 2)', new BinaryNode('<', new ConstantNode(1), new ConstantNode(2))),
- array('(1 <= 2)', new BinaryNode('<=', new ConstantNode(1), new ConstantNode(2))),
- array('(1 <= 1)', new BinaryNode('<=', new ConstantNode(1), new ConstantNode(1))),
+ ['(1 < 2)', new BinaryNode('<', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 <= 2)', new BinaryNode('<=', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 <= 1)', new BinaryNode('<=', new ConstantNode(1), new ConstantNode(1))],
- array('(1 > 2)', new BinaryNode('>', new ConstantNode(1), new ConstantNode(2))),
- array('(1 >= 2)', new BinaryNode('>=', new ConstantNode(1), new ConstantNode(2))),
- array('(1 >= 1)', new BinaryNode('>=', new ConstantNode(1), new ConstantNode(1))),
+ ['(1 > 2)', new BinaryNode('>', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 >= 2)', new BinaryNode('>=', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 >= 1)', new BinaryNode('>=', new ConstantNode(1), new ConstantNode(1))],
- array('(true === true)', new BinaryNode('===', new ConstantNode(true), new ConstantNode(true))),
- array('(true !== true)', new BinaryNode('!==', new ConstantNode(true), new ConstantNode(true))),
+ ['(true === true)', new BinaryNode('===', new ConstantNode(true), new ConstantNode(true))],
+ ['(true !== true)', new BinaryNode('!==', new ConstantNode(true), new ConstantNode(true))],
- array('(2 == 1)', new BinaryNode('==', new ConstantNode(2), new ConstantNode(1))),
- array('(2 != 1)', new BinaryNode('!=', new ConstantNode(2), new ConstantNode(1))),
+ ['(2 == 1)', new BinaryNode('==', new ConstantNode(2), new ConstantNode(1))],
+ ['(2 != 1)', new BinaryNode('!=', new ConstantNode(2), new ConstantNode(1))],
- array('(1 - 2)', new BinaryNode('-', new ConstantNode(1), new ConstantNode(2))),
- array('(1 + 2)', new BinaryNode('+', new ConstantNode(1), new ConstantNode(2))),
- array('(2 * 2)', new BinaryNode('*', new ConstantNode(2), new ConstantNode(2))),
- array('(2 / 2)', new BinaryNode('/', new ConstantNode(2), new ConstantNode(2))),
- array('(5 % 2)', new BinaryNode('%', new ConstantNode(5), new ConstantNode(2))),
- array('pow(5, 2)', new BinaryNode('**', new ConstantNode(5), new ConstantNode(2))),
- array('("a" . "b")', new BinaryNode('~', new ConstantNode('a'), new ConstantNode('b'))),
+ ['(1 - 2)', new BinaryNode('-', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 + 2)', new BinaryNode('+', new ConstantNode(1), new ConstantNode(2))],
+ ['(2 * 2)', new BinaryNode('*', new ConstantNode(2), new ConstantNode(2))],
+ ['(2 / 2)', new BinaryNode('/', new ConstantNode(2), new ConstantNode(2))],
+ ['(5 % 2)', new BinaryNode('%', new ConstantNode(5), new ConstantNode(2))],
+ ['pow(5, 2)', new BinaryNode('**', new ConstantNode(5), new ConstantNode(2))],
+ ['("a" . "b")', new BinaryNode('~', new ConstantNode('a'), new ConstantNode('b'))],
- array('in_array("a", array(0 => "a", 1 => "b"))', new BinaryNode('in', new ConstantNode('a'), $array)),
- array('in_array("c", array(0 => "a", 1 => "b"))', new BinaryNode('in', new ConstantNode('c'), $array)),
- array('!in_array("c", array(0 => "a", 1 => "b"))', new BinaryNode('not in', new ConstantNode('c'), $array)),
- array('!in_array("a", array(0 => "a", 1 => "b"))', new BinaryNode('not in', new ConstantNode('a'), $array)),
+ ['in_array("a", [0 => "a", 1 => "b"])', new BinaryNode('in', new ConstantNode('a'), $array)],
+ ['in_array("c", [0 => "a", 1 => "b"])', new BinaryNode('in', new ConstantNode('c'), $array)],
+ ['!in_array("c", [0 => "a", 1 => "b"])', new BinaryNode('not in', new ConstantNode('c'), $array)],
+ ['!in_array("a", [0 => "a", 1 => "b"])', new BinaryNode('not in', new ConstantNode('a'), $array)],
- array('range(1, 3)', new BinaryNode('..', new ConstantNode(1), new ConstantNode(3))),
+ ['range(1, 3)', new BinaryNode('..', new ConstantNode(1), new ConstantNode(3))],
- array('preg_match("/^[a-z]+/i\$/", "abc")', new BinaryNode('matches', new ConstantNode('abc'), new ConstantNode('/^[a-z]+/i$/'))),
- );
+ ['preg_match("/^[a-z]+/i\$/", "abc")', new BinaryNode('matches', new ConstantNode('abc'), new ConstantNode('/^[a-z]+/i$/'))],
+ ];
}
public function getDumpData()
$array->addElement(new ConstantNode('a'));
$array->addElement(new ConstantNode('b'));
- return array(
- array('(true or false)', new BinaryNode('or', new ConstantNode(true), new ConstantNode(false))),
- array('(true || false)', new BinaryNode('||', new ConstantNode(true), new ConstantNode(false))),
- array('(true and false)', new BinaryNode('and', new ConstantNode(true), new ConstantNode(false))),
- array('(true && false)', new BinaryNode('&&', new ConstantNode(true), new ConstantNode(false))),
+ return [
+ ['(true or false)', new BinaryNode('or', new ConstantNode(true), new ConstantNode(false))],
+ ['(true || false)', new BinaryNode('||', new ConstantNode(true), new ConstantNode(false))],
+ ['(true and false)', new BinaryNode('and', new ConstantNode(true), new ConstantNode(false))],
+ ['(true && false)', new BinaryNode('&&', new ConstantNode(true), new ConstantNode(false))],
- array('(2 & 4)', new BinaryNode('&', new ConstantNode(2), new ConstantNode(4))),
- array('(2 | 4)', new BinaryNode('|', new ConstantNode(2), new ConstantNode(4))),
- array('(2 ^ 4)', new BinaryNode('^', new ConstantNode(2), new ConstantNode(4))),
+ ['(2 & 4)', new BinaryNode('&', new ConstantNode(2), new ConstantNode(4))],
+ ['(2 | 4)', new BinaryNode('|', new ConstantNode(2), new ConstantNode(4))],
+ ['(2 ^ 4)', new BinaryNode('^', new ConstantNode(2), new ConstantNode(4))],
- array('(1 < 2)', new BinaryNode('<', new ConstantNode(1), new ConstantNode(2))),
- array('(1 <= 2)', new BinaryNode('<=', new ConstantNode(1), new ConstantNode(2))),
- array('(1 <= 1)', new BinaryNode('<=', new ConstantNode(1), new ConstantNode(1))),
+ ['(1 < 2)', new BinaryNode('<', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 <= 2)', new BinaryNode('<=', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 <= 1)', new BinaryNode('<=', new ConstantNode(1), new ConstantNode(1))],
- array('(1 > 2)', new BinaryNode('>', new ConstantNode(1), new ConstantNode(2))),
- array('(1 >= 2)', new BinaryNode('>=', new ConstantNode(1), new ConstantNode(2))),
- array('(1 >= 1)', new BinaryNode('>=', new ConstantNode(1), new ConstantNode(1))),
+ ['(1 > 2)', new BinaryNode('>', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 >= 2)', new BinaryNode('>=', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 >= 1)', new BinaryNode('>=', new ConstantNode(1), new ConstantNode(1))],
- array('(true === true)', new BinaryNode('===', new ConstantNode(true), new ConstantNode(true))),
- array('(true !== true)', new BinaryNode('!==', new ConstantNode(true), new ConstantNode(true))),
+ ['(true === true)', new BinaryNode('===', new ConstantNode(true), new ConstantNode(true))],
+ ['(true !== true)', new BinaryNode('!==', new ConstantNode(true), new ConstantNode(true))],
- array('(2 == 1)', new BinaryNode('==', new ConstantNode(2), new ConstantNode(1))),
- array('(2 != 1)', new BinaryNode('!=', new ConstantNode(2), new ConstantNode(1))),
+ ['(2 == 1)', new BinaryNode('==', new ConstantNode(2), new ConstantNode(1))],
+ ['(2 != 1)', new BinaryNode('!=', new ConstantNode(2), new ConstantNode(1))],
- array('(1 - 2)', new BinaryNode('-', new ConstantNode(1), new ConstantNode(2))),
- array('(1 + 2)', new BinaryNode('+', new ConstantNode(1), new ConstantNode(2))),
- array('(2 * 2)', new BinaryNode('*', new ConstantNode(2), new ConstantNode(2))),
- array('(2 / 2)', new BinaryNode('/', new ConstantNode(2), new ConstantNode(2))),
- array('(5 % 2)', new BinaryNode('%', new ConstantNode(5), new ConstantNode(2))),
- array('(5 ** 2)', new BinaryNode('**', new ConstantNode(5), new ConstantNode(2))),
- array('("a" ~ "b")', new BinaryNode('~', new ConstantNode('a'), new ConstantNode('b'))),
+ ['(1 - 2)', new BinaryNode('-', new ConstantNode(1), new ConstantNode(2))],
+ ['(1 + 2)', new BinaryNode('+', new ConstantNode(1), new ConstantNode(2))],
+ ['(2 * 2)', new BinaryNode('*', new ConstantNode(2), new ConstantNode(2))],
+ ['(2 / 2)', new BinaryNode('/', new ConstantNode(2), new ConstantNode(2))],
+ ['(5 % 2)', new BinaryNode('%', new ConstantNode(5), new ConstantNode(2))],
+ ['(5 ** 2)', new BinaryNode('**', new ConstantNode(5), new ConstantNode(2))],
+ ['("a" ~ "b")', new BinaryNode('~', new ConstantNode('a'), new ConstantNode('b'))],
- array('("a" in ["a", "b"])', new BinaryNode('in', new ConstantNode('a'), $array)),
- array('("c" in ["a", "b"])', new BinaryNode('in', new ConstantNode('c'), $array)),
- array('("c" not in ["a", "b"])', new BinaryNode('not in', new ConstantNode('c'), $array)),
- array('("a" not in ["a", "b"])', new BinaryNode('not in', new ConstantNode('a'), $array)),
+ ['("a" in ["a", "b"])', new BinaryNode('in', new ConstantNode('a'), $array)],
+ ['("c" in ["a", "b"])', new BinaryNode('in', new ConstantNode('c'), $array)],
+ ['("c" not in ["a", "b"])', new BinaryNode('not in', new ConstantNode('c'), $array)],
+ ['("a" not in ["a", "b"])', new BinaryNode('not in', new ConstantNode('a'), $array)],
- array('(1 .. 3)', new BinaryNode('..', new ConstantNode(1), new ConstantNode(3))),
+ ['(1 .. 3)', new BinaryNode('..', new ConstantNode(1), new ConstantNode(3))],
- array('("abc" matches "/^[a-z]+/i$/")', new BinaryNode('matches', new ConstantNode('abc'), new ConstantNode('/^[a-z]+/i$/'))),
- );
+ ['("abc" matches "/^[a-z]+/i$/")', new BinaryNode('matches', new ConstantNode('abc'), new ConstantNode('/^[a-z]+/i$/'))],
+ ];
}
}
{
public function getEvaluateData()
{
- return array(
- array(1, new ConditionalNode(new ConstantNode(true), new ConstantNode(1), new ConstantNode(2))),
- array(2, new ConditionalNode(new ConstantNode(false), new ConstantNode(1), new ConstantNode(2))),
- );
+ return [
+ [1, new ConditionalNode(new ConstantNode(true), new ConstantNode(1), new ConstantNode(2))],
+ [2, new ConditionalNode(new ConstantNode(false), new ConstantNode(1), new ConstantNode(2))],
+ ];
}
public function getCompileData()
{
- return array(
- array('((true) ? (1) : (2))', new ConditionalNode(new ConstantNode(true), new ConstantNode(1), new ConstantNode(2))),
- array('((false) ? (1) : (2))', new ConditionalNode(new ConstantNode(false), new ConstantNode(1), new ConstantNode(2))),
- );
+ return [
+ ['((true) ? (1) : (2))', new ConditionalNode(new ConstantNode(true), new ConstantNode(1), new ConstantNode(2))],
+ ['((false) ? (1) : (2))', new ConditionalNode(new ConstantNode(false), new ConstantNode(1), new ConstantNode(2))],
+ ];
}
public function getDumpData()
{
- return array(
- array('(true ? 1 : 2)', new ConditionalNode(new ConstantNode(true), new ConstantNode(1), new ConstantNode(2))),
- array('(false ? 1 : 2)', new ConditionalNode(new ConstantNode(false), new ConstantNode(1), new ConstantNode(2))),
- );
+ return [
+ ['(true ? 1 : 2)', new ConditionalNode(new ConstantNode(true), new ConstantNode(1), new ConstantNode(2))],
+ ['(false ? 1 : 2)', new ConditionalNode(new ConstantNode(false), new ConstantNode(1), new ConstantNode(2))],
+ ];
}
}
{
public function getEvaluateData()
{
- return array(
- array(false, new ConstantNode(false)),
- array(true, new ConstantNode(true)),
- array(null, new ConstantNode(null)),
- array(3, new ConstantNode(3)),
- array(3.3, new ConstantNode(3.3)),
- array('foo', new ConstantNode('foo')),
- array(array(1, 'b' => 'a'), new ConstantNode(array(1, 'b' => 'a'))),
- );
+ return [
+ [false, new ConstantNode(false)],
+ [true, new ConstantNode(true)],
+ [null, new ConstantNode(null)],
+ [3, new ConstantNode(3)],
+ [3.3, new ConstantNode(3.3)],
+ ['foo', new ConstantNode('foo')],
+ [[1, 'b' => 'a'], new ConstantNode([1, 'b' => 'a'])],
+ ];
}
public function getCompileData()
{
- return array(
- array('false', new ConstantNode(false)),
- array('true', new ConstantNode(true)),
- array('null', new ConstantNode(null)),
- array('3', new ConstantNode(3)),
- array('3.3', new ConstantNode(3.3)),
- array('"foo"', new ConstantNode('foo')),
- array('array(0 => 1, "b" => "a")', new ConstantNode(array(1, 'b' => 'a'))),
- );
+ return [
+ ['false', new ConstantNode(false)],
+ ['true', new ConstantNode(true)],
+ ['null', new ConstantNode(null)],
+ ['3', new ConstantNode(3)],
+ ['3.3', new ConstantNode(3.3)],
+ ['"foo"', new ConstantNode('foo')],
+ ['[0 => 1, "b" => "a"]', new ConstantNode([1, 'b' => 'a'])],
+ ];
}
public function getDumpData()
{
- return array(
- array('false', new ConstantNode(false)),
- array('true', new ConstantNode(true)),
- array('null', new ConstantNode(null)),
- array('3', new ConstantNode(3)),
- array('3.3', new ConstantNode(3.3)),
- array('"foo"', new ConstantNode('foo')),
- array('foo', new ConstantNode('foo', true)),
- array('{0: 1, "b": "a", 1: true}', new ConstantNode(array(1, 'b' => 'a', true))),
- array('{"a\\"b": "c", "a\\\\b": "d"}', new ConstantNode(array('a"b' => 'c', 'a\\b' => 'd'))),
- array('["c", "d"]', new ConstantNode(array('c', 'd'))),
- array('{"a": ["b"]}', new ConstantNode(array('a' => array('b')))),
- );
+ return [
+ ['false', new ConstantNode(false)],
+ ['true', new ConstantNode(true)],
+ ['null', new ConstantNode(null)],
+ ['3', new ConstantNode(3)],
+ ['3.3', new ConstantNode(3.3)],
+ ['"foo"', new ConstantNode('foo')],
+ ['foo', new ConstantNode('foo', true)],
+ ['{0: 1, "b": "a", 1: true}', new ConstantNode([1, 'b' => 'a', true])],
+ ['{"a\\"b": "c", "a\\\\b": "d"}', new ConstantNode(['a"b' => 'c', 'a\\b' => 'd'])],
+ ['["c", "d"]', new ConstantNode(['c', 'd'])],
+ ['{"a": ["b"]}', new ConstantNode(['a' => ['b']])],
+ ];
}
}
namespace Symfony\Component\ExpressionLanguage\Tests\Node;
-use Symfony\Component\ExpressionLanguage\Node\FunctionNode;
use Symfony\Component\ExpressionLanguage\Node\ConstantNode;
+use Symfony\Component\ExpressionLanguage\Node\FunctionNode;
use Symfony\Component\ExpressionLanguage\Node\Node;
class FunctionNodeTest extends AbstractNodeTest
{
public function getEvaluateData()
{
- return array(
- array('bar', new FunctionNode('foo', new Node(array(new ConstantNode('bar')))), array(), array('foo' => $this->getCallables())),
- );
+ return [
+ ['bar', new FunctionNode('foo', new Node([new ConstantNode('bar')])), [], ['foo' => $this->getCallables()]],
+ ];
}
public function getCompileData()
{
- return array(
- array('foo("bar")', new FunctionNode('foo', new Node(array(new ConstantNode('bar')))), array('foo' => $this->getCallables())),
- );
+ return [
+ ['foo("bar")', new FunctionNode('foo', new Node([new ConstantNode('bar')])), ['foo' => $this->getCallables()]],
+ ];
}
public function getDumpData()
{
- return array(
- array('foo("bar")', new FunctionNode('foo', new Node(array(new ConstantNode('bar')))), array('foo' => $this->getCallables())),
- );
+ return [
+ ['foo("bar")', new FunctionNode('foo', new Node([new ConstantNode('bar')])), ['foo' => $this->getCallables()]],
+ ];
}
protected function getCallables()
{
- return array(
+ return [
'compiler' => function ($arg) {
return sprintf('foo(%s)', $arg);
},
'evaluator' => function ($variables, $arg) {
return $arg;
},
- );
+ ];
}
}
namespace Symfony\Component\ExpressionLanguage\Tests\Node;
use Symfony\Component\ExpressionLanguage\Node\ArrayNode;
-use Symfony\Component\ExpressionLanguage\Node\NameNode;
-use Symfony\Component\ExpressionLanguage\Node\GetAttrNode;
use Symfony\Component\ExpressionLanguage\Node\ConstantNode;
+use Symfony\Component\ExpressionLanguage\Node\GetAttrNode;
+use Symfony\Component\ExpressionLanguage\Node\NameNode;
class GetAttrNodeTest extends AbstractNodeTest
{
public function getEvaluateData()
{
- return array(
- array('b', new GetAttrNode(new NameNode('foo'), new ConstantNode(0), $this->getArrayNode(), GetAttrNode::ARRAY_CALL), array('foo' => array('b' => 'a', 'b'))),
- array('a', new GetAttrNode(new NameNode('foo'), new ConstantNode('b'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL), array('foo' => array('b' => 'a', 'b'))),
+ return [
+ ['b', new GetAttrNode(new NameNode('foo'), new ConstantNode(0), $this->getArrayNode(), GetAttrNode::ARRAY_CALL), ['foo' => ['b' => 'a', 'b']]],
+ ['a', new GetAttrNode(new NameNode('foo'), new ConstantNode('b'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL), ['foo' => ['b' => 'a', 'b']]],
- array('bar', new GetAttrNode(new NameNode('foo'), new ConstantNode('foo'), $this->getArrayNode(), GetAttrNode::PROPERTY_CALL), array('foo' => new Obj())),
+ ['bar', new GetAttrNode(new NameNode('foo'), new ConstantNode('foo'), $this->getArrayNode(), GetAttrNode::PROPERTY_CALL), ['foo' => new Obj()]],
- array('baz', new GetAttrNode(new NameNode('foo'), new ConstantNode('foo'), $this->getArrayNode(), GetAttrNode::METHOD_CALL), array('foo' => new Obj())),
- array('a', new GetAttrNode(new NameNode('foo'), new NameNode('index'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL), array('foo' => array('b' => 'a', 'b'), 'index' => 'b')),
- );
+ ['baz', new GetAttrNode(new NameNode('foo'), new ConstantNode('foo'), $this->getArrayNode(), GetAttrNode::METHOD_CALL), ['foo' => new Obj()]],
+ ['a', new GetAttrNode(new NameNode('foo'), new NameNode('index'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL), ['foo' => ['b' => 'a', 'b'], 'index' => 'b']],
+ ];
}
public function getCompileData()
{
- return array(
- array('$foo[0]', new GetAttrNode(new NameNode('foo'), new ConstantNode(0), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)),
- array('$foo["b"]', new GetAttrNode(new NameNode('foo'), new ConstantNode('b'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)),
+ return [
+ ['$foo[0]', new GetAttrNode(new NameNode('foo'), new ConstantNode(0), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)],
+ ['$foo["b"]', new GetAttrNode(new NameNode('foo'), new ConstantNode('b'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)],
- array('$foo->foo', new GetAttrNode(new NameNode('foo'), new ConstantNode('foo'), $this->getArrayNode(), GetAttrNode::PROPERTY_CALL), array('foo' => new Obj())),
+ ['$foo->foo', new GetAttrNode(new NameNode('foo'), new ConstantNode('foo'), $this->getArrayNode(), GetAttrNode::PROPERTY_CALL), ['foo' => new Obj()]],
- array('$foo->foo(array("b" => "a", 0 => "b"))', new GetAttrNode(new NameNode('foo'), new ConstantNode('foo'), $this->getArrayNode(), GetAttrNode::METHOD_CALL), array('foo' => new Obj())),
- array('$foo[$index]', new GetAttrNode(new NameNode('foo'), new NameNode('index'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)),
- );
+ ['$foo->foo(["b" => "a", 0 => "b"])', new GetAttrNode(new NameNode('foo'), new ConstantNode('foo'), $this->getArrayNode(), GetAttrNode::METHOD_CALL), ['foo' => new Obj()]],
+ ['$foo[$index]', new GetAttrNode(new NameNode('foo'), new NameNode('index'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)],
+ ];
}
public function getDumpData()
{
- return array(
- array('foo[0]', new GetAttrNode(new NameNode('foo'), new ConstantNode(0), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)),
- array('foo["b"]', new GetAttrNode(new NameNode('foo'), new ConstantNode('b'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)),
+ return [
+ ['foo[0]', new GetAttrNode(new NameNode('foo'), new ConstantNode(0), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)],
+ ['foo["b"]', new GetAttrNode(new NameNode('foo'), new ConstantNode('b'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)],
- array('foo.foo', new GetAttrNode(new NameNode('foo'), new NameNode('foo'), $this->getArrayNode(), GetAttrNode::PROPERTY_CALL), array('foo' => new Obj())),
+ ['foo.foo', new GetAttrNode(new NameNode('foo'), new NameNode('foo'), $this->getArrayNode(), GetAttrNode::PROPERTY_CALL), ['foo' => new Obj()]],
- array('foo.foo({"b": "a", 0: "b"})', new GetAttrNode(new NameNode('foo'), new NameNode('foo'), $this->getArrayNode(), GetAttrNode::METHOD_CALL), array('foo' => new Obj())),
- array('foo[index]', new GetAttrNode(new NameNode('foo'), new NameNode('index'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)),
- );
+ ['foo.foo({"b": "a", 0: "b"})', new GetAttrNode(new NameNode('foo'), new NameNode('foo'), $this->getArrayNode(), GetAttrNode::METHOD_CALL), ['foo' => new Obj()]],
+ ['foo[index]', new GetAttrNode(new NameNode('foo'), new NameNode('index'), $this->getArrayNode(), GetAttrNode::ARRAY_CALL)],
+ ];
}
protected function getArrayNode()
{
public function getEvaluateData()
{
- return array(
- array('bar', new NameNode('foo'), array('foo' => 'bar')),
- );
+ return [
+ ['bar', new NameNode('foo'), ['foo' => 'bar']],
+ ];
}
public function getCompileData()
{
- return array(
- array('$foo', new NameNode('foo')),
- );
+ return [
+ ['$foo', new NameNode('foo')],
+ ];
}
public function getDumpData()
{
- return array(
- array('foo', new NameNode('foo')),
- );
+ return [
+ ['foo', new NameNode('foo')],
+ ];
}
}
namespace Symfony\Component\ExpressionLanguage\Tests\Node;
use PHPUnit\Framework\TestCase;
-use Symfony\Component\ExpressionLanguage\Node\Node;
use Symfony\Component\ExpressionLanguage\Node\ConstantNode;
+use Symfony\Component\ExpressionLanguage\Node\Node;
class NodeTest extends TestCase
{
public function testToString()
{
- $node = new Node(array(new ConstantNode('foo')));
+ $node = new Node([new ConstantNode('foo')]);
$this->assertEquals(<<<'EOF'
Node(
public function testSerialization()
{
- $node = new Node(array('foo' => 'bar'), array('bar' => 'foo'));
+ $node = new Node(['foo' => 'bar'], ['bar' => 'foo']);
$serializedNode = serialize($node);
$unserializedNode = unserialize($serializedNode);
namespace Symfony\Component\ExpressionLanguage\Tests\Node;
-use Symfony\Component\ExpressionLanguage\Node\UnaryNode;
use Symfony\Component\ExpressionLanguage\Node\ConstantNode;
+use Symfony\Component\ExpressionLanguage\Node\UnaryNode;
class UnaryNodeTest extends AbstractNodeTest
{
public function getEvaluateData()
{
- return array(
- array(-1, new UnaryNode('-', new ConstantNode(1))),
- array(3, new UnaryNode('+', new ConstantNode(3))),
- array(false, new UnaryNode('!', new ConstantNode(true))),
- array(false, new UnaryNode('not', new ConstantNode(true))),
- );
+ return [
+ [-1, new UnaryNode('-', new ConstantNode(1))],
+ [3, new UnaryNode('+', new ConstantNode(3))],
+ [false, new UnaryNode('!', new ConstantNode(true))],
+ [false, new UnaryNode('not', new ConstantNode(true))],
+ ];
}
public function getCompileData()
{
- return array(
- array('(-1)', new UnaryNode('-', new ConstantNode(1))),
- array('(+3)', new UnaryNode('+', new ConstantNode(3))),
- array('(!true)', new UnaryNode('!', new ConstantNode(true))),
- array('(!true)', new UnaryNode('not', new ConstantNode(true))),
- );
+ return [
+ ['(-1)', new UnaryNode('-', new ConstantNode(1))],
+ ['(+3)', new UnaryNode('+', new ConstantNode(3))],
+ ['(!true)', new UnaryNode('!', new ConstantNode(true))],
+ ['(!true)', new UnaryNode('not', new ConstantNode(true))],
+ ];
}
public function getDumpData()
{
- return array(
- array('(- 1)', new UnaryNode('-', new ConstantNode(1))),
- array('(+ 3)', new UnaryNode('+', new ConstantNode(3))),
- array('(! true)', new UnaryNode('!', new ConstantNode(true))),
- array('(not true)', new UnaryNode('not', new ConstantNode(true))),
- );
+ return [
+ ['(- 1)', new UnaryNode('-', new ConstantNode(1))],
+ ['(+ 3)', new UnaryNode('+', new ConstantNode(3))],
+ ['(! true)', new UnaryNode('!', new ConstantNode(true))],
+ ['(not true)', new UnaryNode('not', new ConstantNode(true))],
+ ];
}
}
namespace Symfony\Component\ExpressionLanguage\Tests;
use PHPUnit\Framework\TestCase;
+use Symfony\Component\ExpressionLanguage\Node\Node;
use Symfony\Component\ExpressionLanguage\ParsedExpression;
use Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheAdapter;
-use Symfony\Component\ExpressionLanguage\Node\Node;
/**
* @group legacy
$cacheItem = $parserCacheAdapter->getItem($key);
- $this->assertEquals($cacheItem->get(), $value);
- $this->assertEquals($cacheItem->isHit(), true);
+ $this->assertEquals($value, $cacheItem->get());
+ $this->assertTrue($cacheItem->isHit());
}
public function testSave()
$poolMock = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface')->getMock();
$cacheItemMock = $this->getMockBuilder('Psr\Cache\CacheItemInterface')->getMock();
$key = 'key';
- $value = new ParsedExpression('1 + 1', new Node(array(), array()));
+ $value = new ParsedExpression('1 + 1', new Node([], []));
$parserCacheAdapter = new ParserCacheAdapter($poolMock);
$poolMock
->willReturn($value)
;
- $cacheItem = $parserCacheAdapter->save($cacheItemMock);
+ $parserCacheAdapter->save($cacheItemMock);
}
public function testGetItems()
{
$poolMock = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface')->getMock();
$parserCacheAdapter = new ParserCacheAdapter($poolMock);
- $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(\BadMethodCallException::class);
+ $this->expectException(\BadMethodCallException::class);
$parserCacheAdapter->getItems();
}
$poolMock = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface')->getMock();
$key = 'key';
$parserCacheAdapter = new ParserCacheAdapter($poolMock);
- $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(\BadMethodCallException::class);
+ $this->expectException(\BadMethodCallException::class);
$parserCacheAdapter->hasItem($key);
}
{
$poolMock = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface')->getMock();
$parserCacheAdapter = new ParserCacheAdapter($poolMock);
- $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(\BadMethodCallException::class);
+ $this->expectException(\BadMethodCallException::class);
$parserCacheAdapter->clear();
}
$poolMock = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface')->getMock();
$key = 'key';
$parserCacheAdapter = new ParserCacheAdapter($poolMock);
- $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(\BadMethodCallException::class);
+ $this->expectException(\BadMethodCallException::class);
$parserCacheAdapter->deleteItem($key);
}
public function testDeleteItems()
{
$poolMock = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface')->getMock();
- $keys = array('key');
+ $keys = ['key'];
$parserCacheAdapter = new ParserCacheAdapter($poolMock);
- $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(\BadMethodCallException::class);
+ $this->expectException(\BadMethodCallException::class);
$parserCacheAdapter->deleteItems($keys);
}
$poolMock = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface')->getMock();
$parserCacheAdapter = new ParserCacheAdapter($poolMock);
$cacheItemMock = $this->getMockBuilder('Psr\Cache\CacheItemInterface')->getMock();
- $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(\BadMethodCallException::class);
+ $this->expectException(\BadMethodCallException::class);
$parserCacheAdapter->saveDeferred($cacheItemMock);
}
{
$poolMock = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface')->getMock();
$parserCacheAdapter = new ParserCacheAdapter($poolMock);
- $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(\BadMethodCallException::class);
+ $this->expectException(\BadMethodCallException::class);
$parserCacheAdapter->commit();
}
namespace Symfony\Component\ExpressionLanguage\Tests;
use PHPUnit\Framework\TestCase;
-use Symfony\Component\ExpressionLanguage\Parser;
use Symfony\Component\ExpressionLanguage\Lexer;
use Symfony\Component\ExpressionLanguage\Node;
+use Symfony\Component\ExpressionLanguage\Parser;
class ParserTest extends TestCase
{
- /**
- * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError
- * @expectedExceptionMessage Variable "foo" is not valid around position 1 for expression `foo`.
- */
public function testParseWithInvalidName()
{
+ $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError');
+ $this->expectExceptionMessage('Variable "foo" is not valid around position 1 for expression `foo`.');
$lexer = new Lexer();
- $parser = new Parser(array());
+ $parser = new Parser([]);
$parser->parse($lexer->tokenize('foo'));
}
- /**
- * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError
- * @expectedExceptionMessage Variable "foo" is not valid around position 1 for expression `foo`.
- */
public function testParseWithZeroInNames()
{
+ $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError');
+ $this->expectExceptionMessage('Variable "foo" is not valid around position 1 for expression `foo`.');
$lexer = new Lexer();
- $parser = new Parser(array());
- $parser->parse($lexer->tokenize('foo'), array(0));
+ $parser = new Parser([]);
+ $parser->parse($lexer->tokenize('foo'), [0]);
}
/**
* @dataProvider getParseData
*/
- public function testParse($node, $expression, $names = array())
+ public function testParse($node, $expression, $names = [])
{
$lexer = new Lexer();
- $parser = new Parser(array());
+ $parser = new Parser([]);
$this->assertEquals($node, $parser->parse($lexer->tokenize($expression), $names));
}
$arguments->addElement(new Node\ConstantNode(2));
$arguments->addElement(new Node\ConstantNode(true));
- return array(
- array(
+ $arrayNode = new Node\ArrayNode();
+ $arrayNode->addElement(new Node\NameNode('bar'));
+
+ return [
+ [
new Node\NameNode('a'),
'a',
- array('a'),
- ),
- array(
+ ['a'],
+ ],
+ [
new Node\ConstantNode('a'),
'"a"',
- ),
- array(
+ ],
+ [
new Node\ConstantNode(3),
'3',
- ),
- array(
+ ],
+ [
new Node\ConstantNode(false),
'false',
- ),
- array(
+ ],
+ [
new Node\ConstantNode(true),
'true',
- ),
- array(
+ ],
+ [
new Node\ConstantNode(null),
'null',
- ),
- array(
+ ],
+ [
new Node\UnaryNode('-', new Node\ConstantNode(3)),
'-3',
- ),
- array(
+ ],
+ [
new Node\BinaryNode('-', new Node\ConstantNode(3), new Node\ConstantNode(3)),
'3 - 3',
- ),
- array(
+ ],
+ [
new Node\BinaryNode('*',
new Node\BinaryNode('-', new Node\ConstantNode(3), new Node\ConstantNode(3)),
new Node\ConstantNode(2)
),
'(3 - 3) * 2',
- ),
- array(
+ ],
+ [
new Node\GetAttrNode(new Node\NameNode('foo'), new Node\ConstantNode('bar', true), new Node\ArgumentsNode(), Node\GetAttrNode::PROPERTY_CALL),
'foo.bar',
- array('foo'),
- ),
- array(
+ ['foo'],
+ ],
+ [
new Node\GetAttrNode(new Node\NameNode('foo'), new Node\ConstantNode('bar', true), new Node\ArgumentsNode(), Node\GetAttrNode::METHOD_CALL),
'foo.bar()',
- array('foo'),
- ),
- array(
+ ['foo'],
+ ],
+ [
new Node\GetAttrNode(new Node\NameNode('foo'), new Node\ConstantNode('not', true), new Node\ArgumentsNode(), Node\GetAttrNode::METHOD_CALL),
'foo.not()',
- array('foo'),
- ),
- array(
+ ['foo'],
+ ],
+ [
new Node\GetAttrNode(
new Node\NameNode('foo'),
new Node\ConstantNode('bar', true),
Node\GetAttrNode::METHOD_CALL
),
'foo.bar("arg1", 2, true)',
- array('foo'),
- ),
- array(
+ ['foo'],
+ ],
+ [
new Node\GetAttrNode(new Node\NameNode('foo'), new Node\ConstantNode(3), new Node\ArgumentsNode(), Node\GetAttrNode::ARRAY_CALL),
'foo[3]',
- array('foo'),
- ),
- array(
+ ['foo'],
+ ],
+ [
new Node\ConditionalNode(new Node\ConstantNode(true), new Node\ConstantNode(true), new Node\ConstantNode(false)),
'true ? true : false',
- ),
- array(
+ ],
+ [
new Node\BinaryNode('matches', new Node\ConstantNode('foo'), new Node\ConstantNode('/foo/')),
'"foo" matches "/foo/"',
- ),
+ ],
// chained calls
- array(
+ [
$this->createGetAttrNode(
$this->createGetAttrNode(
$this->createGetAttrNode(
'baz', Node\GetAttrNode::PROPERTY_CALL),
'3', Node\GetAttrNode::ARRAY_CALL),
'foo.bar().foo().baz[3]',
- array('foo'),
- ),
+ ['foo'],
+ ],
- array(
+ [
new Node\NameNode('foo'),
'bar',
- array('foo' => 'bar'),
- ),
- );
+ ['foo' => 'bar'],
+ ],
+
+ // Operators collisions
+ [
+ new Node\BinaryNode(
+ 'in',
+ new Node\GetAttrNode(
+ new Node\NameNode('foo'),
+ new Node\ConstantNode('not', true),
+ new Node\ArgumentsNode(),
+ Node\GetAttrNode::PROPERTY_CALL
+ ),
+ $arrayNode
+ ),
+ 'foo.not in [bar]',
+ ['foo', 'bar'],
+ ],
+ [
+ new Node\BinaryNode(
+ 'or',
+ new Node\UnaryNode('not', new Node\NameNode('foo')),
+ new Node\GetAttrNode(
+ new Node\NameNode('foo'),
+ new Node\ConstantNode('not', true),
+ new Node\ArgumentsNode(),
+ Node\GetAttrNode::PROPERTY_CALL
+ )
+ ),
+ 'not foo or foo.not',
+ ['foo'],
+ ],
+ ];
}
private function createGetAttrNode($node, $item, $type)
/**
* @dataProvider getInvalidPostfixData
- * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError
*/
- public function testParseWithInvalidPostfixData($expr, $names = array())
+ public function testParseWithInvalidPostfixData($expr, $names = [])
{
+ $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError');
$lexer = new Lexer();
- $parser = new Parser(array());
+ $parser = new Parser([]);
$parser->parse($lexer->tokenize($expr), $names);
}
public function getInvalidPostfixData()
{
- return array(
- array(
+ return [
+ [
'foo."#"',
- array('foo'),
- ),
- array(
+ ['foo'],
+ ],
+ [
'foo."bar"',
- array('foo'),
- ),
- array(
+ ['foo'],
+ ],
+ [
'foo.**',
- array('foo'),
- ),
- array(
+ ['foo'],
+ ],
+ [
'foo.123',
- array('foo'),
- ),
- );
+ ['foo'],
+ ],
+ ];
}
- /**
- * @expectedException \Symfony\Component\ExpressionLanguage\SyntaxError
- * @expectedExceptionMessage Did you mean "baz"?
- */
public function testNameProposal()
{
+ $this->expectException('Symfony\Component\ExpressionLanguage\SyntaxError');
+ $this->expectExceptionMessage('Did you mean "baz"?');
$lexer = new Lexer();
- $parser = new Parser(array());
+ $parser = new Parser([]);
- $parser->parse($lexer->tokenize('foo > bar'), array('foo', 'baz'));
+ $parser->parse($lexer->tokenize('foo > bar'), ['foo', 'baz']);
}
}
/**
* Tests the current token for a type and/or a value.
*
- * @param array|int $type The type to test
+ * @param string $type The type to test
* @param string|null $value The token value
*
* @return bool
++$this->position;
if (!isset($this->tokens[$this->position])) {
- throw new SyntaxError('Unexpected end of expression', $this->current->cursor, $this->expression);
+ throw new SyntaxError('Unexpected end of expression.', $this->current->cursor, $this->expression);
}
$this->current = $this->tokens[$this->position];
{
$token = $this->current;
if (!$token->test($type, $value)) {
- throw new SyntaxError(sprintf('%sUnexpected token "%s" of value "%s" ("%s" expected%s)', $message ? $message.'. ' : '', $token->type, $token->value, $type, $value ? sprintf(' with value "%s"', $value) : ''), $token->cursor, $this->expression);
+ throw new SyntaxError(sprintf('%sUnexpected token "%s" of value "%s" ("%s" expected%s).', $message ? $message.'. ' : '', $token->type, $token->value, $type, $value ? sprintf(' with value "%s"', $value) : ''), $token->cursor, $this->expression);
}
$this->next();
}
],
"require": {
"php": "^5.5.9|>=7.0.8",
- "symfony/cache": "~3.1|~4.0"
+ "symfony/cache": "~3.1|~4.0",
+ "symfony/polyfill-php70": "~1.6"
},
"autoload": {
"psr-4": { "Symfony\\Component\\ExpressionLanguage\\": "" },
"/Tests/"
]
},
- "minimum-stability": "dev",
- "extra": {
- "branch-alias": {
- "dev-master": "3.4-dev"
- }
- }
+ "minimum-stability": "dev"
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
+ xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.2/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
{
public static function apcu_add($key, $var = null, $ttl = 0)
{
- if (!is_array($key)) {
+ if (!\is_array($key)) {
return apc_add($key, $var, $ttl);
}
- $errors = array();
+ $errors = [];
foreach ($key as $k => $v) {
if (!apc_add($k, $v, $ttl)) {
$errors[$k] = -1;
public static function apcu_store($key, $var = null, $ttl = 0)
{
- if (!is_array($key)) {
+ if (!\is_array($key)) {
return apc_store($key, $var, $ttl);
}
- $errors = array();
+ $errors = [];
foreach ($key as $k => $v) {
if (!apc_store($k, $v, $ttl)) {
$errors[$k] = -1;
public static function apcu_exists($keys)
{
- if (!is_array($keys)) {
+ if (!\is_array($keys)) {
return apc_exists($keys);
}
- $existing = array();
+ $existing = [];
foreach ($keys as $k) {
if (apc_exists($k)) {
$existing[$k] = true;
public static function apcu_fetch($key, &$success = null)
{
- if (!is_array($key)) {
+ if (!\is_array($key)) {
return apc_fetch($key, $success);
}
$succeeded = true;
- $values = array();
+ $values = [];
foreach ($key as $k) {
$v = apc_fetch($k, $success);
if ($success) {
public static function apcu_delete($key)
{
- if (!is_array($key)) {
+ if (!\is_array($key)) {
return apc_delete($key);
}
-Copyright (c) 2015-2018 Fabien Potencier
+Copyright (c) 2015-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
Symfony Polyfill / APCu
========================
-This component provides `apcu_*` functions and the `APCUIterator` class to users of the legacy APC extension.
+This component provides `apcu_*` functions and the `APCuIterator` class to users of the legacy APC extension.
More information can be found in the
-[main Polyfill README](https://github.com/symfony/polyfill/blob/master/README.md).
+[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md).
License
=======
return;
}
-if (!function_exists('apcu_add')) {
- if (extension_loaded('Zend Data Cache')) {
- function apcu_add($key, $var = null, $ttl = 0) { return p\Apcu::apcu_add($key, $var, $ttl); }
+if (\PHP_VERSION_ID >= 80000) {
+ return require __DIR__.'/bootstrap80.php';
+}
+
+if (extension_loaded('Zend Data Cache')) {
+ if (!function_exists('apcu_add')) {
+ function apcu_add($key, $value = null, $ttl = 0) { return p\Apcu::apcu_add($key, $value, $ttl); }
+ }
+ if (!function_exists('apcu_delete')) {
function apcu_delete($key) { return p\Apcu::apcu_delete($key); }
- function apcu_exists($keys) { return p\Apcu::apcu_exists($keys); }
+ }
+ if (!function_exists('apcu_exists')) {
+ function apcu_exists($key) { return p\Apcu::apcu_exists($key); }
+ }
+ if (!function_exists('apcu_fetch')) {
function apcu_fetch($key, &$success = null) { return p\Apcu::apcu_fetch($key, $success); }
- function apcu_store($key, $var = null, $ttl = 0) { return p\Apcu::apcu_store($key, $var, $ttl); }
- } else {
- function apcu_add($key, $var = null, $ttl = 0) { return apc_add($key, $var, $ttl); }
+ }
+ if (!function_exists('apcu_store')) {
+ function apcu_store($key, $value = null, $ttl = 0) { return p\Apcu::apcu_store($key, $value, $ttl); }
+ }
+} else {
+ if (!function_exists('apcu_add')) {
+ function apcu_add($key, $value = null, $ttl = 0) { return apc_add($key, $value, $ttl); }
+ }
+ if (!function_exists('apcu_delete')) {
function apcu_delete($key) { return apc_delete($key); }
- function apcu_exists($keys) { return apc_exists($keys); }
+ }
+ if (!function_exists('apcu_exists')) {
+ function apcu_exists($key) { return apc_exists($key); }
+ }
+ if (!function_exists('apcu_fetch')) {
function apcu_fetch($key, &$success = null) { return apc_fetch($key, $success); }
- function apcu_store($key, $var = null, $ttl = 0) { return apc_store($key, $var, $ttl); }
}
+ if (!function_exists('apcu_store')) {
+ function apcu_store($key, $value = null, $ttl = 0) { return apc_store($key, $value, $ttl); }
+ }
+}
+
+if (!function_exists('apcu_cache_info')) {
function apcu_cache_info($limited = false) { return apc_cache_info('user', $limited); }
+}
+if (!function_exists('apcu_cas')) {
function apcu_cas($key, $old, $new) { return apc_cas($key, $old, $new); }
+}
+if (!function_exists('apcu_clear_cache')) {
function apcu_clear_cache() { return apc_clear_cache('user'); }
+}
+if (!function_exists('apcu_dec')) {
function apcu_dec($key, $step = 1, &$success = false) { return apc_dec($key, $step, $success); }
+}
+if (!function_exists('apcu_inc')) {
function apcu_inc($key, $step = 1, &$success = false) { return apc_inc($key, $step, $success); }
+}
+if (!function_exists('apcu_sma_info')) {
function apcu_sma_info($limited = false) { return apc_sma_info($limited); }
}
-if (!class_exists('APCUIterator', false) && class_exists('APCIterator', false)) {
- class APCUIterator extends APCIterator
+if (!class_exists('APCuIterator', false) && class_exists('APCIterator', false)) {
+ class APCuIterator extends APCIterator
{
- public function __construct($search = null, $format = APC_ITER_ALL, $chunk_size = 100, $list = APC_LIST_ACTIVE)
+ public function __construct($search = null, $format = \APC_ITER_ALL, $chunk_size = 100, $list = \APC_LIST_ACTIVE)
{
parent::__construct('user', $search, $format, $chunk_size, $list);
}
--- /dev/null
+<?php
+
+/*
+ * This file is part of the Symfony package.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+use Symfony\Polyfill\Apcu as p;
+
+if (extension_loaded('Zend Data Cache')) {
+ if (!function_exists('apcu_add')) {
+ function apcu_add($key, mixed $value, ?int $ttl = 0): array|bool { return p\Apcu::apcu_add($key, $value, (int) $ttl); }
+ }
+ if (!function_exists('apcu_delete')) {
+ function apcu_delete($key): array|bool { return p\Apcu::apcu_delete($key); }
+ }
+ if (!function_exists('apcu_exists')) {
+ function apcu_exists($key): array|bool { return p\Apcu::apcu_exists($key); }
+ }
+ if (!function_exists('apcu_fetch')) {
+ function apcu_fetch($key, &$success = null): mixed { return p\Apcu::apcu_fetch($key, $success); }
+ }
+ if (!function_exists('apcu_store')) {
+ function apcu_store($key, mixed $value, ?int $ttl = 0): array|bool { return p\Apcu::apcu_store($key, $value, (int) $ttl); }
+ }
+} else {
+ if (!function_exists('apcu_add')) {
+ function apcu_add($key, mixed $value, ?int $ttl = 0): array|bool { return apc_add($key, $value, (int) $ttl); }
+ }
+ if (!function_exists('apcu_delete')) {
+ function apcu_delete($key): array|bool { return apc_delete($key); }
+ }
+ if (!function_exists('apcu_exists')) {
+ function apcu_exists($key): array|bool { return apc_exists($key); }
+ }
+ if (!function_exists('apcu_fetch')) {
+ function apcu_fetch($key, &$success = null) { return apc_fetch($key, $success); }
+ }
+ if (!function_exists('apcu_store')) {
+ function apcu_store($key, mixed $value, ?int $ttl = 0): array|bool { return apc_store($key, $value, (int) $ttl); }
+ }
+}
+
+if (!function_exists('apcu_cache_info')) {
+ function apcu_cache_info($limited = false) { return apc_cache_info('user', $limited); }
+}
+if (!function_exists('apcu_cas')) {
+ function apcu_cas($key, $old, $new) { return apc_cas($key, $old, $new); }
+}
+if (!function_exists('apcu_clear_cache')) {
+ function apcu_clear_cache() { return apc_clear_cache('user'); }
+}
+if (!function_exists('apcu_dec')) {
+ function apcu_dec($key, $step = 1, &$success = false) { return apc_dec($key, $step, $success); }
+}
+if (!function_exists('apcu_inc')) {
+ function apcu_inc($key, $step = 1, &$success = false) { return apc_inc($key, $step, $success); }
+}
+if (!function_exists('apcu_sma_info')) {
+ function apcu_sma_info($limited = false) { return apc_sma_info($limited); }
+}
+
+if (!class_exists('APCuIterator', false) && class_exists('APCIterator', false)) {
+ class APCuIterator extends APCIterator
+ {
+ public function __construct($search = null, $format = APC_ITER_ALL, $chunk_size = 100, $list = APC_LIST_ACTIVE)
+ {
+ parent::__construct('user', $search, $format, $chunk_size, $list);
+ }
+ }
+}
}
],
"require": {
- "php": ">=5.3.3"
+ "php": ">=7.1"
},
"autoload": {
"psr-4": { "Symfony\\Polyfill\\Apcu\\": "" },
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "1.7-dev"
+ "dev-main": "1.28-dev"
+ },
+ "thanks": {
+ "name": "symfony/polyfill",
+ "url": "https://github.com/symfony/polyfill"
}
}
}