diff --git a/composer.json b/composer.json index bbc1e0e0b..1ad7b9081 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,8 @@ "require-dev": { "http-interop/http-middleware": "^0.4.1", "phpunit/phpunit": "^8.0", - "zendframework/zend-coding-standard": "~1.0.0", + "webimpress/coding-standard": "dev-master", + "zendframework/zend-coding-standard": "2.0.0-alpha.3", "zendframework/zend-json": "^2.6.1 || ^3.0", "zendframework/zend-psr7bridge": "^1.0", "zendframework/zend-stratigility": ">=2.0.1 <2.2" diff --git a/composer.lock b/composer.lock index 45256b7e5..186aab1df 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "a3458c4868bd29adf56ecb626ee26f16", + "content-hash": "eff7d85e20f5a16fcf0324a9adfcd819", "packages": [ { "name": "container-interop/container-interop", @@ -840,6 +840,72 @@ } ], "packages-dev": [ + { + "name": "dealerdirect/phpcodesniffer-composer-installer", + "version": "v0.5.0", + "source": { + "type": "git", + "url": "https://github.com/Dealerdirect/phpcodesniffer-composer-installer.git", + "reference": "e749410375ff6fb7a040a68878c656c2e610b132" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Dealerdirect/phpcodesniffer-composer-installer/zipball/e749410375ff6fb7a040a68878c656c2e610b132", + "reference": "e749410375ff6fb7a040a68878c656c2e610b132", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.0", + "php": "^5.3|^7", + "squizlabs/php_codesniffer": "^2|^3" + }, + "require-dev": { + "composer/composer": "*", + "phpcompatibility/php-compatibility": "^9.0", + "sensiolabs/security-checker": "^4.1.0" + }, + "type": "composer-plugin", + "extra": { + "class": "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin" + }, + "autoload": { + "psr-4": { + "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Franck Nijhof", + "email": "franck.nijhof@dealerdirect.com", + "homepage": "http://www.frenck.nl", + "role": "Developer / IT Manager" + } + ], + "description": "PHP_CodeSniffer Standards Composer Installer Plugin", + "homepage": "http://www.dealerdirect.com", + "keywords": [ + "PHPCodeSniffer", + "PHP_CodeSniffer", + "code quality", + "codesniffer", + "composer", + "installer", + "phpcs", + "plugin", + "qa", + "quality", + "standard", + "standards", + "style guide", + "stylecheck", + "tests" + ], + "time": "2018-10-26T13:21:45+00:00" + }, { "name": "doctrine/instantiator", "version": "1.1.0", @@ -1646,6 +1712,58 @@ ], "time": "2019-02-01T05:41:59+00:00" }, + { + "name": "psr/http-factory", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "378bfe27931ecc54ff824a20d6f6bfc303bbd04c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/378bfe27931ecc54ff824a20d6f6bfc303bbd04c", + "reference": "378bfe27931ecc54ff824a20d6f6bfc303bbd04c", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "time": "2018-07-30T21:54:04+00:00" + }, { "name": "psr/http-message", "version": "1.0.1", @@ -2265,66 +2383,78 @@ "homepage": "https://github.com/sebastianbergmann/version", "time": "2016-10-03T07:35:21+00:00" }, + { + "name": "slevomat/coding-standard", + "version": "4.8.7", + "source": { + "type": "git", + "url": "https://github.com/slevomat/coding-standard.git", + "reference": "bff96313d8c7c2ba57a4edb13c1c141df8988c58" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slevomat/coding-standard/zipball/bff96313d8c7c2ba57a4edb13c1c141df8988c58", + "reference": "bff96313d8c7c2ba57a4edb13c1c141df8988c58", + "shasum": "" + }, + "require": { + "php": "^7.1", + "squizlabs/php_codesniffer": "^3.4.0" + }, + "require-dev": { + "jakub-onderka/php-parallel-lint": "1.0.0", + "phing/phing": "2.16.1", + "phpstan/phpstan": "0.9.2", + "phpstan/phpstan-phpunit": "0.9.4", + "phpstan/phpstan-strict-rules": "0.9", + "phpunit/phpunit": "7.5.1" + }, + "type": "phpcodesniffer-standard", + "autoload": { + "psr-4": { + "SlevomatCodingStandard\\": "SlevomatCodingStandard" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Slevomat Coding Standard for PHP_CodeSniffer complements Consistence Coding Standard by providing sniffs with additional checks.", + "time": "2019-01-03T13:15:50+00:00" + }, { "name": "squizlabs/php_codesniffer", - "version": "2.9.2", + "version": "3.4.0", "source": { "type": "git", "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", - "reference": "2acf168de78487db620ab4bc524135a13cfe6745" + "reference": "379deb987e26c7cd103a7b387aea178baec96e48" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/2acf168de78487db620ab4bc524135a13cfe6745", - "reference": "2acf168de78487db620ab4bc524135a13cfe6745", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/379deb987e26c7cd103a7b387aea178baec96e48", + "reference": "379deb987e26c7cd103a7b387aea178baec96e48", "shasum": "" }, "require": { "ext-simplexml": "*", "ext-tokenizer": "*", "ext-xmlwriter": "*", - "php": ">=5.1.2" + "php": ">=5.4.0" }, "require-dev": { - "phpunit/phpunit": "~4.0" + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" }, "bin": [ - "scripts/phpcs", - "scripts/phpcbf" + "bin/phpcs", + "bin/phpcbf" ], "type": "library", "extra": { "branch-alias": { - "dev-master": "2.x-dev" + "dev-master": "3.x-dev" } }, - "autoload": { - "classmap": [ - "CodeSniffer.php", - "CodeSniffer/CLI.php", - "CodeSniffer/Exception.php", - "CodeSniffer/File.php", - "CodeSniffer/Fixer.php", - "CodeSniffer/Report.php", - "CodeSniffer/Reporting.php", - "CodeSniffer/Sniff.php", - "CodeSniffer/Tokens.php", - "CodeSniffer/Reports/", - "CodeSniffer/Tokenizers/", - "CodeSniffer/DocGenerators/", - "CodeSniffer/Standards/AbstractPatternSniff.php", - "CodeSniffer/Standards/AbstractScopeSniff.php", - "CodeSniffer/Standards/AbstractVariableSniff.php", - "CodeSniffer/Standards/IncorrectPatternException.php", - "CodeSniffer/Standards/Generic/Sniffs/", - "CodeSniffer/Standards/MySource/Sniffs/", - "CodeSniffer/Standards/PEAR/Sniffs/", - "CodeSniffer/Standards/PSR1/Sniffs/", - "CodeSniffer/Standards/PSR2/Sniffs/", - "CodeSniffer/Standards/Squiz/Sniffs/", - "CodeSniffer/Standards/Zend/Sniffs/" - ] - }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" @@ -2341,7 +2471,7 @@ "phpcs", "standards" ], - "time": "2018-11-07T22:31:41+00:00" + "time": "2018-12-19T23:57:18+00:00" }, { "name": "symfony/polyfill-ctype", @@ -2441,6 +2571,47 @@ "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", "time": "2017-04-07T12:08:54+00:00" }, + { + "name": "webimpress/coding-standard", + "version": "dev-master", + "source": { + "type": "git", + "url": "https://github.com/webimpress/coding-standard.git", + "reference": "dffb65291b040f43f760c7ee23192f8ba01eb028" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webimpress/coding-standard/zipball/dffb65291b040f43f760c7ee23192f8ba01eb028", + "reference": "dffb65291b040f43f760c7ee23192f8ba01eb028", + "shasum": "" + }, + "require": { + "php": "^7.1", + "squizlabs/php_codesniffer": "^3.4" + }, + "require-dev": { + "phpunit/phpunit": "^7.5.1" + }, + "type": "phpcodesniffer-standard", + "autoload": { + "psr-4": { + "WebimpressCodingStandard\\": "src/WebimpressCodingStandard/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-2-Clause" + ], + "description": "Webimpress Coding Standard", + "keywords": [ + "Coding Standard", + "PSR-2", + "phpcs", + "psr-12", + "webimpress" + ], + "time": "2019-01-17T15:27:37+00:00" + }, { "name": "webimpress/composer-extra-dependency", "version": "0.2.2", @@ -2587,67 +2758,86 @@ }, { "name": "zendframework/zend-coding-standard", - "version": "1.0.0", + "version": "2.0.0-alpha.3", "source": { "type": "git", "url": "https://github.com/zendframework/zend-coding-standard.git", - "reference": "893316d2904e93f1c74c1384b6d7d57778299cb6" + "reference": "d7d46e080684a9da51940393c8f0c6ed67735ff5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-coding-standard/zipball/893316d2904e93f1c74c1384b6d7d57778299cb6", - "reference": "893316d2904e93f1c74c1384b6d7d57778299cb6", + "url": "https://api.github.com/repos/zendframework/zend-coding-standard/zipball/d7d46e080684a9da51940393c8f0c6ed67735ff5", + "reference": "d7d46e080684a9da51940393c8f0c6ed67735ff5", "shasum": "" }, "require": { - "squizlabs/php_codesniffer": "^2.7" + "dealerdirect/phpcodesniffer-composer-installer": "^0.5.0", + "php": "^7.1", + "slevomat/coding-standard": "^4.8.0", + "squizlabs/php_codesniffer": "^3.4.0", + "webimpress/coding-standard": "dev-master" + }, + "type": "phpcodesniffer-standard", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev", + "dev-develop": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "ZendCodingStandard\\": "src/ZendCodingStandard" + } }, - "type": "library", "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], - "description": "Zend Framework coding standard", + "description": "Zend Framework Coding Standard", "keywords": [ "Coding Standard", + "ZendFramework", "zf" ], - "time": "2016-11-09T21:30:43+00:00" + "time": "2019-01-01T19:08:39+00:00" }, { "name": "zendframework/zend-diactoros", - "version": "1.8.6", + "version": "2.1.1", "source": { "type": "git", "url": "https://github.com/zendframework/zend-diactoros.git", - "reference": "20da13beba0dde8fb648be3cc19765732790f46e" + "reference": "c3c330192bc9cc51b7e9ce968ff721dc32ffa986" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-diactoros/zipball/20da13beba0dde8fb648be3cc19765732790f46e", - "reference": "20da13beba0dde8fb648be3cc19765732790f46e", + "url": "https://api.github.com/repos/zendframework/zend-diactoros/zipball/c3c330192bc9cc51b7e9ce968ff721dc32ffa986", + "reference": "c3c330192bc9cc51b7e9ce968ff721dc32ffa986", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0", + "php": "^7.1", + "psr/http-factory": "^1.0", "psr/http-message": "^1.0" }, "provide": { + "psr/http-factory-implementation": "1.0", "psr/http-message-implementation": "1.0" }, "require-dev": { "ext-dom": "*", "ext-libxml": "*", + "http-interop/http-factory-tests": "^0.5.0", "php-http/psr7-integration-tests": "dev-master", - "phpunit/phpunit": "^5.7.16 || ^6.0.8 || ^7.2.7", - "zendframework/zend-coding-standard": "~1.0" + "phpunit/phpunit": "^7.0.2", + "zendframework/zend-coding-standard": "~1.0.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.8.x-dev", - "dev-develop": "1.9.x-dev", - "dev-release-2.0": "2.0.x-dev" + "dev-master": "2.1.x-dev", + "dev-develop": "2.2.x-dev", + "dev-release-1.8": "1.8.x-dev" } }, "autoload": { @@ -2667,16 +2857,15 @@ }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-2-Clause" + "BSD-3-Clause" ], "description": "PSR HTTP Message implementations", - "homepage": "https://github.com/zendframework/zend-diactoros", "keywords": [ "http", "psr", "psr-7" ], - "time": "2018-09-05T19:29:37+00:00" + "time": "2019-01-05T20:13:32+00:00" }, { "name": "zendframework/zend-psr7bridge", @@ -2789,7 +2978,10 @@ ], "aliases": [], "minimum-stability": "stable", - "stability-flags": [], + "stability-flags": { + "webimpress/coding-standard": 20, + "zendframework/zend-coding-standard": 15 + }, "prefer-stable": false, "prefer-lowest": false, "platform": { diff --git a/phpcs.xml b/phpcs.xml index 9e6a75116..f6c9f8f4e 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -1,8 +1,20 @@  - - + + + + + + + + + + - src - test + src/ + test/ + + + diff --git a/src/Application.php b/src/Application.php index cc66cbb22..71f00910b 100644 --- a/src/Application.php +++ b/src/Application.php @@ -1,10 +1,12 @@ serviceManager = $serviceManager; $this->setEventManager($events ?: $serviceManager->get('EventManager')); - $this->request = $request ?: $serviceManager->get('Request'); - $this->response = $response ?: $serviceManager->get('Response'); + $this->request = $request ?: $serviceManager->get('Request'); + $this->response = $response ?: $serviceManager->get('Response'); } /** @@ -174,7 +171,7 @@ public function getServiceManager() /** * Get the request object * - * @return \Zend\Stdlib\RequestInterface + * @return RequestInterface */ public function getRequest() { @@ -210,8 +207,8 @@ public function getMvcEvent() public function setEventManager(EventManagerInterface $eventManager) { $eventManager->setIdentifiers([ - __CLASS__, - get_class($this), + self::class, + static::class, ]); $this->events = $eventManager; return $this; @@ -251,7 +248,7 @@ public function getEventManager() public static function init($configuration = []) { // Prepare the service manager - $smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : []; + $smConfig = $configuration['service_manager'] ?? []; $smConfig = new Service\ServiceManagerConfig($smConfig); $serviceManager = new ServiceManager(); @@ -262,9 +259,9 @@ public static function init($configuration = []) $serviceManager->get('ModuleManager')->loadModules(); // Prepare list of listeners to bootstrap - $listenersFromAppConfig = isset($configuration['listeners']) ? $configuration['listeners'] : []; + $listenersFromAppConfig = $configuration['listeners'] ?? []; $config = $serviceManager->get('config'); - $listenersFromConfigService = isset($config['listeners']) ? $config['listeners'] : []; + $listenersFromConfigService = $config['listeners'] ?? []; $listeners = array_unique(array_merge($listenersFromConfigService, $listenersFromAppConfig)); diff --git a/src/ApplicationInterface.php b/src/ApplicationInterface.php index 6f8c4062f..d01004618 100644 --- a/src/ApplicationInterface.php +++ b/src/ApplicationInterface.php @@ -1,34 +1,39 @@ 'Placeholder page' + 'content' => 'Placeholder page', ]); } @@ -53,7 +57,7 @@ public function notFoundAction() * * @param MvcEvent $e * @return mixed - * @throws Exception\DomainException + * @throws DomainException */ public function onDispatch(MvcEvent $e) { @@ -63,7 +67,7 @@ public function onDispatch(MvcEvent $e) * @todo Determine requirements for when route match is missing. * Potentially allow pulling directly from request metadata? */ - throw new Exception\DomainException('Missing route matches; unsure how to retrieve action'); + throw new DomainException('Missing route matches; unsure how to retrieve action'); } $action = $routeMatch->getParam('action', 'not-found'); diff --git a/src/Controller/AbstractController.php b/src/Controller/AbstractController.php index da634c5c6..ddaf4d34e 100644 --- a/src/Controller/AbstractController.php +++ b/src/Controller/AbstractController.php @@ -1,10 +1,12 @@ request = $request; if (! $response) { @@ -100,7 +102,7 @@ public function dispatch(Request $request, Response $response = null) $e->setTarget($this); $result = $this->getEventManager()->triggerEventUntil(function ($test) { - return ($test instanceof Response); + return $test instanceof Response; }, $e); if ($result->stopped()) { @@ -146,14 +148,14 @@ public function getResponse() */ public function setEventManager(EventManagerInterface $events) { - $className = get_class($this); + $className = static::class; $nsPos = strpos($className, '\\') ?: 0; $events->setIdentifiers(array_merge( [ - __CLASS__, + self::class, $className, - substr($className, 0, $nsPos) + substr($className, 0, $nsPos), ], array_values(class_implements($className)), (array) $this->eventIdentifier @@ -193,7 +195,7 @@ public function setEvent(Event $e) { if (! $e instanceof MvcEvent) { $eventParams = $e->getParams(); - $e = new MvcEvent(); + $e = new MvcEvent(); $e->setParams($eventParams); unset($eventParams); } @@ -252,7 +254,7 @@ public function setPluginManager(PluginManager $plugins) * @param null|array $options Options to pass to plugin constructor (if not already instantiated) * @return mixed */ - public function plugin($name, array $options = null) + public function plugin($name, ?array $options = null) { return $this->getPluginManager()->get($name, $options); } @@ -296,12 +298,10 @@ protected function attachDefaultListeners() */ public static function getMethodFromAction($action) { - $method = str_replace(['.', '-', '_'], ' ', $action); - $method = ucwords($method); - $method = str_replace(' ', '', $method); - $method = lcfirst($method); - $method .= 'Action'; - - return $method; + $method = str_replace(['.', '-', '_'], ' ', $action); + $method = ucwords($method); + $method = str_replace(' ', '', $method); + $method = lcfirst($method); + return $method . 'Action'; } } diff --git a/src/Controller/AbstractRestfulController.php b/src/Controller/AbstractRestfulController.php index cff21f6db..0403ccd37 100644 --- a/src/Controller/AbstractRestfulController.php +++ b/src/Controller/AbstractRestfulController.php @@ -1,38 +1,62 @@ [ 'application/hal+json', - 'application/json' - ] + 'application/json', + ], ]; /** @@ -101,7 +125,7 @@ public function create($data) $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -116,7 +140,7 @@ public function delete($id) $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -133,7 +157,7 @@ public function deleteList($data) $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -148,7 +172,7 @@ public function get($id) $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -162,7 +186,7 @@ public function getList() $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -180,7 +204,7 @@ public function head($id = null) $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -200,7 +224,7 @@ public function options() $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -210,8 +234,8 @@ public function options() * Not marked as abstract, as that would introduce a BC break * (introduced in 2.1.0); instead, raises an exception if not implemented. * - * @param $id - * @param $data + * @param mixed $id + * @param mixed $data * @return array */ public function patch($id, $data) @@ -219,7 +243,7 @@ public function patch($id, $data) $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -237,7 +261,7 @@ public function replaceList($data) $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -255,7 +279,7 @@ public function patchList($data) $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -271,7 +295,7 @@ public function update($id, $data) $this->response->setStatusCode(405); return [ - 'content' => 'Method Not Allowed' + 'content' => 'Method Not Allowed', ]; } @@ -285,7 +309,7 @@ public function notFoundAction() $this->response->setStatusCode(404); return [ - 'content' => 'Page not found' + 'content' => 'Page not found', ]; } @@ -297,12 +321,12 @@ public function notFoundAction() * to determine how to handle the request, and which method to delegate to. * * @events dispatch.pre, dispatch.post - * @param Request $request + * @param Request $request * @param null|Response $response * @return mixed|Response * @throws Exception\InvalidArgumentException */ - public function dispatch(Request $request, Response $response = null) + public function dispatch(Request $request, ?Response $response = null) { if (! $request instanceof HttpRequest) { throw new Exception\InvalidArgumentException('Expected an HTTP request'); @@ -333,7 +357,7 @@ public function onDispatch(MvcEvent $e) $request = $e->getRequest(); // Was an "action" requested? - $action = $routeMatch->getParam('action', false); + $action = $routeMatch->getParam('action', false); if ($action) { // Handle arbitrary methods, ending in Action $method = static::getMethodFromAction($action); @@ -349,10 +373,10 @@ public function onDispatch(MvcEvent $e) $method = strtolower($request->getMethod()); switch ($method) { // Custom HTTP methods (or custom overrides for standard methods) - case (isset($this->customHttpMethodsMap[$method])): + case isset($this->customHttpMethodsMap[$method]): $callable = $this->customHttpMethodsMap[$method]; - $action = $method; - $return = call_user_func($callable, $e); + $action = $method; + $return = call_user_func($callable, $e); break; // DELETE case 'delete': @@ -386,9 +410,9 @@ public function onDispatch(MvcEvent $e) if ($id === false) { $id = null; } - $action = 'head'; + $action = 'head'; $headResult = $this->head($id); - $response = ($headResult instanceof Response) ? clone $headResult : $e->getResponse(); + $response = $headResult instanceof Response ? clone $headResult : $e->getResponse(); $response->setContent(''); $return = $response; break; @@ -400,7 +424,7 @@ public function onDispatch(MvcEvent $e) break; // PATCH case 'patch': - $id = $this->getIdentifier($routeMatch, $request); + $id = $this->getIdentifier($routeMatch, $request); $data = $this->processBodyContent($request); if ($id !== false) { @@ -472,13 +496,13 @@ public function processPostData(Request $request) /** * Check if request has certain content type * - * @param Request $request + * @param Request $request * @param string|null $contentType * @return bool */ public function requestHasContentType(Request $request, $contentType = '') { - /** @var $headerContentType \Zend\Http\Header\ContentType */ + /** @var ContentType $headerContentType */ $headerContentType = $request->getHeaders()->get('content-type'); if (! $headerContentType) { return false; @@ -486,7 +510,7 @@ public function requestHasContentType(Request $request, $contentType = '') $requestedContentType = $headerContentType->getFieldValue(); if (false !== strpos($requestedContentType, ';')) { - $headerData = explode(';', $requestedContentType); + $headerData = explode(';', $requestedContentType); $requestedContentType = array_shift($headerData); } $requestedContentType = trim($requestedContentType); @@ -523,19 +547,19 @@ public function requestHasContentType(Request $request, $contentType = '') * To retrieve the body content data, use "$data = $this->processBodyContent($request)"; * that method will return a string, array, or, in the case of JSON, an object. * - * @param string $method + * @param string $method * @param Callable $handler * @return AbstractRestfulController */ - public function addHttpMethodHandler($method, /* Callable */ $handler) + public function addHttpMethodHandler($method, $handler) { if (! is_callable($handler)) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid HTTP method handler: must be a callable; received "%s"', - (is_object($handler) ? get_class($handler) : gettype($handler)) + is_object($handler) ? get_class($handler) : gettype($handler) )); } - $method = strtolower($method); + $method = strtolower($method); $this->customHttpMethodsMap[$method] = $handler; return $this; } @@ -546,14 +570,14 @@ public function addHttpMethodHandler($method, /* Callable */ $handler) * Attempts to see if an identifier was passed in either the URI or the * query string, returning it if found. Otherwise, returns a boolean false. * - * @param \Zend\Router\RouteMatch $routeMatch - * @param Request $request + * @param RouteMatch $routeMatch + * @param Request $request * @return false|mixed */ protected function getIdentifier($routeMatch, $request) { $identifier = $this->getIdentifierName(); - $id = $routeMatch->getParam($identifier, false); + $id = $routeMatch->getParam($identifier, false); if ($id !== false) { return $id; } @@ -593,7 +617,7 @@ protected function processBodyContent($request) // If parse_str fails to decode, or we have a single element with empty value if (! is_array($parsedParams) || empty($parsedParams) - || (1 == count($parsedParams) && '' === reset($parsedParams)) + || (1 === count($parsedParams) && '' === reset($parsedParams)) ) { return $content; } @@ -611,7 +635,7 @@ protected function processBodyContent($request) * * Marked protected to allow usage from extending classes. * - * @param string + * @param string $string * @return mixed * @throws Exception\DomainException if no JSON decoding functionality is * available. diff --git a/src/Controller/ControllerManager.php b/src/Controller/ControllerManager.php index 20e721655..ecae6e5a5 100644 --- a/src/Controller/ControllerManager.php +++ b/src/Controller/ControllerManager.php @@ -1,10 +1,12 @@ instanceOf) { throw new InvalidServiceException(sprintf( 'Plugin of type "%s" is invalid; must implement %s', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), + is_object($plugin) ? get_class($plugin) : gettype($plugin), $this->instanceOf )); } @@ -78,7 +86,7 @@ public function validate($plugin) * the shared EM injection needs to happen; the conditional will always * pass. * - * @param ContainerInterface $container + * @param ContainerInterface $container * @param DispatchableInterface $controller */ public function injectEventManager(ContainerInterface $container, $controller) @@ -96,7 +104,7 @@ public function injectEventManager(ContainerInterface $container, $controller) /** * Initializer: inject plugin manager * - * @param ContainerInterface $container + * @param ContainerInterface $container * @param DispatchableInterface $controller */ public function injectPluginManager(ContainerInterface $container, $controller) diff --git a/src/Controller/LazyControllerAbstractFactory.php b/src/Controller/LazyControllerAbstractFactory.php index 0cd0f23d8..c936c5f95 100644 --- a/src/Controller/LazyControllerAbstractFactory.php +++ b/src/Controller/LazyControllerAbstractFactory.php @@ -1,10 +1,12 @@ getClass()) { - return; + return null; } $type = $parameter->getClass()->getName(); - $type = isset($this->aliases[$type]) ? $this->aliases[$type] : $type; + $type = $this->aliases[$type] ?? $type; if (! $container->has($type)) { throw new ServiceNotFoundException(sprintf( diff --git a/src/Controller/MiddlewareController.php b/src/Controller/MiddlewareController.php index aee5e269d..230dc77d9 100644 --- a/src/Controller/MiddlewareController.php +++ b/src/Controller/MiddlewareController.php @@ -1,14 +1,17 @@ eventIdentifier = __CLASS__; + $this->eventIdentifier = self::class; $this->pipe = $pipe; $this->responsePrototype = $responsePrototype; @@ -83,7 +85,7 @@ function () { } /** - * @return \Zend\Diactoros\ServerRequest + * @return ServerRequest * * @throws RuntimeException */ @@ -104,11 +106,11 @@ private function loadRequest() /** * @param ServerRequestInterface $request - * @param RouteMatch|null $routeMatch + * @param RouteMatch|null $routeMatch * * @return ServerRequestInterface */ - private function populateRequestParametersFromRoute(ServerRequestInterface $request, RouteMatch $routeMatch = null) + private function populateRequestParametersFromRoute(ServerRequestInterface $request, ?RouteMatch $routeMatch = null) { if (! $routeMatch) { return $request; diff --git a/src/Controller/Plugin/AbstractPlugin.php b/src/Controller/Plugin/AbstractPlugin.php index c00a570cf..cd9b4b2ff 100644 --- a/src/Controller/Plugin/AbstractPlugin.php +++ b/src/Controller/Plugin/AbstractPlugin.php @@ -1,19 +1,19 @@ getViewModel($matchAgainst, $returnDefault, $resultReference); } @@ -72,21 +72,21 @@ public function __invoke( /** * Detects an appropriate viewmodel for request. * - * @param array $matchAgainst (optional) The Array to match against - * @param bool $returnDefault (optional) If no match is available. Return default instead + * @param array $matchAgainst (optional) The Array to match against + * @param bool $returnDefault (optional) If no match is available. Return default instead * @param AbstractFieldValuePart|null $resultReference (optional) The object that was matched * @throws InvalidArgumentException If the supplied and matched View Model could not be found * @return ModelInterface|null */ public function getViewModel( - array $matchAgainst = null, + ?array $matchAgainst = null, $returnDefault = true, - & $resultReference = null + &$resultReference = null ) { $name = $this->getViewModelName($matchAgainst, $returnDefault, $resultReference); if (! $name) { - return; + return null; } if (! class_exists($name)) { @@ -99,15 +99,15 @@ public function getViewModel( /** * Detects an appropriate viewmodel name for request. * - * @param array $matchAgainst (optional) The Array to match against - * @param bool $returnDefault (optional) If no match is available. Return default instead + * @param array $matchAgainst (optional) The Array to match against + * @param bool $returnDefault (optional) If no match is available. Return default instead * @param AbstractFieldValuePart|null $resultReference (optional) The object that was matched. - * @return ModelInterface|null Returns null if $returnDefault = false and no match could be made + * @return string|null Returns null if $returnDefault = false and no match could be made */ public function getViewModelName( - array $matchAgainst = null, + ?array $matchAgainst = null, $returnDefault = true, - & $resultReference = null + &$resultReference = null ) { $res = $this->match($matchAgainst); if ($res) { @@ -118,6 +118,7 @@ public function getViewModelName( if ($returnDefault) { return $this->defaultViewModelName; } + return null; } /** @@ -126,13 +127,13 @@ public function getViewModelName( * @param array $matchAgainst (optional) The Array to match against * @return AbstractFieldValuePart|null The object that was matched */ - public function match(array $matchAgainst = null) + public function match(?array $matchAgainst = null) { - $request = $this->getRequest(); - $headers = $request->getHeaders(); + $request = $this->getRequest(); + $headers = $request->getHeaders(); if ((! $matchAgainst && ! $this->defaultMatchAgainst) || ! $headers->has('accept')) { - return; + return null; } if (! $matchAgainst) { @@ -146,10 +147,10 @@ public function match(array $matchAgainst = null) } } - /** @var $accept \Zend\Http\Header\Accept */ + /** @var Accept $accept */ $accept = $headers->get('Accept'); if (($res = $accept->match($matchAgainstString)) === false) { - return; + return null; } return $res; @@ -181,7 +182,7 @@ public function getDefaultViewModelName() * @param array $matchAgainst (optional) The Array to match against * @return AcceptableViewModelSelector provides fluent interface */ - public function setDefaultMatchAgainst(array $matchAgainst = null) + public function setDefaultMatchAgainst(?array $matchAgainst = null) { $this->defaultMatchAgainst = $matchAgainst; return $this; @@ -206,8 +207,8 @@ public function getDefaultMatchAgainst() */ protected function injectViewModelName($modelAcceptString, $modelName) { - $modelName = str_replace('\\', '|', $modelName); - $modelAcceptString = (is_array($modelAcceptString)) + $modelName = str_replace('\\', '|', $modelName); + $modelAcceptString = is_array($modelAcceptString) ? $modelAcceptString[key($modelAcceptString)] : $modelAcceptString; return $modelAcceptString . '; ' . self::INJECT_VIEWMODEL_NAME . '="' . $modelName . '", '; @@ -236,7 +237,7 @@ protected function getRequest() return $this->request; } - $event = $this->getEvent(); + $event = $this->getEvent(); $request = $event->getRequest(); if (! $request instanceof Request) { throw new DomainException( @@ -264,14 +265,14 @@ protected function getEvent() if (! $controller instanceof InjectApplicationEventInterface) { throw new DomainException( 'A controller that implements InjectApplicationEventInterface ' - . 'is required to use ' . __CLASS__ + . 'is required to use ' . self::class ); } $event = $controller->getEvent(); if (! $event instanceof MvcEvent) { $params = $event->getParams(); - $event = new MvcEvent(); + $event = new MvcEvent(); $event->setParams($params); } $this->event = $event; diff --git a/src/Controller/Plugin/CreateHttpNotFoundModel.php b/src/Controller/Plugin/CreateHttpNotFoundModel.php index dd35143e2..0570b7a0d 100644 --- a/src/Controller/Plugin/CreateHttpNotFoundModel.php +++ b/src/Controller/Plugin/CreateHttpNotFoundModel.php @@ -1,10 +1,12 @@ listenersToDetach = [[ - 'id' => 'Zend\Stdlib\DispatchableInterface', - 'event' => MvcEvent::EVENT_DISPATCH, - 'class' => 'Zend\Mvc\View\Http\InjectViewModelListener', - ]]; + $this->listenersToDetach = [ + [ + 'id' => DispatchableInterface::class, + 'event' => MvcEvent::EVENT_DISPATCH, + 'class' => InjectViewModelListener::class, + ], + ]; } return $this->listenersToDetach; } @@ -107,15 +110,15 @@ public function setListenersToDetach($listeners) /** * Dispatch another controller * - * @param string $name Controller name; either a class name or an alias used in the controller manager + * @param string $name Controller name; either a class name or an alias used in the controller manager * @param null|array $params Parameters with which to seed a custom RouteMatch object for the new controller * @return mixed * @throws Exception\DomainException if composed controller does not define InjectApplicationEventInterface * or Locator aware; or if the discovered controller is not dispatchable */ - public function dispatch($name, array $params = null) + public function dispatch($name, ?array $params = null) { - $event = clone($this->getEvent()); + $event = clone $this->getEvent(); $controller = $this->controllers->get($name); if ($controller instanceof InjectApplicationEventInterface) { @@ -130,15 +133,16 @@ public function dispatch($name, array $params = null) } if ($this->numNestedForwards > $this->maxNestedForwards) { - throw new Exception\DomainException( - "Circular forwarding detected: greater than $this->maxNestedForwards nested forwards" - ); + throw new Exception\DomainException(sprintf( + 'Circular forwarding detected: greater than %s nested forwards', + $this->maxNestedForwards + )); } $this->numNestedForwards++; // Detach listeners that may cause problems during dispatch: $sharedEvents = $event->getApplication()->getEventManager()->getSharedManager(); - $listeners = $this->detachProblemListeners($sharedEvents); + $listeners = $this->detachProblemListeners($sharedEvents); $return = $controller->dispatch($event->getRequest(), $event->getResponse()); @@ -178,7 +182,7 @@ protected function detachProblemListeners(SharedEvents $sharedEvents) $results[$id] = []; foreach ($eventArray as $eventName => $classArray) { $results[$id][$eventName] = []; - $events = $this->getSharedListenersById($id, $eventName, $sharedEvents); + $events = $this->getSharedListenersById($id, $eventName, $sharedEvents); foreach ($events as $priority => $currentPriorityEvents) { foreach ($currentPriorityEvents as $currentEvent) { $currentCallback = $currentEvent; @@ -243,7 +247,7 @@ protected function getEvent() if (! $controller instanceof InjectApplicationEventInterface) { throw new Exception\DomainException(sprintf( 'Forward plugin requires a controller that implements InjectApplicationEventInterface; received %s', - (is_object($controller) ? get_class($controller) : var_export($controller, 1)) + is_object($controller) ? get_class($controller) : var_export($controller, true) )); } @@ -253,7 +257,7 @@ protected function getEvent() if ($event) { $params = $event->getParams(); } - $event = new MvcEvent(); + $event = new MvcEvent(); $event->setParams($params); } $this->event = $event; @@ -266,10 +270,10 @@ protected function getEvent() * * Varies retrieval based on zend-eventmanager version. * - * @param string|int $id - * @param string $event + * @param string|int $id + * @param string $event * @param SharedEvents $sharedEvents - * @return array|\Traversable + * @return array|Traversable */ private function getSharedListenersById($id, $event, SharedEvents $sharedEvents) { @@ -281,8 +285,8 @@ private function getSharedListenersById($id, $event, SharedEvents $sharedEvents) * * Varies detachment based on zend-eventmanager version. * - * @param string|int $id - * @param callable|CallbackHandler $listener + * @param string|int $id + * @param callable $listener * @param SharedEvents $sharedEvents * @return void */ diff --git a/src/Controller/Plugin/Layout.php b/src/Controller/Plugin/Layout.php index 89e41588e..9df474356 100644 --- a/src/Controller/Plugin/Layout.php +++ b/src/Controller/Plugin/Layout.php @@ -1,10 +1,12 @@ has('ControllerManager')) { throw new ServiceNotCreatedException(sprintf( '%s requires that the application service manager contains a "%s" service; none found', - __CLASS__, + self::class, 'ControllerManager' )); } diff --git a/src/Controller/Plugin/Url.php b/src/Controller/Plugin/Url.php index 7a050a175..b8b6dd640 100644 --- a/src/Controller/Plugin/Url.php +++ b/src/Controller/Plugin/Url.php @@ -1,48 +1,58 @@ getController(); if (! $controller instanceof InjectApplicationEventInterface) { - throw new Exception\DomainException( + throw new DomainException( 'Url plugin requires a controller that implements InjectApplicationEventInterface' ); } if (! is_array($params)) { if (! $params instanceof Traversable) { - throw new Exception\InvalidArgumentException( + throw new InvalidArgumentException( 'Params is expected to be an array or a Traversable object' ); } @@ -60,25 +70,25 @@ public function fromRoute($route = null, $params = [], $options = [], $reuseMatc $matches = $event->getParam('route-match', false); } if (! $router instanceof RouteStackInterface) { - throw new Exception\DomainException( + throw new DomainException( 'Url plugin requires that controller event compose a router; none found' ); } - if (3 == func_num_args() && is_bool($options)) { + if (3 === func_num_args() && is_bool($options)) { $reuseMatchedParams = $options; - $options = []; + $options = []; } if ($route === null) { if (! $matches) { - throw new Exception\RuntimeException('No RouteMatch instance present'); + throw new RuntimeException('No RouteMatch instance present'); } $route = $matches->getMatchedRouteName(); if ($route === null) { - throw new Exception\RuntimeException('RouteMatch does not contain a matched route name'); + throw new RuntimeException('RouteMatch does not contain a matched route name'); } } diff --git a/src/Controller/PluginManager.php b/src/Controller/PluginManager.php index 5a9295903..3ad68317d 100644 --- a/src/Controller/PluginManager.php +++ b/src/Controller/PluginManager.php @@ -1,10 +1,12 @@ Plugin\AcceptableViewModelSelector::class, 'acceptableViewModelSelector' => Plugin\AcceptableViewModelSelector::class, @@ -49,9 +55,7 @@ class PluginManager extends AbstractPluginManager 'createhttpnotfoundmodel' => Plugin\CreateHttpNotFoundModel::class, ]; - /** - * @var string[]|callable[] Default factories - */ + /** @var string[]|callable[] Default factories */ protected $factories = [ Plugin\Forward::class => Plugin\Service\ForwardFactory::class, Plugin\AcceptableViewModelSelector::class => InvokableFactory::class, @@ -60,9 +64,7 @@ class PluginManager extends AbstractPluginManager Plugin\Redirect::class => InvokableFactory::class, Plugin\Url::class => InvokableFactory::class, Plugin\CreateHttpNotFoundModel::class => InvokableFactory::class, - // v2 normalized names - 'zendmvccontrollerpluginforward' => Plugin\Service\ForwardFactory::class, 'zendmvccontrollerpluginacceptableviewmodelselector' => InvokableFactory::class, 'zendmvccontrollerpluginlayout' => InvokableFactory::class, @@ -72,9 +74,7 @@ class PluginManager extends AbstractPluginManager 'zendmvccontrollerplugincreatehttpnotfoundmodel' => InvokableFactory::class, ]; - /** - * @var DispatchableInterface - */ + /** @var DispatchableInterface */ protected $controller; /** @@ -90,7 +90,7 @@ class PluginManager extends AbstractPluginManager * @param string $name * @return DispatchableInterface */ - public function get($name, array $options = null) + public function get($name, ?array $options = null) { $plugin = parent::get($name, $options); $this->injectController($plugin); @@ -154,7 +154,7 @@ public function validate($plugin) if (! $plugin instanceof $this->instanceOf) { throw new InvalidServiceException(sprintf( 'Plugin of type "%s" is invalid; must implement %s', - (is_object($plugin) ? get_class($plugin) : gettype($plugin)), + is_object($plugin) ? get_class($plugin) : gettype($plugin), $this->instanceOf )); } diff --git a/src/DispatchListener.php b/src/DispatchListener.php index ed7c7fe68..320a7d89b 100644 --- a/src/DispatchListener.php +++ b/src/DispatchListener.php @@ -1,19 +1,26 @@ getEventManager(); $controllerManager = $this->controllerManager; - // Query abstract controllers, too! if (! $controllerManager->has($controllerName)) { $return = $this->marshalControllerNotFoundEvent( @@ -118,10 +122,7 @@ public function onDispatch(MvcEvent $e) $exception ); return $this->complete($return, $e); - } catch (\Throwable $exception) { - $return = $this->marshalBadControllerEvent($controllerName, $e, $application, $exception); - return $this->complete($return, $e); - } catch (\Exception $exception) { // @TODO clean up once PHP 7 requirement is enforced + } catch (Throwable $exception) { $return = $this->marshalBadControllerEvent($controllerName, $e, $application, $exception); return $this->complete($return, $e); } @@ -130,15 +131,13 @@ public function onDispatch(MvcEvent $e) $controller->setEvent($e); } - $request = $e->getRequest(); - $response = $application->getResponse(); + $request = $e->getRequest(); + $response = $application->getResponse(); $caughtException = null; try { $return = $controller->dispatch($request, $response); - } catch (\Throwable $ex) { - $caughtException = $ex; - } catch (\Exception $ex) { // @TODO clean up once PHP 7 requirement is enforced + } catch (Throwable $ex) { $caughtException = $ex; } @@ -165,8 +164,7 @@ public function reportMonitorEvent(MvcEvent $e) { $error = $e->getError(); $exception = $e->getParam('exception'); - // @TODO clean up once PHP 7 requirement is enforced - if ($exception instanceof \Exception || $exception instanceof \Throwable) { + if ($exception instanceof Throwable) { zend_monitor_custom_event_ex( $error, $exception->getMessage(), @@ -179,7 +177,7 @@ public function reportMonitorEvent(MvcEvent $e) /** * Complete the dispatch * - * @param mixed $return + * @param mixed $return * @param MvcEvent $event * @return mixed */ @@ -197,11 +195,11 @@ protected function complete($return, MvcEvent $event) /** * Marshal a controller not found exception event * - * @param string $type - * @param string $controllerName - * @param MvcEvent $event + * @param string $type + * @param string $controllerName + * @param MvcEvent $event * @param Application $application - * @param \Throwable|\Exception $exception + * @param Throwable $exception * @return mixed */ protected function marshalControllerNotFoundEvent( @@ -231,10 +229,10 @@ protected function marshalControllerNotFoundEvent( /** * Marshal a bad controller exception event * - * @param string $controllerName - * @param MvcEvent $event + * @param string $controllerName + * @param MvcEvent $event * @param Application $application - * @param \Throwable|\Exception $exception + * @param Throwable $exception * @return mixed */ protected function marshalBadControllerEvent( diff --git a/src/Exception/BadMethodCallException.php b/src/Exception/BadMethodCallException.php index 50c951c8c..b9917cfdd 100644 --- a/src/Exception/BadMethodCallException.php +++ b/src/Exception/BadMethodCallException.php @@ -1,12 +1,16 @@ middlewareName = $middlewareName; return $instance; } public static function fromNull() { - $instance = new self('Middleware name cannot be null'); - return $instance; + return new self('Middleware name cannot be null'); } /** diff --git a/src/Exception/InvalidPluginException.php b/src/Exception/InvalidPluginException.php index bb3f3cd00..0ed356647 100644 --- a/src/Exception/InvalidPluginException.php +++ b/src/Exception/InvalidPluginException.php @@ -1,12 +1,16 @@ getRequest(); + $request = $e->getRequest(); $response = $e->getResponse(); if (! $request instanceof HttpRequest || ! $response instanceof HttpResponse) { diff --git a/src/InjectApplicationEventInterface.php b/src/InjectApplicationEventInterface.php index 18ae5af1c..07303672a 100644 --- a/src/InjectApplicationEventInterface.php +++ b/src/InjectApplicationEventInterface.php @@ -1,10 +1,12 @@ getServiceManager()->get('EventManager'), $event ))->dispatch($request, $response); - } catch (\Throwable $ex) { - $caughtException = $ex; - } catch (\Exception $ex) { // @TODO clean up once PHP 7 requirement is enforced + } catch (Throwable $ex) { $caughtException = $ex; } @@ -120,8 +122,8 @@ public function onDispatch(MvcEvent $event) * Create a middleware pipe from the array spec given. * * @param ContainerInterface $serviceLocator - * @param ResponseInterface $responsePrototype - * @param array $middlewaresToBePiped + * @param ResponseInterface $responsePrototype + * @param array $middlewaresToBePiped * @return MiddlewarePipe * @throws InvalidMiddlewareException */ @@ -154,11 +156,11 @@ private function createPipeFromSpec( /** * Marshal a middleware not callable exception event * - * @param string $type - * @param string $middlewareName - * @param MvcEvent $event + * @param string $type + * @param string $middlewareName + * @param MvcEvent $event * @param Application $application - * @param \Exception $exception + * @param Throwable $exception * @return mixed */ protected function marshalInvalidMiddleware( @@ -166,7 +168,7 @@ protected function marshalInvalidMiddleware( $middlewareName, MvcEvent $event, Application $application, - \Exception $exception = null + ?Throwable $exception = null ) { $event->setName(MvcEvent::EVENT_DISPATCH_ERROR); $event->setError($type); diff --git a/src/ModuleRouteListener.php b/src/ModuleRouteListener.php index 02fc72be9..0d0264a8b 100644 --- a/src/ModuleRouteListener.php +++ b/src/ModuleRouteListener.php @@ -1,26 +1,32 @@ sendHeaders($event) - ->sendContent($event); + ->sendContent($event); $event->stopPropagation(true); return $this; } diff --git a/src/ResponseSender/PhpEnvironmentResponseSender.php b/src/ResponseSender/PhpEnvironmentResponseSender.php index 5309e11f0..9c0256631 100644 --- a/src/ResponseSender/PhpEnvironmentResponseSender.php +++ b/src/ResponseSender/PhpEnvironmentResponseSender.php @@ -1,10 +1,12 @@ sendHeaders($event) - ->sendContent($event); + ->sendContent($event); $event->stopPropagation(true); return $this; } diff --git a/src/ResponseSender/ResponseSenderInterface.php b/src/ResponseSender/ResponseSenderInterface.php index 8322ae631..fe4c6b238 100644 --- a/src/ResponseSender/ResponseSenderInterface.php +++ b/src/ResponseSender/ResponseSenderInterface.php @@ -1,10 +1,12 @@ getResponse(); - $contentSent = $this->getParam('contentSent', []); + $response = $this->getResponse(); + $contentSent = $this->getParam('contentSent', []); $contentSent[spl_object_hash($response)] = true; $this->setParam('contentSent', $contentSent); $this->contentSent[spl_object_hash($response)] = true; @@ -91,8 +87,8 @@ public function contentSent() */ public function setHeadersSent() { - $response = $this->getResponse(); - $headersSent = $this->getParam('headersSent', []); + $response = $this->getResponse(); + $headersSent = $this->getParam('headersSent', []); $headersSent[spl_object_hash($response)] = true; $this->setParam('headersSent', $headersSent); $this->headersSent[spl_object_hash($response)] = true; diff --git a/src/ResponseSender/SimpleStreamResponseSender.php b/src/ResponseSender/SimpleStreamResponseSender.php index 3d1be8f75..a3c63181b 100644 --- a/src/ResponseSender/SimpleStreamResponseSender.php +++ b/src/ResponseSender/SimpleStreamResponseSender.php @@ -1,14 +1,18 @@ getStream(); fpassthru($stream); $event->setContentSent(); + return $this; } /** diff --git a/src/RouteListener.php b/src/RouteListener.php index 4fd1fc37f..03f89725e 100644 --- a/src/RouteListener.php +++ b/src/RouteListener.php @@ -1,10 +1,12 @@ setIdentifiers([ - __CLASS__, - get_class($this), + self::class, + static::class, ]); $this->eventManager = $eventManager; $this->attachDefaultListeners(); @@ -66,7 +64,7 @@ public function getEventManager() * Attach the aggregate to the specified event manager * * @param EventManagerInterface $events - * @param int $priority + * @param int $priority * @return void */ public function attach(EventManagerInterface $events, $priority = 1) @@ -109,7 +107,7 @@ public function getEvent() * Set the send response event * * @param SendResponseEvent $e - * @return SendResponseEvent + * @return SendResponseListener */ public function setEvent(SendResponseEvent $e) { diff --git a/src/Service/AbstractPluginManagerFactory.php b/src/Service/AbstractPluginManagerFactory.php index 0224eb99e..837ec287d 100644 --- a/src/Service/AbstractPluginManagerFactory.php +++ b/src/Service/AbstractPluginManagerFactory.php @@ -1,10 +1,12 @@ get('ModuleManager'); $moduleManager->loadModules(); diff --git a/src/Service/ControllerManagerFactory.php b/src/Service/ControllerManagerFactory.php index a1dd50812..f500ec336 100644 --- a/src/Service/ControllerManagerFactory.php +++ b/src/Service/ControllerManagerFactory.php @@ -1,10 +1,12 @@ get('ControllerManager')); } diff --git a/src/Service/EventManagerFactory.php b/src/Service/EventManagerFactory.php index 98bc186a6..3f33164ff 100644 --- a/src/Service/EventManagerFactory.php +++ b/src/Service/EventManagerFactory.php @@ -1,10 +1,12 @@ has('SharedEventManager') ? $container->get('SharedEventManager') : null; diff --git a/src/Service/HttpDefaultRenderingStrategyFactory.php b/src/Service/HttpDefaultRenderingStrategyFactory.php index 21a47daae..63692b0da 100644 --- a/src/Service/HttpDefaultRenderingStrategyFactory.php +++ b/src/Service/HttpDefaultRenderingStrategyFactory.php @@ -1,10 +1,12 @@ get(View::class)); $config = $this->getConfig($container); @@ -38,11 +40,11 @@ public function __invoke(ContainerInterface $container, $name, array $options = * Uses layout template from configuration; if none available, defaults to "layout/layout". * * @param DefaultRenderingStrategy $strategy - * @param array $config + * @param array $config */ private function injectLayoutTemplate(DefaultRenderingStrategy $strategy, array $config) { - $layout = isset($config['layout']) ? $config['layout'] : 'layout/layout'; + $layout = $config['layout'] ?? 'layout/layout'; $strategy->setLayoutTemplate($layout); } } diff --git a/src/Service/HttpExceptionStrategyFactory.php b/src/Service/HttpExceptionStrategyFactory.php index 6798f5a0a..d7eefaa8e 100644 --- a/src/Service/HttpExceptionStrategyFactory.php +++ b/src/Service/HttpExceptionStrategyFactory.php @@ -1,10 +1,12 @@ getConfig($container); @@ -36,11 +38,11 @@ public function __invoke(ContainerInterface $container, $name, array $options = * Inject strategy with configured display_exceptions flag. * * @param ExceptionStrategy $strategy - * @param array $config + * @param array $config */ private function injectDisplayExceptions(ExceptionStrategy $strategy, array $config) { - $flag = isset($config['display_exceptions']) ? $config['display_exceptions'] : false; + $flag = $config['display_exceptions'] ?? false; $strategy->setDisplayExceptions($flag); } @@ -48,11 +50,11 @@ private function injectDisplayExceptions(ExceptionStrategy $strategy, array $con * Inject strategy with configured exception_template * * @param ExceptionStrategy $strategy - * @param array $config + * @param array $config */ private function injectExceptionTemplate(ExceptionStrategy $strategy, array $config) { - $template = isset($config['exception_template']) ? $config['exception_template'] : 'error'; + $template = $config['exception_template'] ?? 'error'; $strategy->setExceptionTemplate($template); } } diff --git a/src/Service/HttpMethodListenerFactory.php b/src/Service/HttpMethodListenerFactory.php index 7562ac9b8..3b51cd23f 100644 --- a/src/Service/HttpMethodListenerFactory.php +++ b/src/Service/HttpMethodListenerFactory.php @@ -1,23 +1,28 @@ get('config'); @@ -25,11 +30,11 @@ public function __invoke(ContainerInterface $container, $name, array $options = return new HttpMethodListener(); } - $listenerConfig = $config['http_methods_listener']; - $enabled = array_key_exists('enabled', $listenerConfig) + $listenerConfig = $config['http_methods_listener']; + $enabled = array_key_exists('enabled', $listenerConfig) ? $listenerConfig['enabled'] : true; - $allowedMethods = (isset($listenerConfig['allowed_methods']) && is_array($listenerConfig['allowed_methods'])) + $allowedMethods = isset($listenerConfig['allowed_methods']) && is_array($listenerConfig['allowed_methods']) ? $listenerConfig['allowed_methods'] : null; diff --git a/src/Service/HttpRouteNotFoundStrategyFactory.php b/src/Service/HttpRouteNotFoundStrategyFactory.php index a426d1aea..9e9686805 100644 --- a/src/Service/HttpRouteNotFoundStrategyFactory.php +++ b/src/Service/HttpRouteNotFoundStrategyFactory.php @@ -1,10 +1,12 @@ getConfig($container); @@ -37,11 +39,11 @@ public function __invoke(ContainerInterface $container, $name, array $options = * Inject strategy with configured display_exceptions flag. * * @param RouteNotFoundStrategy $strategy - * @param array $config + * @param array $config */ private function injectDisplayExceptions(RouteNotFoundStrategy $strategy, array $config) { - $flag = isset($config['display_exceptions']) ? $config['display_exceptions'] : false; + $flag = $config['display_exceptions'] ?? false; $strategy->setDisplayExceptions($flag); } @@ -49,11 +51,11 @@ private function injectDisplayExceptions(RouteNotFoundStrategy $strategy, array * Inject strategy with configured display_not_found_reason flag. * * @param RouteNotFoundStrategy $strategy - * @param array $config + * @param array $config */ private function injectDisplayNotFoundReason(RouteNotFoundStrategy $strategy, array $config) { - $flag = isset($config['display_not_found_reason']) ? $config['display_not_found_reason'] : false; + $flag = $config['display_not_found_reason'] ?? false; $strategy->setDisplayNotFoundReason($flag); } @@ -61,11 +63,11 @@ private function injectDisplayNotFoundReason(RouteNotFoundStrategy $strategy, ar * Inject strategy with configured not_found_template. * * @param RouteNotFoundStrategy $strategy - * @param array $config + * @param array $config */ private function injectNotFoundTemplate(RouteNotFoundStrategy $strategy, array $config) { - $template = isset($config['not_found_template']) ? $config['not_found_template'] : '404'; + $template = $config['not_found_template'] ?? '404'; $strategy->setNotFoundTemplate($template); } } diff --git a/src/Service/HttpViewManagerConfigTrait.php b/src/Service/HttpViewManagerConfigTrait.php index 6c6efa62d..70819ff7a 100644 --- a/src/Service/HttpViewManagerConfigTrait.php +++ b/src/Service/HttpViewManagerConfigTrait.php @@ -1,15 +1,19 @@ get('config'); diff --git a/src/Service/ModuleManagerFactory.php b/src/Service/ModuleManagerFactory.php index 2d50ea820..9df025cc8 100644 --- a/src/Service/ModuleManagerFactory.php +++ b/src/Service/ModuleManagerFactory.php @@ -1,13 +1,20 @@ get('ApplicationConfig'); $listenerOptions = new ListenerOptions($configuration['module_listener_options']); @@ -42,32 +49,32 @@ public function __invoke(ContainerInterface $container, $name, array $options = $serviceListener->addServiceManager( $container, 'service_manager', - 'Zend\ModuleManager\Feature\ServiceProviderInterface', + ServiceProviderInterface::class, 'getServiceConfig' ); $serviceListener->addServiceManager( 'ControllerManager', 'controllers', - 'Zend\ModuleManager\Feature\ControllerProviderInterface', + ControllerProviderInterface::class, 'getControllerConfig' ); $serviceListener->addServiceManager( 'ControllerPluginManager', 'controller_plugins', - 'Zend\ModuleManager\Feature\ControllerPluginProviderInterface', + ControllerPluginProviderInterface::class, 'getControllerPluginConfig' ); $serviceListener->addServiceManager( 'ViewHelperManager', 'view_helpers', - 'Zend\ModuleManager\Feature\ViewHelperProviderInterface', + ViewHelperProviderInterface::class, 'getViewHelperConfig' ); $serviceListener->addServiceManager( 'RoutePluginManager', 'route_manager', - 'Zend\ModuleManager\Feature\RouteProviderInterface', + RouteProviderInterface::class, 'getRouteConfig' ); @@ -75,7 +82,7 @@ public function __invoke(ContainerInterface $container, $name, array $options = $defaultListeners->attach($events); $serviceListener->attach($events); - $moduleEvent = new ModuleEvent; + $moduleEvent = new ModuleEvent(); $moduleEvent->setParam('ServiceManager', $container); $moduleManager = new ModuleManager($configuration['modules'], $events); diff --git a/src/Service/PaginatorPluginManagerFactory.php b/src/Service/PaginatorPluginManagerFactory.php index eac7de893..d56e9d704 100644 --- a/src/Service/PaginatorPluginManagerFactory.php +++ b/src/Service/PaginatorPluginManagerFactory.php @@ -1,15 +1,17 @@ [ - 'application' => 'Application', - 'Config' => 'config', - 'configuration' => 'config', - 'Configuration' => 'config', - 'HttpDefaultRenderingStrategy' => View\Http\DefaultRenderingStrategy::class, - 'MiddlewareListener' => 'Zend\Mvc\MiddlewareListener', - 'request' => 'Request', - 'response' => 'Response', - 'RouteListener' => 'Zend\Mvc\RouteListener', - 'SendResponseListener' => 'Zend\Mvc\SendResponseListener', - 'View' => 'Zend\View\View', - 'ViewFeedRenderer' => 'Zend\View\Renderer\FeedRenderer', - 'ViewJsonRenderer' => 'Zend\View\Renderer\JsonRenderer', - 'ViewPhpRendererStrategy' => 'Zend\View\Strategy\PhpRendererStrategy', - 'ViewPhpRenderer' => 'Zend\View\Renderer\PhpRenderer', - 'ViewRenderer' => 'Zend\View\Renderer\PhpRenderer', - 'Zend\Mvc\Controller\PluginManager' => 'ControllerPluginManager', - 'Zend\Mvc\View\Http\InjectTemplateListener' => 'InjectTemplateListener', - 'Zend\View\Renderer\RendererInterface' => 'Zend\View\Renderer\PhpRenderer', - 'Zend\View\Resolver\TemplateMapResolver' => 'ViewTemplateMapResolver', - 'Zend\View\Resolver\TemplatePathStack' => 'ViewTemplatePathStack', - 'Zend\View\Resolver\AggregateResolver' => 'ViewResolver', - 'Zend\View\Resolver\ResolverInterface' => 'ViewResolver', + 'aliases' => [ + 'application' => 'Application', + 'Config' => 'config', + 'configuration' => 'config', + 'Configuration' => 'config', + 'HttpDefaultRenderingStrategy' => DefaultRenderingStrategy::class, + 'MiddlewareListener' => MiddlewareListener::class, + 'request' => 'Request', + 'response' => 'Response', + 'RouteListener' => RouteListener::class, + 'SendResponseListener' => SendResponseListener::class, + 'View' => View::class, + 'ViewFeedRenderer' => FeedRenderer::class, + 'ViewJsonRenderer' => JsonRenderer::class, + 'ViewPhpRendererStrategy' => PhpRendererStrategy::class, + 'ViewPhpRenderer' => PhpRenderer::class, + 'ViewRenderer' => PhpRenderer::class, + PluginManager::class => 'ControllerPluginManager', + InjectTemplateListener::class => 'InjectTemplateListener', + RendererInterface::class => PhpRenderer::class, + TemplateMapResolver::class => 'ViewTemplateMapResolver', + TemplatePathStack::class => 'ViewTemplatePathStack', + AggregateResolver::class => 'ViewResolver', + ResolverInterface::class => 'ViewResolver', ], 'invokables' => [], 'factories' => [ - 'Application' => ApplicationFactory::class, - 'config' => 'Zend\Mvc\Service\ConfigFactory', - 'ControllerManager' => 'Zend\Mvc\Service\ControllerManagerFactory', - 'ControllerPluginManager' => 'Zend\Mvc\Service\ControllerPluginManagerFactory', - 'DispatchListener' => 'Zend\Mvc\Service\DispatchListenerFactory', - 'HttpExceptionStrategy' => HttpExceptionStrategyFactory::class, - 'HttpMethodListener' => 'Zend\Mvc\Service\HttpMethodListenerFactory', - 'HttpRouteNotFoundStrategy' => HttpRouteNotFoundStrategyFactory::class, - 'HttpViewManager' => 'Zend\Mvc\Service\HttpViewManagerFactory', - 'InjectTemplateListener' => 'Zend\Mvc\Service\InjectTemplateListenerFactory', - 'PaginatorPluginManager' => 'Zend\Mvc\Service\PaginatorPluginManagerFactory', - 'Request' => 'Zend\Mvc\Service\RequestFactory', - 'Response' => 'Zend\Mvc\Service\ResponseFactory', - 'ViewHelperManager' => 'Zend\Mvc\Service\ViewHelperManagerFactory', - View\Http\DefaultRenderingStrategy::class => HttpDefaultRenderingStrategyFactory::class, - 'ViewFeedStrategy' => 'Zend\Mvc\Service\ViewFeedStrategyFactory', - 'ViewJsonStrategy' => 'Zend\Mvc\Service\ViewJsonStrategyFactory', - 'ViewManager' => 'Zend\Mvc\Service\ViewManagerFactory', - 'ViewResolver' => 'Zend\Mvc\Service\ViewResolverFactory', - 'ViewTemplateMapResolver' => 'Zend\Mvc\Service\ViewTemplateMapResolverFactory', - 'ViewTemplatePathStack' => 'Zend\Mvc\Service\ViewTemplatePathStackFactory', - 'ViewPrefixPathStackResolver' => 'Zend\Mvc\Service\ViewPrefixPathStackResolverFactory', - 'Zend\Mvc\MiddlewareListener' => InvokableFactory::class, - 'Zend\Mvc\RouteListener' => InvokableFactory::class, - 'Zend\Mvc\SendResponseListener' => SendResponseListenerFactory::class, - 'Zend\View\Renderer\FeedRenderer' => InvokableFactory::class, - 'Zend\View\Renderer\JsonRenderer' => InvokableFactory::class, - 'Zend\View\Renderer\PhpRenderer' => ViewPhpRendererFactory::class, - 'Zend\View\Strategy\PhpRendererStrategy' => ViewPhpRendererStrategyFactory::class, - 'Zend\View\View' => ViewFactory::class, + 'Application' => ApplicationFactory::class, + 'config' => ConfigFactory::class, + 'ControllerManager' => ControllerManagerFactory::class, + 'ControllerPluginManager' => ControllerPluginManagerFactory::class, + 'DispatchListener' => DispatchListenerFactory::class, + 'HttpExceptionStrategy' => HttpExceptionStrategyFactory::class, + 'HttpMethodListener' => HttpMethodListenerFactory::class, + 'HttpRouteNotFoundStrategy' => HttpRouteNotFoundStrategyFactory::class, + 'HttpViewManager' => HttpViewManagerFactory::class, + 'InjectTemplateListener' => InjectTemplateListenerFactory::class, + 'PaginatorPluginManager' => PaginatorPluginManagerFactory::class, + 'Request' => RequestFactory::class, + 'Response' => ResponseFactory::class, + 'ViewHelperManager' => ViewHelperManagerFactory::class, + DefaultRenderingStrategy::class => HttpDefaultRenderingStrategyFactory::class, + 'ViewFeedStrategy' => ViewFeedStrategyFactory::class, + 'ViewJsonStrategy' => ViewJsonStrategyFactory::class, + 'ViewManager' => ViewManagerFactory::class, + 'ViewResolver' => ViewResolverFactory::class, + 'ViewTemplateMapResolver' => ViewTemplateMapResolverFactory::class, + 'ViewTemplatePathStack' => ViewTemplatePathStackFactory::class, + 'ViewPrefixPathStackResolver' => ViewPrefixPathStackResolverFactory::class, + MiddlewareListener::class => InvokableFactory::class, + RouteListener::class => InvokableFactory::class, + SendResponseListener::class => SendResponseListenerFactory::class, + FeedRenderer::class => InvokableFactory::class, + JsonRenderer::class => InvokableFactory::class, + PhpRenderer::class => ViewPhpRendererFactory::class, + PhpRendererStrategy::class => ViewPhpRendererStrategyFactory::class, + View::class => ViewFactory::class, ], ]; @@ -112,14 +135,14 @@ class ServiceListenerFactory implements FactoryInterface * - interface: the name of the interface that modules can implement as string * - method: the name of the method that modules have to implement as string * - * @param ServiceLocatorInterface $serviceLocator + * @param string $requestedName * @return ServiceListenerInterface * @throws ServiceNotCreatedException for invalid ServiceListener service * @throws ServiceNotCreatedException For invalid configurations. */ - public function __invoke(ContainerInterface $container, $requestedName, array $options = null) + public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null) { - $configuration = $container->get('ApplicationConfig'); + $configuration = $container->get('ApplicationConfig'); $serviceListener = $container->has('ServiceListenerInterface') ? $container->get('ServiceListenerInterface') @@ -128,7 +151,7 @@ public function __invoke(ContainerInterface $container, $requestedName, array $o if (! $serviceListener instanceof ServiceListenerInterface) { throw new ServiceNotCreatedException( 'The service named ServiceListenerInterface must implement ' - . ServiceListenerInterface::class + . ServiceListenerInterface::class ); } @@ -144,7 +167,7 @@ public function __invoke(ContainerInterface $container, $requestedName, array $o /** * Validate and inject plugin manager options into the service listener. * - * @param array $options + * @param array $options * @param ServiceListenerInterface $serviceListener * @throws ServiceListenerInterface for invalid $options types */ @@ -153,7 +176,7 @@ private function injectServiceListenerOptions($options, ServiceListenerInterface if (! is_array($options)) { throw new ServiceNotCreatedException(sprintf( 'The value of service_listener_options must be an array, %s given.', - (is_object($options) ? get_class($options) : gettype($options)) + is_object($options) ? get_class($options) : gettype($options) )); } @@ -174,8 +197,8 @@ private function injectServiceListenerOptions($options, ServiceListenerInterface * * Ensures all required keys are present in the expected types. * - * @param array $options - * @param string $name Plugin manager service name; used for exception messages + * @param array $options + * @param string $name Plugin manager service name; used for exception messages * @throws ServiceNotCreatedException for any missing configuration options. * @throws ServiceNotCreatedException for configuration options of invalid types. */ @@ -185,7 +208,7 @@ private function validatePluginManagerOptions($options, $name) throw new ServiceNotCreatedException(sprintf( 'Plugin manager configuration for "%s" is invalid; must be an array, received "%s"', $name, - (is_object($options) ? get_class($options) : gettype($options)) + is_object($options) ? get_class($options) : gettype($options) )); } diff --git a/src/Service/ServiceManagerConfig.php b/src/Service/ServiceManagerConfig.php index dc1073a4e..953b08015 100644 --- a/src/Service/ServiceManagerConfig.php +++ b/src/Service/ServiceManagerConfig.php @@ -1,10 +1,12 @@ 'SharedEventManager', SharedEventManagerInterface::class => 'SharedEventManager', ], - 'delegators' => [], - 'factories' => [ - 'EventManager' => EventManagerFactory::class, - 'ModuleManager' => ModuleManagerFactory::class, - 'ServiceListener' => ServiceListenerFactory::class, + 'delegators' => [], + 'factories' => [ + 'EventManager' => EventManagerFactory::class, + 'ModuleManager' => ModuleManagerFactory::class, + 'ServiceListener' => ServiceListenerFactory::class, ], - 'lazy_services' => [], - 'initializers' => [], - 'invokables' => [], - 'services' => [], - 'shared' => [ + 'lazy_services' => [], + 'initializers' => [], + 'invokables' => [], + 'services' => [], + 'shared' => [ 'EventManager' => false, ], ]; @@ -81,10 +82,10 @@ public function __construct(array $config = []) 'EventManagerAwareInitializer' => function ($first, $second) { if ($first instanceof ContainerInterface) { $container = $first; - $instance = $second; + $instance = $second; } else { $container = $second; - $instance = $first; + $instance = $first; } if (! $instance instanceof EventManagerAwareInterface) { diff --git a/src/Service/ViewFactory.php b/src/Service/ViewFactory.php index ed5852752..89c752497 100644 --- a/src/Service/ViewFactory.php +++ b/src/Service/ViewFactory.php @@ -1,10 +1,12 @@ get('EventManager'); diff --git a/src/Service/ViewFeedStrategyFactory.php b/src/Service/ViewFeedStrategyFactory.php index 61a0d6c1a..82864528f 100644 --- a/src/Service/ViewFeedStrategyFactory.php +++ b/src/Service/ViewFeedStrategyFactory.php @@ -1,10 +1,12 @@ get('ViewFeedRenderer')); } diff --git a/src/Service/ViewHelperManagerFactory.php b/src/Service/ViewHelperManagerFactory.php index 371885b19..d83ba7756 100644 --- a/src/Service/ViewHelperManagerFactory.php +++ b/src/Service/ViewHelperManagerFactory.php @@ -1,10 +1,12 @@ injectOverrideFactories($plugins, $container); @@ -50,7 +54,7 @@ public function __invoke(ContainerInterface $container, $requestedName, array $o * Inject override factories into the plugin manager. * * @param HelperPluginManager $plugins - * @param ContainerInterface $services + * @param ContainerInterface $services * @return HelperPluginManager */ private function injectOverrideFactories(HelperPluginManager $plugins, ContainerInterface $services) @@ -86,13 +90,12 @@ private function injectOverrideFactories(HelperPluginManager $plugins, Container private function createUrlHelperFactory(ContainerInterface $services) { return function () use ($services) { - $helper = new ViewHelper\Url; + $helper = new ViewHelper\Url(); $helper->setRouter($services->get('HttpRouter')); $match = $services->get('Application') ->getMvcEvent() - ->getRouteMatch() - ; + ->getRouteMatch(); if ($match instanceof RouteMatch) { $helper->setRouteMatch($match); @@ -114,7 +117,7 @@ private function createBasePathHelperFactory(ContainerInterface $services) { return function () use ($services) { $config = $services->has('config') ? $services->get('config') : []; - $helper = new ViewHelper\BasePath; + $helper = new ViewHelper\BasePath(); if (isset($config['view_manager']) && isset($config['view_manager']['base_path'])) { $helper->setBasePath($config['view_manager']['base_path']); @@ -144,8 +147,8 @@ private function createDoctypeHelperFactory(ContainerInterface $services) { return function () use ($services) { $config = $services->has('config') ? $services->get('config') : []; - $config = isset($config['view_manager']) ? $config['view_manager'] : []; - $helper = new ViewHelper\Doctype; + $config = $config['view_manager'] ?? []; + $helper = new ViewHelper\Doctype(); if (isset($config['doctype']) && $config['doctype']) { $helper->setDoctype($config['doctype']); } diff --git a/src/Service/ViewJsonStrategyFactory.php b/src/Service/ViewJsonStrategyFactory.php index 1f5615031..efc8389a5 100644 --- a/src/Service/ViewJsonStrategyFactory.php +++ b/src/Service/ViewJsonStrategyFactory.php @@ -1,10 +1,12 @@ get('ViewJsonRenderer'); - $jsonStrategy = new JsonStrategy($jsonRenderer); - return $jsonStrategy; + return new JsonStrategy($jsonRenderer); } } diff --git a/src/Service/ViewManagerFactory.php b/src/Service/ViewManagerFactory.php index 28c1ecb76..097807a05 100644 --- a/src/Service/ViewManagerFactory.php +++ b/src/Service/ViewManagerFactory.php @@ -1,10 +1,12 @@ get('HttpViewManager'); } diff --git a/src/Service/ViewPhpRendererFactory.php b/src/Service/ViewPhpRendererFactory.php index 3cd3d836b..969545e5f 100644 --- a/src/Service/ViewPhpRendererFactory.php +++ b/src/Service/ViewPhpRendererFactory.php @@ -1,10 +1,12 @@ setHelperPluginManager($container->get('ViewHelperManager')); diff --git a/src/Service/ViewPhpRendererStrategyFactory.php b/src/Service/ViewPhpRendererStrategyFactory.php index 6b83c7254..7c5e8d05b 100644 --- a/src/Service/ViewPhpRendererStrategyFactory.php +++ b/src/Service/ViewPhpRendererStrategyFactory.php @@ -1,10 +1,12 @@ get(PhpRenderer::class)); } diff --git a/src/Service/ViewPrefixPathStackResolverFactory.php b/src/Service/ViewPrefixPathStackResolverFactory.php index 08e9f49e1..4c8f85748 100644 --- a/src/Service/ViewPrefixPathStackResolverFactory.php +++ b/src/Service/ViewPrefixPathStackResolverFactory.php @@ -1,10 +1,12 @@ get('config'); $prefixes = []; diff --git a/src/Service/ViewResolverFactory.php b/src/Service/ViewResolverFactory.php index ae743b8d2..9b805afb4 100644 --- a/src/Service/ViewResolverFactory.php +++ b/src/Service/ViewResolverFactory.php @@ -1,16 +1,17 @@ get('ViewTemplateMapResolver'); - /* @var $pathResolver ResolverInterface */ - $pathResolver = $container->get('ViewTemplatePathStack'); - /* @var $prefixPathStackResolver ResolverInterface */ + /** @var ResolverInterface $mapResolver */ + $mapResolver = $container->get('ViewTemplateMapResolver'); + /** @var ResolverInterface $pathResolver */ + $pathResolver = $container->get('ViewTemplatePathStack'); + /** @var ResolverInterface $prefixPathStackResolver */ $prefixPathStackResolver = $container->get('ViewPrefixPathStackResolver'); $resolver diff --git a/src/Service/ViewTemplateMapResolverFactory.php b/src/Service/ViewTemplateMapResolverFactory.php index 18146d50f..6c404250d 100644 --- a/src/Service/ViewTemplateMapResolverFactory.php +++ b/src/Service/ViewTemplateMapResolverFactory.php @@ -1,16 +1,20 @@ get('config'); - $map = []; + $map = []; if (is_array($config) && isset($config['view_manager'])) { $config = $config['view_manager']; if (is_array($config) && isset($config['template_map'])) { diff --git a/src/Service/ViewTemplatePathStackFactory.php b/src/Service/ViewTemplatePathStackFactory.php index cf7f01af0..259aabfc0 100644 --- a/src/Service/ViewTemplatePathStackFactory.php +++ b/src/Service/ViewTemplatePathStackFactory.php @@ -1,16 +1,20 @@ get('config'); diff --git a/src/View/Http/CreateViewModelListener.php b/src/View/Http/CreateViewModelListener.php index f75186110..de250182d 100644 --- a/src/View/Http/CreateViewModelListener.php +++ b/src/View/Http/CreateViewModelListener.php @@ -1,10 +1,12 @@ getResult(); @@ -54,7 +56,7 @@ public function createViewModelFromNull(MvcEvent $e) return; } - $model = new ViewModel; + $model = new ViewModel(); $e->setResult($model); } } diff --git a/src/View/Http/DefaultRenderingStrategy.php b/src/View/Http/DefaultRenderingStrategy.php index 5031966c8..25d8a363b 100644 --- a/src/View/Http/DefaultRenderingStrategy.php +++ b/src/View/Http/DefaultRenderingStrategy.php @@ -1,12 +1,16 @@ render($viewModel); - } catch (\Throwable $ex) { - $caughtException = $ex; - } catch (\Exception $ex) { // @TODO clean up once PHP 7 requirement is enforced + } catch (Throwable $ex) { $caughtException = $ex; } diff --git a/src/View/Http/ExceptionStrategy.php b/src/View/Http/ExceptionStrategy.php index 440358210..d481ddeb1 100644 --- a/src/View/Http/ExceptionStrategy.php +++ b/src/View/Http/ExceptionStrategy.php @@ -1,10 +1,12 @@ getRouteMatch()->getParams(); - $request = $e->getRequest(); + $request = $e->getRequest(); if (! $request instanceof HttpRequest) { // unsupported request type diff --git a/src/View/Http/InjectTemplateListener.php b/src/View/Http/InjectTemplateListener.php index 3b110a787..baadd2a8a 100644 --- a/src/View/Http/InjectTemplateListener.php +++ b/src/View/Http/InjectTemplateListener.php @@ -1,10 +1,12 @@ mapController($controller); - $action = $routeMatch->getParam('action'); + $action = $routeMatch->getParam('action'); if (null !== $action) { $template .= '/' . $this->inflectName($action); } @@ -105,10 +124,10 @@ public function mapController($controller) { $mapped = ''; foreach ($this->controllerMap as $namespace => $replacement) { - if (// Allow disabling rule by setting value to false since config - // merging have no feature to remove entries - false == $replacement - // Match full class or full namespace + // Allow disabling rule by setting value to false since config + // merging have no feature to remove entries + if (false === $replacement + // Match full class or full namespace || ! ($controller === $namespace || strpos($controller, $namespace . '\\') === 0) ) { continue; @@ -116,7 +135,7 @@ public function mapController($controller) // Map namespace to $replacement if its value is string if (is_string($replacement)) { - $mapped = rtrim($replacement, '/') . '/'; + $mapped = rtrim($replacement, '/') . '/'; $controller = substr($controller, strlen($namespace) + 1) ?: ''; break; } @@ -127,7 +146,7 @@ public function mapController($controller) array_pop($parts); $parts = array_diff($parts, ['Controller']); //strip trailing Controller in class name - $parts[] = $this->deriveControllerClass($controller); + $parts[] = $this->deriveControllerClass($controller); $controller = implode('/', $parts); $template = trim($mapped . $controller, '/'); @@ -173,7 +192,7 @@ protected function deriveControllerClass($controller) } if ((10 < strlen($controller)) - && ('Controller' == substr($controller, -10)) + && ('Controller' === substr($controller, -10)) ) { $controller = substr($controller, 0, -10); } @@ -185,7 +204,7 @@ protected function deriveControllerClass($controller) * Sets the flag to instruct the listener to prefer the route match controller param * over the class name * - * @param boolean $preferRouteMatchController + * @param bool $preferRouteMatchController */ public function setPreferRouteMatchController($preferRouteMatchController) { @@ -193,7 +212,7 @@ public function setPreferRouteMatchController($preferRouteMatchController) } /** - * @return boolean + * @return bool */ public function isPreferRouteMatchController() { diff --git a/src/View/Http/InjectViewModelListener.php b/src/View/Http/InjectViewModelListener.php index 6a61a9b32..cb02d3219 100644 --- a/src/View/Http/InjectViewModelListener.php +++ b/src/View/Http/InjectViewModelListener.php @@ -1,10 +1,12 @@ reason = $error; - $response = $e->getResponse(); + $response = $e->getResponse(); if (! $response) { $response = new HttpResponse(); $e->setResponse($response); @@ -169,7 +174,7 @@ public function prepareNotFoundViewModel(MvcEvent $e) } $response = $e->getResponse(); - if ($response->getStatusCode() != 404) { + if ($response->getStatusCode() !== 404) { // Only handle 404 responses return; } @@ -236,7 +241,7 @@ protected function injectNotFoundReason(ViewModel $model) * event, inject it into the model. * * @param ViewModel $model - * @param MvcEvent $e + * @param MvcEvent $e * @return void */ protected function injectException($model, $e) @@ -250,7 +255,7 @@ protected function injectException($model, $e) $exception = $e->getParam('exception', false); // @TODO clean up once PHP 7 requirement is enforced - if (! $exception instanceof \Exception && ! $exception instanceof \Throwable) { + if (! $exception instanceof Exception && ! $exception instanceof Throwable) { return; } @@ -267,7 +272,7 @@ protected function injectException($model, $e) * the model. * * @param ViewModel $model - * @param MvcEvent $e + * @param MvcEvent $e * @return void */ protected function injectController($model, $e) diff --git a/src/View/Http/ViewManager.php b/src/View/Http/ViewManager.php index 67802c5ac..8675358df 100644 --- a/src/View/Http/ViewManager.php +++ b/src/View/Http/ViewManager.php @@ -1,10 +1,12 @@ config = isset($config['view_manager']) && (is_array($config['view_manager']) - || $config['view_manager'] instanceof ArrayAccess) - ? $config['view_manager'] - : []; + || $config['view_manager'] instanceof ArrayAccess) + ? $config['view_manager'] + : []; $this->services = $services; $this->event = $event; - $routeNotFoundStrategy = $services->get('HttpRouteNotFoundStrategy'); - $exceptionStrategy = $services->get('HttpExceptionStrategy'); - $mvcRenderingStrategy = $services->get('HttpDefaultRenderingStrategy'); + $routeNotFoundStrategy = $services->get('HttpRouteNotFoundStrategy'); + $exceptionStrategy = $services->get('HttpExceptionStrategy'); + $mvcRenderingStrategy = $services->get('HttpDefaultRenderingStrategy'); $this->injectViewModelIntoPlugin(); - $injectTemplateListener = $services->get('Zend\Mvc\View\Http\InjectTemplateListener'); + $injectTemplateListener = $services->get(InjectTemplateListener::class); $createViewModelListener = new CreateViewModelListener(); $injectViewModelListener = new InjectViewModelListener(); @@ -118,31 +119,31 @@ public function onBootstrap($event) $mvcRenderingStrategy->attach($events); $sharedEvents->attach( - 'Zend\Stdlib\DispatchableInterface', + DispatchableInterface::class, MvcEvent::EVENT_DISPATCH, [$createViewModelListener, 'createViewModelFromArray'], -80 ); $sharedEvents->attach( - 'Zend\Stdlib\DispatchableInterface', + DispatchableInterface::class, MvcEvent::EVENT_DISPATCH, [$routeNotFoundStrategy, 'prepareNotFoundViewModel'], -90 ); $sharedEvents->attach( - 'Zend\Stdlib\DispatchableInterface', + DispatchableInterface::class, MvcEvent::EVENT_DISPATCH, [$createViewModelListener, 'createViewModelFromNull'], -80 ); $sharedEvents->attach( - 'Zend\Stdlib\DispatchableInterface', + DispatchableInterface::class, MvcEvent::EVENT_DISPATCH, [$injectTemplateListener, 'injectTemplate'], -90 ); $sharedEvents->attach( - 'Zend\Stdlib\DispatchableInterface', + DispatchableInterface::class, MvcEvent::EVENT_DISPATCH, [$injectViewModelListener, 'injectViewModel'], -100 @@ -167,7 +168,7 @@ public function getView() /** * Configures the MvcEvent view model to ensure it has the template injected * - * @return \Zend\View\Model\ModelInterface + * @return ModelInterface */ public function getViewModel() { diff --git a/test/Application/AllowsReturningEarlyFromRoutingTest.php b/test/Application/AllowsReturningEarlyFromRoutingTest.php index 77b0f560f..9f7f9f1d8 100644 --- a/test/Application/AllowsReturningEarlyFromRoutingTest.php +++ b/test/Application/AllowsReturningEarlyFromRoutingTest.php @@ -1,10 +1,12 @@ [ 'routes' => [ 'path' => [ - 'type' => Router\Http\Literal::class, + 'type' => Router\Http\Literal::class, 'options' => [ - 'route' => '/bad', + 'route' => '/bad', 'defaults' => [ 'controller' => 'bad', 'action' => 'test', @@ -42,7 +43,7 @@ public function prepareApplication() ]; $serviceListener = new ServiceListenerFactory(); - $r = new ReflectionProperty($serviceListener, 'defaultServiceConfig'); + $r = new ReflectionProperty($serviceListener, 'defaultServiceConfig'); $r->setAccessible(true); $serviceConfig = $r->getValue($serviceListener); @@ -54,19 +55,21 @@ public function prepareApplication() $serviceConfig = ArrayUtils::merge( $serviceConfig, [ - 'aliases' => [ + 'aliases' => [ 'ControllerLoader' => ControllerManager::class, 'ControllerManager' => ControllerManager::class, ], - 'factories' => [ + 'factories' => [ ControllerManager::class => function ($services) { - return new ControllerManager($services, ['factories' => [ - 'bad' => function () { - return new BadController(); - }, - ]]); + return new ControllerManager($services, [ + 'factories' => [ + 'bad' => function () { + return new BadController(); + }, + ], + ]); }, - 'Router' => function ($services) { + 'Router' => function ($services) { return $services->get('HttpRouter'); }, ], @@ -77,8 +80,8 @@ public function prepareApplication() 'SendResponseListener' => TestAsset\MockSendResponseListener::class, 'BootstrapListener' => TestAsset\StubBootstrapListener::class, ], - 'services' => [ - 'config' => $config, + 'services' => [ + 'config' => $config, 'ApplicationConfig' => [ 'modules' => [], 'module_listener_options' => [ @@ -90,7 +93,7 @@ public function prepareApplication() ], ] ); - $services = new ServiceManager(); + $services = new ServiceManager(); (new ServiceManagerConfig($serviceConfig))->configureServiceManager($services); $application = $services->get('Application'); diff --git a/test/Application/ControllerIsDispatchedTest.php b/test/Application/ControllerIsDispatchedTest.php index 8a8aef6f2..92db3d39d 100644 --- a/test/Application/ControllerIsDispatchedTest.php +++ b/test/Application/ControllerIsDispatchedTest.php @@ -1,10 +1,12 @@ attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) use ($response) { $error = $e->getError(); $controller = $e->getController(); - $response->setContent("Code: " . $error . '; Controller: ' . $controller); + $response->setContent('Code: ' . $error . '; Controller: ' . $controller); return $response; }); diff --git a/test/Application/InabilityToRetrieveControllerShouldTriggerExceptionTest.php b/test/Application/InabilityToRetrieveControllerShouldTriggerExceptionTest.php index bbfe16aaf..9e32d129b 100644 --- a/test/Application/InabilityToRetrieveControllerShouldTriggerExceptionTest.php +++ b/test/Application/InabilityToRetrieveControllerShouldTriggerExceptionTest.php @@ -1,10 +1,12 @@ attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) use ($response) { $error = $e->getError(); $controller = $e->getController(); - $response->setContent("Code: " . $error . '; Controller: ' . $controller); + $response->setContent('Code: ' . $error . '; Controller: ' . $controller); return $response; }); diff --git a/test/Application/InitializationIntegrationTest.php b/test/Application/InitializationIntegrationTest.php index 43129c998..e6d7ca2f6 100644 --- a/test/Application/InitializationIntegrationTest.php +++ b/test/Application/InitializationIntegrationTest.php @@ -1,22 +1,27 @@ [ + 'modules' => [ 'Zend\Router', 'Application', ], diff --git a/test/Application/InvalidControllerTypeShouldTriggerDispatchErrorTest.php b/test/Application/InvalidControllerTypeShouldTriggerDispatchErrorTest.php index 79b1ede2c..2fd48933e 100644 --- a/test/Application/InvalidControllerTypeShouldTriggerDispatchErrorTest.php +++ b/test/Application/InvalidControllerTypeShouldTriggerDispatchErrorTest.php @@ -1,17 +1,19 @@ getError(); $controller = $e->getController(); $class = $e->getControllerClass(); - $response->setContent("Code: " . $error . '; Controller: ' . $controller . '; Class: ' . $class); + $response->setContent('Code: ' . $error . '; Controller: ' . $controller . '; Class: ' . $class); return $response; }); diff --git a/test/Application/InvalidControllerTypeTrait.php b/test/Application/InvalidControllerTypeTrait.php index 5478a638a..f300eeeb1 100644 --- a/test/Application/InvalidControllerTypeTrait.php +++ b/test/Application/InvalidControllerTypeTrait.php @@ -1,20 +1,21 @@ [ 'routes' => [ 'path' => [ - 'type' => Router\Http\Literal::class, + 'type' => Router\Http\Literal::class, 'options' => [ - 'route' => '/bad', + 'route' => '/bad', 'defaults' => [ 'controller' => 'bad', 'action' => 'test', @@ -42,7 +43,7 @@ public function prepareApplication() ]; $serviceListener = new ServiceListenerFactory(); - $r = new ReflectionProperty($serviceListener, 'defaultServiceConfig'); + $r = new ReflectionProperty($serviceListener, 'defaultServiceConfig'); $r->setAccessible(true); $serviceConfig = $r->getValue($serviceListener); @@ -54,18 +55,20 @@ public function prepareApplication() $serviceConfig = ArrayUtils::merge( $serviceConfig, [ - 'aliases' => [ - 'ControllerLoader' => 'ControllerManager', + 'aliases' => [ + 'ControllerLoader' => 'ControllerManager', ], - 'factories' => [ + 'factories' => [ 'ControllerManager' => function ($services) { - return new ControllerManager($services, ['factories' => [ - 'bad' => function () { - return new stdClass(); - }, - ]]); + return new ControllerManager($services, [ + 'factories' => [ + 'bad' => function () { + return new stdClass(); + }, + ], + ]); }, - 'Router' => function ($services) { + 'Router' => function ($services) { return $services->get('HttpRouter'); }, ], @@ -76,8 +79,8 @@ public function prepareApplication() 'SendResponseListener' => TestAsset\MockSendResponseListener::class, 'BootstrapListener' => TestAsset\StubBootstrapListener::class, ], - 'services' => [ - 'config' => $config, + 'services' => [ + 'config' => $config, 'ApplicationConfig' => [ 'modules' => [], 'module_listener_options' => [ @@ -89,7 +92,7 @@ public function prepareApplication() ], ] ); - $services = new ServiceManager(); + $services = new ServiceManager(); (new ServiceManagerConfig($serviceConfig))->configureServiceManager($services); $application = $services->get('Application'); diff --git a/test/Application/MissingControllerTrait.php b/test/Application/MissingControllerTrait.php index 8921b78ea..d2bba0075 100644 --- a/test/Application/MissingControllerTrait.php +++ b/test/Application/MissingControllerTrait.php @@ -1,18 +1,19 @@ [ 'routes' => [ 'path' => [ - 'type' => Router\Http\Literal::class, + 'type' => Router\Http\Literal::class, 'options' => [ - 'route' => '/bad', + 'route' => '/bad', 'defaults' => [ 'controller' => 'bad', 'action' => 'test', @@ -40,7 +41,7 @@ public function prepareApplication() ]; $serviceListener = new ServiceListenerFactory(); - $r = new ReflectionProperty($serviceListener, 'defaultServiceConfig'); + $r = new ReflectionProperty($serviceListener, 'defaultServiceConfig'); $r->setAccessible(true); $serviceConfig = $r->getValue($serviceListener); @@ -52,7 +53,7 @@ public function prepareApplication() $serviceConfig = ArrayUtils::merge( $serviceConfig, [ - 'factories' => [ + 'factories' => [ 'Router' => function ($services) { return $services->get('HttpRouter'); }, @@ -64,8 +65,8 @@ public function prepareApplication() 'SendResponseListener' => TestAsset\MockSendResponseListener::class, 'BootstrapListener' => TestAsset\StubBootstrapListener::class, ], - 'services' => [ - 'config' => $config, + 'services' => [ + 'config' => $config, 'ApplicationConfig' => [ 'modules' => [], 'module_listener_options' => [ @@ -77,7 +78,7 @@ public function prepareApplication() ], ] ); - $services = new ServiceManager(); + $services = new ServiceManager(); (new ServiceManagerConfig($serviceConfig))->configureServiceManager($services); $application = $services->get('Application'); diff --git a/test/Application/PathControllerTrait.php b/test/Application/PathControllerTrait.php index f511e8684..eae92c6cb 100644 --- a/test/Application/PathControllerTrait.php +++ b/test/Application/PathControllerTrait.php @@ -1,19 +1,20 @@ [ 'routes' => [ 'path' => [ - 'type' => Router\Http\Literal::class, + 'type' => Router\Http\Literal::class, 'options' => [ - 'route' => '/path', + 'route' => '/path', 'defaults' => [ 'controller' => 'path', ], @@ -40,7 +41,7 @@ public function prepareApplication() ]; $serviceListener = new ServiceListenerFactory(); - $r = new ReflectionProperty($serviceListener, 'defaultServiceConfig'); + $r = new ReflectionProperty($serviceListener, 'defaultServiceConfig'); $r->setAccessible(true); $serviceConfig = $r->getValue($serviceListener); @@ -52,19 +53,21 @@ public function prepareApplication() $serviceConfig = ArrayUtils::merge( $serviceConfig, [ - 'aliases' => [ + 'aliases' => [ 'ControllerLoader' => ControllerManager::class, 'ControllerManager' => ControllerManager::class, ], - 'factories' => [ + 'factories' => [ ControllerManager::class => function ($services) { - return new ControllerManager($services, ['factories' => [ - 'path' => function () { - return new TestAsset\PathController(); - }, - ]]); + return new ControllerManager($services, [ + 'factories' => [ + 'path' => function () { + return new TestAsset\PathController(); + }, + ], + ]); }, - 'Router' => function ($services) { + 'Router' => function ($services) { return $services->get('HttpRouter'); }, ], @@ -75,8 +78,8 @@ public function prepareApplication() 'SendResponseListener' => TestAsset\MockSendResponseListener::class, 'BootstrapListener' => TestAsset\StubBootstrapListener::class, ], - 'services' => [ - 'config' => $config, + 'services' => [ + 'config' => $config, 'ApplicationConfig' => [ 'modules' => [ 'Zend\Router', @@ -90,7 +93,7 @@ public function prepareApplication() ], ] ); - $services = new ServiceManager(); + $services = new ServiceManager(); (new ServiceManagerConfig($serviceConfig))->configureServiceManager($services); $application = $services->get('Application'); diff --git a/test/Application/RoutingSuccessTest.php b/test/Application/RoutingSuccessTest.php index d2c05d6af..4c20afcb6 100644 --- a/test/Application/RoutingSuccessTest.php +++ b/test/Application/RoutingSuccessTest.php @@ -1,10 +1,12 @@ [ + 'controllers' => [ 'factories' => [ 'path' => function () { return new Controller\PathController(); }, ], ], - 'router' => [ + 'router' => [ 'routes' => [ 'path' => [ - 'type' => 'literal', + 'type' => 'literal', 'options' => [ - 'route' => '/path', + 'route' => '/path', 'defaults' => [ 'controller' => 'path', ], @@ -35,29 +37,29 @@ ], 'service_manager' => [ 'factories' => [ - 'Request' => function () { + 'Request' => function () { return new HttpRequest(); }, - 'Response' => function () { + 'Response' => function () { return new HttpResponse(); }, 'Router' => HttpRouterFactory::class, 'ViewManager' => HttpViewManagerFactory::class, ], ], - 'view_manager' => [ + 'view_manager' => [ 'display_not_found_reason' => true, 'display_exceptions' => true, 'doctype' => 'HTML5', 'not_found_template' => 'error/404', 'exception_template' => 'error/index', - 'template_map' => [ + 'template_map' => [ 'layout/layout' => __DIR__ . '/../view/layout/layout.phtml', 'application/index/index' => __DIR__ . '/../view/application/index/index.phtml', 'error/404' => __DIR__ . '/../view/error/404.phtml', 'error/index' => __DIR__ . '/../view/error/index.phtml', ], - 'template_path_stack' => [ + 'template_path_stack' => [ __DIR__ . '/../view', ], ], diff --git a/test/Application/TestAsset/modules/Application/src/Application/Controller/PathController.php b/test/Application/TestAsset/modules/Application/src/Application/Controller/PathController.php index fd9db7fe9..2a0e3591e 100644 --- a/test/Application/TestAsset/modules/Application/src/Application/Controller/PathController.php +++ b/test/Application/TestAsset/modules/Application/src/Application/Controller/PathController.php @@ -1,10 +1,12 @@ setAccessible(true); $serviceConfig = $r->getValue($serviceListener); @@ -55,7 +61,7 @@ public function setUp() : void (new Router\ConfigProvider())->getDependencyConfig() ); - $serviceConfig = ArrayUtils::merge( + $serviceConfig = ArrayUtils::merge( $serviceConfig, [ 'invokables' => [ @@ -65,13 +71,13 @@ public function setUp() : void 'SendResponseListener' => TestAsset\MockSendResponseListener::class, 'BootstrapListener' => TestAsset\StubBootstrapListener::class, ], - 'factories' => [ + 'factories' => [ 'Router' => Router\RouterFactory::class, ], - 'services' => [ - 'config' => [], + 'services' => [ + 'config' => [], 'ApplicationConfig' => [ - 'modules' => [ + 'modules' => [ 'Zend\Router', ], 'module_listener_options' => [ @@ -146,20 +152,20 @@ public function testConfigIsPopulated() $this->assertEquals( $smConfig, $appConfig, - sprintf('SM config: %s; App config: %s', var_export($smConfig, 1), var_export($appConfig, 1)) + sprintf('SM config: %s; App config: %s', var_export($smConfig, true), var_export($appConfig, true)) ); } public function testEventsAreEmptyAtFirst() { - $events = $this->application->getEventManager(); + $events = $this->application->getEventManager(); $registeredEvents = $this->getEventsFromEventManager($events); $this->assertEquals([], $registeredEvents); $sharedEvents = $events->getSharedManager(); $this->assertInstanceOf(SharedEventManager::class, $sharedEvents); /** - * @TODO change test not to depend on internal state + * @todo change test not to depend on internal state */ $property = new ReflectionProperty(SharedEventManager::class, 'identifiers'); $property->setAccessible(true); @@ -180,7 +186,7 @@ public function testBootstrapRegistersListeners($listenerServiceName, $event, $m $events = $this->application->getEventManager(); $foundListener = false; - $listeners = $this->getArrayOfListenersForEvent($event, $events); + $listeners = $this->getArrayOfListenersForEvent($event, $events); $this->assertContains([$listenerService, $method], $listeners); } @@ -205,7 +211,7 @@ public function testBootstrapAlwaysRegistersDefaultListeners() $r = new ReflectionProperty($this->application, 'defaultListeners'); $r->setAccessible(true); $defaultListenersNames = $r->getValue($this->application); - $defaultListeners = []; + $defaultListeners = []; foreach ($defaultListenersNames as $defaultListenerName) { $defaultListeners[] = $this->serviceManager->get($defaultListenerName); } @@ -265,11 +271,13 @@ public function setupPathController($addService = true) if ($addService) { $this->services->addFactory('ControllerManager', function ($services) { - return new ControllerManager($services, ['factories' => [ - 'path' => function () { - return new TestAsset\PathController; - }, - ]]); + return new ControllerManager($services, [ + 'factories' => [ + 'path' => function () { + return new TestAsset\PathController(); + }, + ], + ]); }); } @@ -293,11 +301,13 @@ public function setupActionController() $router->addRoute('sample', $route); $this->serviceManager->setFactory('ControllerManager', function ($services) { - return new ControllerManager($services, ['factories' => [ - 'sample' => function () { - return new Controller\TestAsset\SampleController(); - }, - ]]); + return new ControllerManager($services, [ + 'factories' => [ + 'sample' => function () { + return new Controller\TestAsset\SampleController(); + }, + ], + ]); }); $this->application->bootstrap(); @@ -321,11 +331,13 @@ public function setupBadController($addService = true, $action = 'test') if ($addService) { $this->serviceManager->setFactory('ControllerManager', function ($services) { - return new ControllerManager($services, ['factories' => [ - 'bad' => function () { - return new Controller\TestAsset\BadController(); - }, - ]]); + return new ControllerManager($services, [ + 'factories' => [ + 'bad' => function () { + return new Controller\TestAsset\BadController(); + }, + ], + ]); }); } @@ -360,8 +372,8 @@ public function testRoutingFailureShouldTriggerDispatchError() $response = $application->getResponse(); $events = $application->getEventManager(); $events->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) use ($response) { - $error = $e->getError(); - $response->setContent("Code: " . $error); + $error = $e->getError(); + $response->setContent('Code: ' . $error); return $response; }); @@ -375,9 +387,9 @@ public function testRoutingFailureShouldTriggerDispatchError() */ public function testLocatorExceptionShouldTriggerDispatchError() { - $application = $this->setupPathController(false); + $application = $this->setupPathController(false); $controllerLoader = $application->getServiceManager()->get('ControllerManager'); - $response = new Response(); + $response = new Response(); $application->getEventManager()->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) use ($response) { return $response; }); @@ -419,8 +431,8 @@ public function testFailureForRouteToReturnRouteMatchShouldPopulateEventError() $response = $application->getResponse(); $events = $application->getEventManager(); $events->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) use ($response) { - $error = $e->getError(); - $response->setContent("Code: " . $error); + $error = $e->getError(); + $response->setContent('Code: ' . $error); return $response; }); @@ -441,7 +453,7 @@ public function testFinishShouldRunEvenIfRouteEventReturnsResponse() return $response; }, 100); - $token = new stdClass; + $token = new stdClass(); $events->attach(MvcEvent::EVENT_FINISH, function ($e) use ($token) { $token->foo = 'bar'; }); @@ -464,7 +476,7 @@ public function testFinishShouldRunEvenIfDispatchEventReturnsResponse() return $response; }, 100); - $token = new stdClass; + $token = new stdClass(); $events->attach(MvcEvent::EVENT_FINISH, function ($e) use ($token) { $token->foo = 'bar'; }); @@ -481,7 +493,7 @@ public function testApplicationShouldBeEventTargetAtFinishEvent() $events = $application->getEventManager(); $response = $application->getResponse(); $events->attach(MvcEvent::EVENT_FINISH, function ($e) use ($response) { - $response->setContent("EventClass: " . get_class($e->getTarget())); + $response->setContent('EventClass: ' . get_class($e->getTarget())); return $response; }); @@ -491,9 +503,9 @@ public function testApplicationShouldBeEventTargetAtFinishEvent() public function testOnDispatchErrorEventPassedToTriggersShouldBeTheOriginalOne() { - $application = $this->setupPathController(false); + $application = $this->setupPathController(false); $controllerManager = $application->getServiceManager()->get('ControllerManager'); - $model = $this->createMock(ViewModel::class); + $model = $this->createMock(ViewModel::class); $application->getEventManager()->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) use ($model) { $e->setResult($model); }); @@ -510,8 +522,8 @@ public function testReturnsResponseFromListenerWhenRouteEventShortCircuits() { $this->application->bootstrap(); $testResponse = new Response(); - $response = $this->application->getResponse(); - $events = $this->application->getEventManager(); + $response = $this->application->getResponse(); + $events = $this->application->getEventManager(); $events->clearListeners(MvcEvent::EVENT_DISPATCH); $events->attach(MvcEvent::EVENT_ROUTE, function ($e) use ($testResponse) { $testResponse->setContent('triggered'); @@ -535,8 +547,8 @@ public function testReturnsResponseFromListenerWhenDispatchEventShortCircuits() { $this->application->bootstrap(); $testResponse = new Response(); - $response = $this->application->getResponse(); - $events = $this->application->getEventManager(); + $response = $this->application->getResponse(); + $events = $this->application->getEventManager(); $events->clearListeners(MvcEvent::EVENT_ROUTE); $events->attach(MvcEvent::EVENT_DISPATCH, function ($e) use ($testResponse) { $testResponse->setContent('triggered'); @@ -655,9 +667,9 @@ public function testEventPropagationStatusIsClearedBetweenEventsDuringRun($event $event = new MvcEvent(); $event->setTarget($this->application); $event->setApplication($this->application) - ->setRequest($this->application->getRequest()) - ->setResponse($this->application->getResponse()) - ->setRouter($this->serviceManager->get('Router')); + ->setRequest($this->application->getRequest()) + ->setResponse($this->application->getResponse()) + ->setRouter($this->serviceManager->get('Router')); $event->stopPropagation(true); // Intentionally not calling bootstrap; setting mvc event @@ -670,7 +682,7 @@ public function testEventPropagationStatusIsClearedBetweenEventsDuringRun($event foreach ($events as $event) { $marker[$event] = true; } - $marker = (object) $marker; + $marker = (object) $marker; $listener = function ($e) use ($marker) { $marker->{$e->getName()} = $e->propagationIsStopped(); $e->stopPropagation(true); diff --git a/test/Controller/AbstractControllerTest.php b/test/Controller/AbstractControllerTest.php index e2ae7c021..d6a8a795e 100644 --- a/test/Controller/AbstractControllerTest.php +++ b/test/Controller/AbstractControllerTest.php @@ -1,13 +1,16 @@ createMock(EventManagerInterface::class); $eventManager @@ -54,7 +55,7 @@ public function testSetEventManagerWithDefaultIdentifiers() */ public function testSetEventManagerWithCustomStringIdentifier() { - /* @var $eventManager EventManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EventManagerInterface|PHPUnit_Framework_MockObject_MockObject $eventManager */ $eventManager = $this->createMock(EventManagerInterface::class); $eventManager->expects($this->once())->method('setIdentifiers')->with($this->contains('customEventIdentifier')); @@ -72,7 +73,7 @@ public function testSetEventManagerWithCustomStringIdentifier() */ public function testSetEventManagerWithMultipleCustomStringIdentifier() { - /* @var $eventManager EventManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EventManagerInterface|PHPUnit_Framework_MockObject_MockObject $eventManager */ $eventManager = $this->createMock(EventManagerInterface::class); $eventManager->expects($this->once())->method('setIdentifiers')->with($this->logicalAnd( @@ -93,7 +94,7 @@ public function testSetEventManagerWithMultipleCustomStringIdentifier() */ public function testSetEventManagerWithDefaultIdentifiersIncludesImplementedInterfaces() { - /* @var $eventManager EventManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ + /** @var EventManagerInterface|PHPUnit_Framework_MockObject_MockObject $eventManager */ $eventManager = $this->createMock(EventManagerInterface::class); $eventManager diff --git a/test/Controller/ActionControllerTest.php b/test/Controller/ActionControllerTest.php index e3b29b145..36c29d38d 100644 --- a/test/Controller/ActionControllerTest.php +++ b/test/Controller/ActionControllerTest.php @@ -1,14 +1,15 @@ controller->dispatch($this->request, $this->response); + $result = $this->controller->dispatch($this->request, $this->response); $response = $this->controller->getResponse(); $this->assertEquals(404, $response->getStatusCode()); $this->assertInstanceOf(ModelInterface::class, $result); $this->assertEquals('content', $result->captureTo()); $vars = $result->getVariables(); - $this->assertArrayHasKey('content', $vars, var_export($vars, 1)); + $this->assertArrayHasKey('content', $vars, var_export($vars, true)); $this->assertStringContainsString('Page not found', $vars['content']); } public function testDispatchInvokesNotFoundActionWhenInvalidActionPresentInRouteMatch() { $this->routeMatch->setParam('action', 'totally-made-up-action'); - $result = $this->controller->dispatch($this->request, $this->response); + $result = $this->controller->dispatch($this->request, $this->response); $response = $this->controller->getResponse(); $this->assertEquals(404, $response->getStatusCode()); $this->assertInstanceOf(ModelInterface::class, $result); $this->assertEquals('content', $result->captureTo()); $vars = $result->getVariables(); - $this->assertArrayHasKey('content', $vars, var_export($vars, 1)); + $this->assertArrayHasKey('content', $vars, var_export($vars, true)); $this->assertStringContainsString('Page not found', $vars['content']); } diff --git a/test/Controller/ControllerManagerTest.php b/test/Controller/ControllerManagerTest.php index 684306a9d..4af072019 100644 --- a/test/Controller/ControllerManagerTest.php +++ b/test/Controller/ControllerManagerTest.php @@ -1,14 +1,15 @@ sharedEvents = new SharedEventManager; - $this->events = $this->createEventManager($this->sharedEvents); + $this->sharedEvents = new SharedEventManager(); + $this->events = $this->createEventManager($this->sharedEvents); $this->services = new ServiceManager(); (new Config([ @@ -34,7 +35,7 @@ public function setUp() : void return new ControllerPluginManager($services); }, ], - 'services' => [ + 'services' => [ 'EventManager' => $this->events, 'SharedEventManager' => $this->sharedEvents, ], @@ -44,7 +45,6 @@ public function setUp() : void } /** - * @param SharedEventManager * @return EventManager */ protected function createEventManager(SharedEventManagerInterface $sharedManager) @@ -88,8 +88,8 @@ public function testInjectEventManagerWillNotOverwriteExistingEventManagerIfItAl } /** - * @covers Zend\ServiceManager\ServiceManager::has - * @covers Zend\ServiceManager\AbstractPluginManager::get + * @covers \Zend\ServiceManager\ServiceManager::has + * @covers \Zend\ServiceManager\AbstractPluginManager::get */ public function testDoNotUsePeeringServiceManagers() { diff --git a/test/Controller/IntegrationTest.php b/test/Controller/IntegrationTest.php index 6223ae180..5aa4e9385 100644 --- a/test/Controller/IntegrationTest.php +++ b/test/Controller/IntegrationTest.php @@ -1,10 +1,12 @@ services = new ServiceManager(); (new Config([ - 'services' => [ + 'services' => [ 'SharedEventManager' => $this->sharedEvents, ], 'factories' => [ 'ControllerPluginManager' => function ($services) { return new PluginManager($services); }, - 'EventManager' => function () { + 'EventManager' => function () { return new EventManager($this->sharedEvents); }, ], - 'shared' => [ + 'shared' => [ 'EventManager' => false, ], ]))->configureServiceManager($this->services); @@ -42,14 +44,16 @@ public function setUp() : void public function testPluginReceivesCurrentController() { - $controllers = new ControllerManager($this->services, ['factories' => [ - 'first' => function ($services) { - return new TestAsset\SampleController(); - }, - 'second' => function ($services) { - return new TestAsset\SampleController(); - }, - ]]); + $controllers = new ControllerManager($this->services, [ + 'factories' => [ + 'first' => function ($services) { + return new TestAsset\SampleController(); + }, + 'second' => function ($services) { + return new TestAsset\SampleController(); + }, + ], + ]); $first = $controllers->get('first'); $second = $controllers->get('second'); diff --git a/test/Controller/LazyControllerAbstractFactoryTest.php b/test/Controller/LazyControllerAbstractFactoryTest.php index 1865e45d2..879a87dea 100644 --- a/test/Controller/LazyControllerAbstractFactoryTest.php +++ b/test/Controller/LazyControllerAbstractFactoryTest.php @@ -1,10 +1,12 @@ assertFalse($factory->canCreate($this->container->reveal(), __CLASS__)); + $this->assertFalse($factory->canCreate($this->container->reveal(), self::class)); } public function testFactoryInstantiatesClassDirectlyIfItHasNoConstructor() { - $factory = new LazyControllerAbstractFactory(); + $factory = new LazyControllerAbstractFactory(); $controller = $factory($this->container->reveal(), TestAsset\SampleController::class); $this->assertInstanceOf(TestAsset\SampleController::class, $controller); } public function testFactoryInstantiatesClassDirectlyIfConstructorHasNoArguments() { - $factory = new LazyControllerAbstractFactory(); + $factory = new LazyControllerAbstractFactory(); $controller = $factory($this->container->reveal(), TestAsset\ControllerWithEmptyConstructor::class); $this->assertInstanceOf(TestAsset\ControllerWithEmptyConstructor::class, $controller); } @@ -73,7 +77,7 @@ public function testFactoryRaisesExceptionWhenUnableToResolveATypeHintedService( public function testFactoryPassesNullForScalarParameters() { - $factory = new LazyControllerAbstractFactory(); + $factory = new LazyControllerAbstractFactory(); $controller = $factory($this->container->reveal(), TestAsset\ControllerWithScalarParameters::class); $this->assertInstanceOf(TestAsset\ControllerWithScalarParameters::class, $controller); $this->assertNull($controller->foo); @@ -86,7 +90,7 @@ public function testFactoryInjectsConfigServiceForConfigArgumentsTypeHintedAsArr $this->container->has('config')->willReturn(true); $this->container->get('config')->willReturn($config); - $factory = new LazyControllerAbstractFactory(); + $factory = new LazyControllerAbstractFactory(); $controller = $factory($this->container->reveal(), TestAsset\ControllerAcceptingConfigToConstructor::class); $this->assertInstanceOf(TestAsset\ControllerAcceptingConfigToConstructor::class, $controller); $this->assertEquals($config, $controller->config); @@ -98,7 +102,7 @@ public function testFactoryCanInjectKnownTypeHintedServices() $this->container->has(TestAsset\SampleInterface::class)->willReturn(true); $this->container->get(TestAsset\SampleInterface::class)->willReturn($sample); - $factory = new LazyControllerAbstractFactory(); + $factory = new LazyControllerAbstractFactory(); $controller = $factory( $this->container->reveal(), TestAsset\ControllerWithTypeHintedConstructorParameter::class @@ -113,7 +117,7 @@ public function testFactoryResolvesTypeHintsForServicesToWellKnownServiceNames() $this->container->has('ValidatorManager')->willReturn(true); $this->container->get('ValidatorManager')->willReturn($validators); - $factory = new LazyControllerAbstractFactory(); + $factory = new LazyControllerAbstractFactory(); $controller = $factory( $this->container->reveal(), TestAsset\ControllerAcceptingWellKnownServicesAsConstructorParameters::class @@ -139,7 +143,7 @@ public function testFactoryCanSupplyAMixOfParameterTypes() $this->container->has('config')->willReturn(true); $this->container->get('config')->willReturn($config); - $factory = new LazyControllerAbstractFactory(); + $factory = new LazyControllerAbstractFactory(); $controller = $factory($this->container->reveal(), TestAsset\ControllerWithMixedConstructorParameters::class); $this->assertInstanceOf(TestAsset\ControllerWithMixedConstructorParameters::class, $controller); diff --git a/test/Controller/MiddlewareControllerTest.php b/test/Controller/MiddlewareControllerTest.php index 2cb94212d..e8e389a2a 100644 --- a/test/Controller/MiddlewareControllerTest.php +++ b/test/Controller/MiddlewareControllerTest.php @@ -1,14 +1,18 @@ createMock(ResponseInterface::class); - /* @var $dispatchListener callable|\PHPUnit_Framework_MockObject_MockObject */ - $dispatchListener = $this->getMockBuilder(\stdClass::class)->setMethods(['__invoke'])->getMock(); + $request = new Request(); + $response = new Response(); + $result = $this->createMock(ResponseInterface::class); + /** @var callable|PHPUnit_Framework_MockObject_MockObject $dispatchListener */ + $dispatchListener = $this->getMockBuilder(stdClass::class)->setMethods(['__invoke'])->getMock(); $this->eventManager->attach(MvcEvent::EVENT_DISPATCH, $dispatchListener, 100); $this->eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function () { @@ -115,11 +109,11 @@ public function testWillDispatchARequestAndResponseWithAGivenPipe() public function testWillRefuseDispatchingInvalidRequestTypes() { - /* @var $request RequestInterface */ - $request = $this->createMock(RequestInterface::class); - $response = new Response(); - /* @var $dispatchListener callable|\PHPUnit_Framework_MockObject_MockObject */ - $dispatchListener = $this->getMockBuilder(\stdClass::class)->setMethods(['__invoke'])->getMock(); + /** @var RequestInterface $request */ + $request = $this->createMock(RequestInterface::class); + $response = new Response(); + /** @var callable|PHPUnit_Framework_MockObject_MockObject $dispatchListener */ + $dispatchListener = $this->getMockBuilder(stdClass::class)->setMethods(['__invoke'])->getMock(); $this->eventManager->attach(MvcEvent::EVENT_DISPATCH, $dispatchListener, 100); diff --git a/test/Controller/Plugin/AcceptableViewModelSelectorTest.php b/test/Controller/Plugin/AcceptableViewModelSelectorTest.php index a417fc126..d2b8ec168 100644 --- a/test/Controller/Plugin/AcceptableViewModelSelectorTest.php +++ b/test/Controller/Plugin/AcceptableViewModelSelectorTest.php @@ -1,19 +1,20 @@ [ 'application/json', - 'application/javascript' + 'application/javascript', ], Model\FeedModel::class => [ 'application/rss+xml', - 'application/atom+xml' + 'application/atom+xml', ], - Model\ViewModel::class => '*/*' + Model\ViewModel::class => '*/*', ]; - $header = Accept::fromString( + $header = Accept::fromString( 'Accept: text/plain; q=0.5, text/html, text/xml; q=0, text/x-dvi; q=0.8, text/x-c' ); $this->request->getHeaders()->addHeader($header); - $plugin = $this->plugin; + $plugin = $this->plugin; $plugin->setDefaultViewModelName(Model\FeedModel::class); - $result = $plugin($arr); + $result = $plugin($arr); $this->assertInstanceOf(Model\ViewModel::class, $result); $this->assertNotInstanceOf(Model\FeedModel::class, $result); // Ensure the default wasn't selected @@ -65,18 +66,18 @@ public function testDefaultViewModelName() $arr = [ Model\JsonModel::class => [ 'application/json', - 'application/javascript' + 'application/javascript', ], Model\FeedModel::class => [ 'application/rss+xml', - 'application/atom+xml' + 'application/atom+xml', ], ]; - $header = Accept::fromString('Accept: text/plain'); + $header = Accept::fromString('Accept: text/plain'); $this->request->getHeaders()->addHeader($header); - $plugin = $this->plugin; - $result = $plugin->getViewModelName($arr); + $plugin = $this->plugin; + $result = $plugin->getViewModelName($arr); $this->assertEquals(Model\ViewModel::class, $result); // Default Default View Model Name @@ -88,41 +89,40 @@ public function testDefaultViewModelName() public function testSelectsViewModelBasedOnAcceptHeaderWhenInvokedAsFunctor() { $arr = [ - Model\JsonModel::class => [ - 'application/json', - 'application/javascript' - ], - Model\FeedModel::class => [ - 'application/rss+xml', - 'application/atom+xml' - ], - Model\ViewModel::class => '*/*' + Model\JsonModel::class => [ + 'application/json', + 'application/javascript', + ], + Model\FeedModel::class => [ + 'application/rss+xml', + 'application/atom+xml', + ], + Model\ViewModel::class => '*/*', ]; - $plugin = $this->plugin; - $header = Accept::fromString('Accept: application/rss+xml; version=0.2'); + $plugin = $this->plugin; + $header = Accept::fromString('Accept: application/rss+xml; version=0.2'); $this->request->getHeaders()->addHeader($header); $result = $plugin($arr); $this->assertInstanceOf(Model\FeedModel::class, $result); } - public function testInvokeWithoutDefaultsReturnsNullWhenNoMatchesOccur() { $arr = [ - Model\JsonModel::class => [ - 'application/json', - 'application/javascript' - ], - Model\FeedModel::class => [ - 'application/rss+xml', - 'application/atom+xml' - ], + Model\JsonModel::class => [ + 'application/json', + 'application/javascript', + ], + Model\FeedModel::class => [ + 'application/rss+xml', + 'application/atom+xml', + ], ]; - $plugin = $this->plugin; - $header = Accept::fromString('Accept: text/html; version=0.2'); + $plugin = $this->plugin; + $header = Accept::fromString('Accept: text/html; version=0.2'); $this->request->getHeaders()->addHeader($header); $result = $plugin($arr, false); @@ -131,12 +131,12 @@ public function testInvokeWithoutDefaultsReturnsNullWhenNoMatchesOccur() public function testInvokeReturnsFieldValuePartOnMatchWhenReferenceProvided() { - $plugin = $this->plugin; - $header = Accept::fromString('Accept: text/html; version=0.2'); + $plugin = $this->plugin; + $header = Accept::fromString('Accept: text/html; version=0.2'); $this->request->getHeaders()->addHeader($header); - $ref = null; - $result = $plugin([ Model\ViewModel::class => '*/*'], false, $ref); + $ref = null; + $result = $plugin([Model\ViewModel::class => '*/*'], false, $ref); $this->assertInstanceOf(Model\ViewModel::class, $result); $this->assertNotInstanceOf(Model\JsonModel::class, $result); $this->assertNotInstanceOf(Model\FeedModel::class, $result); @@ -146,24 +146,24 @@ public function testInvokeReturnsFieldValuePartOnMatchWhenReferenceProvided() public function testGetViewModelNameWithoutDefaults() { $arr = [ - Model\JsonModel::class => [ - 'application/json', - 'application/javascript' - ], - Model\FeedModel::class => [ - 'application/rss+xml', - 'application/atom+xml' - ], + Model\JsonModel::class => [ + 'application/json', + 'application/javascript', + ], + Model\FeedModel::class => [ + 'application/rss+xml', + 'application/atom+xml', + ], ]; - $plugin = $this->plugin; - $header = Accept::fromString('Accept: text/html; version=0.2'); + $plugin = $this->plugin; + $header = Accept::fromString('Accept: text/html; version=0.2'); $this->request->getHeaders()->addHeader($header); $result = $plugin->getViewModelName($arr, false); $this->assertNull($result); - $ref = null; + $ref = null; $result = $plugin->getViewModelName([Model\ViewModel::class => '*/*'], false, $ref); $this->assertEquals(Model\ViewModel::class, $result); $this->assertInstanceOf(AcceptFieldValuePart::class, $ref); @@ -171,8 +171,8 @@ public function testGetViewModelNameWithoutDefaults() public function testMatch() { - $plugin = $this->plugin; - $header = Accept::fromString('Accept: text/html; version=0.2'); + $plugin = $this->plugin; + $header = Accept::fromString('Accept: text/html; version=0.2'); $this->request->getHeaders()->addHeader($header); $arr = [Model\ViewModel::class => '*/*']; @@ -185,8 +185,8 @@ public function testMatch() public function testInvalidModel() { - $arr = ['DoesNotExist' => 'text/xml']; - $header = Accept::fromString('Accept: */*'); + $arr = ['DoesNotExist' => 'text/xml']; + $header = Accept::fromString('Accept: */*'); $this->request->getHeaders()->addHeader($header); $this->expectException(InvalidArgumentException::class); diff --git a/test/Controller/Plugin/CreateHttpNotFoundModelTest.php b/test/Controller/Plugin/CreateHttpNotFoundModelTest.php index 953f9166d..7024df8e4 100644 --- a/test/Controller/Plugin/CreateHttpNotFoundModelTest.php +++ b/test/Controller/Plugin/CreateHttpNotFoundModelTest.php @@ -1,10 +1,12 @@ __invoke($response); + $model = $plugin->__invoke($response); $this->assertInstanceOf(ViewModel::class, $model); $this->assertSame('Page not found', $model->getVariable('content')); diff --git a/test/Controller/Plugin/ForwardTest.php b/test/Controller/Plugin/ForwardTest.php index ed96ee4e0..3cc5768ef 100644 --- a/test/Controller/Plugin/ForwardTest.php +++ b/test/Controller/Plugin/ForwardTest.php @@ -1,14 +1,15 @@ createEventManager(new SharedEventManager()); + $eventManager = $this->createEventManager(new SharedEventManager()); $mockApplication = $this->createMock(ApplicationInterface::class); $mockApplication->expects($this->any())->method('getEventManager')->will($this->returnValue($eventManager)); - $event = new MvcEvent(); + $event = new MvcEvent(); $event->setApplication($mockApplication); $event->setRequest(new Request()); $event->setResponse(new Response()); @@ -70,33 +60,35 @@ public function setUp() : void $routeMatch->setMatchedRouteName('some-route'); $event->setRouteMatch($routeMatch); - $config = new Config([ - 'aliases' => [ + $config = new Config([ + 'aliases' => [ 'ControllerLoader' => 'ControllerManager', ], 'factories' => [ - 'ControllerManager' => function ($services, $name) { + 'ControllerManager' => function ($services, $name) { $plugins = $services->get('ControllerPluginManager'); - return new ControllerManager($services, ['factories' => [ - 'forward' => function ($services) use ($plugins) { - $controller = new ForwardController(); - $controller->setPluginManager($plugins); - return $controller; - }, - ]]); + return new ControllerManager($services, [ + 'factories' => [ + 'forward' => function ($services) use ($plugins) { + $controller = new ForwardController(); + $controller->setPluginManager($plugins); + return $controller; + }, + ], + ]); }, 'ControllerPluginManager' => function ($services, $name) { return new PluginManager($services); }, - 'EventManager' => function ($services, $name) { + 'EventManager' => function ($services, $name) { return $this->createEventManager($services->get('SharedEventManager')); }, - 'SharedEventManager' => function ($services, $name) { + 'SharedEventManager' => function ($services, $name) { return new SharedEventManager(); }, ], - 'shared' => [ + 'shared' => [ 'EventManager' => false, ], ]); @@ -105,7 +97,7 @@ public function setUp() : void $this->controllers = $services->get('ControllerManager'); - $plugins = $services->get('ControllerPluginManager'); + $plugins = $services->get('ControllerPluginManager'); $this->controller = new SampleController(); $this->controller->setEvent($event); $this->controller->setPluginManager($plugins); @@ -114,7 +106,6 @@ public function setUp() : void } /** - * @param SharedEventManager * @return EventManager */ protected function createEventManager(SharedEventManagerInterface $sharedManager) @@ -136,13 +127,13 @@ public function testPluginWithoutControllerLocatorRaisesServiceNotCreatedExcepti { $controller = new SampleController(); $this->expectException(ServiceNotCreatedException::class); - $plugin = $controller->plugin('forward'); + $plugin = $controller->plugin('forward'); } public function testDispatchRaisesDomainExceptionIfDiscoveredControllerIsNotDispatchable() { $this->controllers->setFactory('bogus', function () { - return new stdClass; + return new stdClass(); }); $plugin = new ForwardPlugin($this->controllers); $plugin->setController($this->controller); @@ -156,39 +147,41 @@ public function testDispatchRaisesDomainExceptionIfCircular() { $event = $this->controller->getEvent(); - $config = new Config([ - 'aliases' => [ + $config = new Config([ + 'aliases' => [ 'ControllerLoader' => 'ControllerManager', ], 'factories' => [ - 'ControllerManager' => function ($services) use ($event) { + 'ControllerManager' => function ($services) use ($event) { $plugins = $services->get('ControllerPluginManager'); - return new ControllerManager($services, ['factories' => [ - 'forward' => function ($services) use ($plugins) { - $controller = new ForwardController(); - $controller->setPluginManager($plugins); - return $controller; - }, - 'sample' => function ($services) use ($event, $plugins) { - $controller = new SampleController(); - $controller->setEvent($event); - $controller->setPluginManager($plugins); - return $controller; - }, - ]]); + return new ControllerManager($services, [ + 'factories' => [ + 'forward' => function ($services) use ($plugins) { + $controller = new ForwardController(); + $controller->setPluginManager($plugins); + return $controller; + }, + 'sample' => function ($services) use ($event, $plugins) { + $controller = new SampleController(); + $controller->setEvent($event); + $controller->setPluginManager($plugins); + return $controller; + }, + ], + ]); }, 'ControllerPluginManager' => function ($services) { return new PluginManager($services); }, - 'EventManager' => function ($services, $name) { + 'EventManager' => function ($services, $name) { return $this->createEventManager($services->get('SharedEventManager')); }, - 'SharedEventManager' => function ($services, $name) { + 'SharedEventManager' => function ($services, $name) { return new SharedEventManager(); }, ], - 'shared' => [ + 'shared' => [ 'EventManager' => false, ], ]); @@ -217,15 +210,15 @@ public function testPluginDispatchsRequestedControllerWhenFound() */ public function testNonArrayListenerDoesNotRaiseErrorWhenPluginDispatchsRequestedController() { - $services = $this->services; - $events = $services->get('EventManager'); + $services = $this->services; + $events = $services->get('EventManager'); $sharedEvents = $this->createMock(SharedEventManagerInterface::class); // @codingStandardsIgnoreStart $sharedEvents->expects($this->any())->method('getListeners')->will($this->returnValue([ function ($e) {} ])); // @codingStandardsIgnoreEnd - $events = $this->createEventManager($sharedEvents); + $events = $this->createEventManager($sharedEvents); $application = $this->createMock(ApplicationInterface::class); $application->expects($this->any())->method('getEventManager')->will($this->returnValue($events)); $event = $this->controller->getEvent(); @@ -241,13 +234,13 @@ public function testProblemListenersAreDetachedAndReattachedWhenPluginDispatches $services = $this->services; $events = $services->get('EventManager'); - $myCallback = [new ListenerStub(),'myCallback']; + $myCallback = [new ListenerStub(), 'myCallback']; $sharedEvents = $this->createMock(SharedEventManagerInterface::class); - $sharedEvents->expects($this->once())->method('detach')->with($myCallback, 'Zend\Stdlib\DispatchableInterface'); + $sharedEvents->expects($this->once())->method('detach')->with($myCallback, DispatchableInterface::class); $sharedEvents ->expects($this->once()) ->method('attach') - ->with('Zend\Stdlib\DispatchableInterface', MvcEvent::EVENT_DISPATCH, $myCallback, -50); + ->with(DispatchableInterface::class, MvcEvent::EVENT_DISPATCH, $myCallback, -50); $sharedEvents->expects($this->any())->method('getListeners')->will($this->returnValue([-50 => [$myCallback]])); $events = $this->createEventManager($sharedEvents); @@ -256,11 +249,13 @@ public function testProblemListenersAreDetachedAndReattachedWhenPluginDispatches $event = $this->controller->getEvent(); $event->setApplication($application); - $this->plugin->setListenersToDetach([[ - 'id' => 'Zend\Stdlib\DispatchableInterface', - 'event' => MvcEvent::EVENT_DISPATCH, - 'class' => 'ZendTest\Mvc\Controller\Plugin\TestAsset\ListenerStub', - ]]); + $this->plugin->setListenersToDetach([ + [ + 'id' => DispatchableInterface::class, + 'event' => MvcEvent::EVENT_DISPATCH, + 'class' => ListenerStub::class, + ], + ]); $result = $this->plugin->dispatch('forward'); } @@ -270,13 +265,13 @@ public function testInvokableProblemListenersAreDetachedAndReattachedWhenPluginD $services = $this->services; $events = $services->get('EventManager'); - $myCallback = new ListenerStub(); + $myCallback = new ListenerStub(); $sharedEvents = $this->createMock(SharedEventManagerInterface::class); - $sharedEvents->expects($this->once())->method('detach')->with($myCallback, 'Zend\Stdlib\DispatchableInterface'); + $sharedEvents->expects($this->once())->method('detach')->with($myCallback, DispatchableInterface::class); $sharedEvents ->expects($this->once()) ->method('attach') - ->with('Zend\Stdlib\DispatchableInterface', MvcEvent::EVENT_DISPATCH, $myCallback, -50); + ->with(DispatchableInterface::class, MvcEvent::EVENT_DISPATCH, $myCallback, -50); $sharedEvents->expects($this->any())->method('getListeners')->will($this->returnValue([-50 => [$myCallback]])); $events = $this->createEventManager($sharedEvents); @@ -285,11 +280,13 @@ public function testInvokableProblemListenersAreDetachedAndReattachedWhenPluginD $event = $this->controller->getEvent(); $event->setApplication($application); - $this->plugin->setListenersToDetach([[ - 'id' => 'Zend\Stdlib\DispatchableInterface', - 'event' => MvcEvent::EVENT_DISPATCH, - 'class' => 'ZendTest\Mvc\Controller\Plugin\TestAsset\ListenerStub', - ]]); + $this->plugin->setListenersToDetach([ + [ + 'id' => DispatchableInterface::class, + 'event' => MvcEvent::EVENT_DISPATCH, + 'class' => ListenerStub::class, + ], + ]); $result = $this->plugin->dispatch('forward'); } @@ -312,13 +309,13 @@ public function testRouteMatchObjectRemainsSameFollowingForwardDispatch() $routeMatch = $this->controller->getEvent()->getRouteMatch(); $matchParams = $routeMatch->getParams(); $matchMatchedRouteName = $routeMatch->getMatchedRouteName(); - $result = $this->plugin->dispatch('forward', [ + $result = $this->plugin->dispatch('forward', [ 'action' => 'test-matches', 'param1' => 'foobar', ]); - $testMatch = $this->controller->getEvent()->getRouteMatch(); - $testParams = $testMatch->getParams(); - $testMatchedRouteName = $testMatch->getMatchedRouteName(); + $testMatch = $this->controller->getEvent()->getRouteMatch(); + $testParams = $testMatch->getParams(); + $testMatchedRouteName = $testMatch->getMatchedRouteName(); $this->assertSame($routeMatch, $testMatch); $this->assertEquals($matchParams, $testParams); diff --git a/test/Controller/Plugin/LayoutTest.php b/test/Controller/Plugin/LayoutTest.php index d780c21c7..98a08408e 100644 --- a/test/Controller/Plugin/LayoutTest.php +++ b/test/Controller/Plugin/LayoutTest.php @@ -1,18 +1,20 @@ request = new Request; - $event = new MvcEvent; + $this->request = new Request(); + $event = new MvcEvent(); $event->setRequest($this->request); $event->setResponse(new Response()); @@ -182,7 +188,7 @@ public function testFromHeaderReturnsExpectedValue() public function testFromHeaderReturnsAllIfEmpty() { - $header = new GenericHeader('X-TEST', 'test'); + $header = new GenericHeader('X-TEST', 'test'); $header2 = new GenericHeader('OTHER-TEST', 'value:12345'); $this->request->getHeaders()->addHeader($header); diff --git a/test/Controller/Plugin/RedirectTest.php b/test/Controller/Plugin/RedirectTest.php index cecc5f84c..78da19ab8 100644 --- a/test/Controller/Plugin/RedirectTest.php +++ b/test/Controller/Plugin/RedirectTest.php @@ -1,10 +1,12 @@ response = new Response(); - $router = new SimpleRouteStack; + $router = new SimpleRouteStack(); $router->addRoute('home', LiteralRoute::factory([ 'route' => '/', 'defaults' => [ @@ -53,7 +55,7 @@ public function testPluginCanRedirectToRouteWhenProperlyConfigured() { $response = $this->plugin->toRoute('home'); $this->assertTrue($response->isRedirect()); - $headers = $response->getHeaders(); + $headers = $response->getHeaders(); $location = $headers->get('Location'); $this->assertEquals('/', $location->getFieldValue()); } @@ -62,7 +64,7 @@ public function testPluginCanRedirectToUrlWhenProperlyConfigured() { $response = $this->plugin->toUrl('/foo'); $this->assertTrue($response->isRedirect()); - $headers = $response->getHeaders(); + $headers = $response->getHeaders(); $location = $headers->get('Location'); $this->assertEquals('/foo', $location->getFieldValue()); } @@ -139,7 +141,7 @@ public function testCanReuseMatchedParameters() $routeMatch->setMatchedRouteName('replace'); $this->controller->getEvent()->setRouteMatch($routeMatch); $response = $this->plugin->toRoute('replace', ['action' => 'bar'], [], true); - $headers = $response->getHeaders(); + $headers = $response->getHeaders(); $location = $headers->get('Location'); $this->assertEquals('/foo/bar', $location->getFieldValue()); } @@ -158,7 +160,7 @@ public function testCanPassBooleanValueForThirdArgumentToAllowReusingRouteMatche $routeMatch->setMatchedRouteName('replace'); $this->controller->getEvent()->setRouteMatch($routeMatch); $response = $this->plugin->toRoute('replace', ['action' => 'bar'], true); - $headers = $response->getHeaders(); + $headers = $response->getHeaders(); $location = $headers->get('Location'); $this->assertEquals('/foo/bar', $location->getFieldValue()); } @@ -168,7 +170,7 @@ public function testPluginCanRefreshToRouteWhenProperlyConfigured() $this->event->setRouteMatch($this->routeMatch); $response = $this->plugin->refresh(); $this->assertTrue($response->isRedirect()); - $headers = $response->getHeaders(); + $headers = $response->getHeaders(); $location = $headers->get('Location'); $this->assertEquals('/', $location->getFieldValue()); } @@ -178,7 +180,7 @@ public function testPluginCanRedirectToRouteWithNullWhenProperlyConfigured() $this->event->setRouteMatch($this->routeMatch); $response = $this->plugin->toRoute(); $this->assertTrue($response->isRedirect()); - $headers = $response->getHeaders(); + $headers = $response->getHeaders(); $location = $headers->get('Location'); $this->assertEquals('/', $location->getFieldValue()); } diff --git a/test/Controller/Plugin/TestAsset/ListenerStub.php b/test/Controller/Plugin/TestAsset/ListenerStub.php index cf0455d38..0d182ea4e 100644 --- a/test/Controller/Plugin/TestAsset/ListenerStub.php +++ b/test/Controller/Plugin/TestAsset/ListenerStub.php @@ -1,10 +1,12 @@ addRoute('home', LiteralRoute::factory([ 'route' => '/', 'defaults' => [ @@ -34,10 +37,10 @@ public function setUp() : void ], ])); $router->addRoute('default', [ - 'type' => Segment::class, + 'type' => Segment::class, 'options' => [ 'route' => '/:controller[/:action]', - ] + ], ]); $this->router = $router; @@ -58,7 +61,7 @@ public function testPluginCanGenerateUrlWhenProperlyConfigured() public function testModel() { - $it = new \ArrayIterator(['controller' => 'ctrl', 'action' => 'act']); + $it = new ArrayIterator(['controller' => 'ctrl', 'action' => 'act']); $url = $this->plugin->fromRoute('default', $it); $this->assertEquals('/ctrl/act', $url); @@ -151,42 +154,39 @@ public function testCanPassBooleanValueForThirdArgumentToAllowReusingRouteMatche $this->assertEquals('/foo/bar', $url); } - /** - * - */ public function testRemovesModuleRouteListenerParamsWhenReusingMatchedParameters() { - $router = new TreeRouteStack; + $router = new TreeRouteStack(); $router->addRoute('default', [ - 'type' => Segment::class, - 'options' => [ + 'type' => Segment::class, + 'options' => [ 'route' => '/:controller/:action', 'defaults' => [ ModuleRouteListener::MODULE_NAMESPACE => 'ZendTest\Mvc\Controller\TestAsset', - 'controller' => 'SampleController', - 'action' => 'Dash' - ] + 'controller' => 'SampleController', + 'action' => 'Dash', + ], ], 'child_routes' => [ 'wildcard' => [ 'type' => Wildcard::class, 'options' => [ 'param_delimiter' => '=', - 'key_value_delimiter' => '%' - ] - ] - ] + 'key_value_delimiter' => '%', + ], + ], + ], ]); $routeMatch = new RouteMatch([ ModuleRouteListener::MODULE_NAMESPACE => 'ZendTest\Mvc\Controller\TestAsset', - 'controller' => 'Rainbow' + 'controller' => 'Rainbow', ]); $routeMatch->setMatchedRouteName('default/wildcard'); $event = new MvcEvent(); $event->setRouter($router) - ->setRouteMatch($routeMatch); + ->setRouteMatch($routeMatch); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->onRoute($event); diff --git a/test/Controller/PluginManagerTest.php b/test/Controller/PluginManagerTest.php index 596589602..40e6199e1 100644 --- a/test/Controller/PluginManagerTest.php +++ b/test/Controller/PluginManagerTest.php @@ -1,24 +1,26 @@ ['samplePlugin' => SamplePlugin::class], 'factories' => [SamplePlugin::class => InvokableFactory::class], @@ -31,7 +33,7 @@ public function testPluginManagerInjectsControllerInPlugin() public function testPluginManagerInjectsControllerForExistingPlugin() { - $controller1 = new SampleController; + $controller1 = new SampleController(); $pluginManager = new PluginManager(new ServiceManager(), [ 'aliases' => ['samplePlugin' => SamplePlugin::class], 'factories' => [SamplePlugin::class => InvokableFactory::class], @@ -41,7 +43,7 @@ public function testPluginManagerInjectsControllerForExistingPlugin() // Plugin manager registers now instance of SamplePlugin $pluginManager->get('samplePlugin'); - $controller2 = new SampleController; + $controller2 = new SampleController(); $pluginManager->setController($controller2); $plugin = $pluginManager->get('samplePlugin'); @@ -54,7 +56,7 @@ public function testGetWithConstructor() 'aliases' => ['samplePlugin' => Plugin\TestAsset\SamplePluginWithConstructor::class], 'factories' => [Plugin\TestAsset\SamplePluginWithConstructor::class => InvokableFactory::class], ]); - $plugin = $pluginManager->get('samplePlugin'); + $plugin = $pluginManager->get('samplePlugin'); $this->assertEquals($plugin->getBar(), 'baz'); } @@ -64,7 +66,7 @@ public function testGetWithConstructorAndOptions() 'aliases' => ['samplePlugin' => Plugin\TestAsset\SamplePluginWithConstructor::class], 'factories' => [Plugin\TestAsset\SamplePluginWithConstructor::class => InvokableFactory::class], ]); - $plugin = $pluginManager->get('samplePlugin', ['foo']); + $plugin = $pluginManager->get('samplePlugin', ['foo']); $this->assertEquals($plugin->getBar(), ['foo']); } @@ -73,9 +75,9 @@ public function testCanCreateByFactory() $pluginManager = new PluginManager(new ServiceManager(), [ 'factories' => [ 'samplePlugin' => Plugin\TestAsset\SamplePluginFactory::class, - ] + ], ]); - $plugin = $pluginManager->get('samplePlugin'); + $plugin = $pluginManager->get('samplePlugin'); $this->assertInstanceOf(SamplePlugin::class, $plugin); } @@ -86,7 +88,7 @@ public function testCanCreateByFactoryWithConstrutor() 'samplePlugin' => Plugin\TestAsset\SamplePluginWithConstructorFactory::class, ], ]); - $plugin = $pluginManager->get('samplePlugin', ['foo']); + $plugin = $pluginManager->get('samplePlugin', ['foo']); $this->assertInstanceOf(Plugin\TestAsset\SamplePluginWithConstructor::class, $plugin); $this->assertEquals($plugin->getBar(), ['foo']); } diff --git a/test/Controller/RestfulControllerTest.php b/test/Controller/RestfulControllerTest.php index 9b6275c02..7fda0a8c7 100644 --- a/test/Controller/RestfulControllerTest.php +++ b/test/Controller/RestfulControllerTest.php @@ -1,14 +1,15 @@ request = new Request(); $this->response = new Response(); $this->routeMatch = new RouteMatch(['controller' => 'controller-restful']); - $this->event = new MvcEvent; + $this->event = new MvcEvent(); $this->event->setRouteMatch($this->routeMatch); $this->controller->setEvent($this->event); $this->emptyController->setEvent($this->event); @@ -53,7 +62,6 @@ public function setUp() : void } /** - * @param SharedEventManager * @return EventManager */ protected function createEventManager(SharedEventManagerInterface $sharedManager) @@ -63,13 +71,13 @@ protected function createEventManager(SharedEventManagerInterface $sharedManager public function testDispatchInvokesListWhenNoActionPresentAndNoIdentifierOnGet() { - $entities = [ - new stdClass, - new stdClass, - new stdClass, + $entities = [ + new stdClass(), + new stdClass(), + new stdClass(), ]; $this->controller->entities = $entities; - $result = $this->controller->dispatch($this->request, $this->response); + $result = $this->controller->dispatch($this->request, $this->response); $this->assertArrayHasKey('entities', $result); $this->assertEquals($entities, $result['entities']); $this->assertEquals('getList', $this->routeMatch->getParam('action')); @@ -77,7 +85,7 @@ public function testDispatchInvokesListWhenNoActionPresentAndNoIdentifierOnGet() public function testDispatchInvokesGetMethodWhenNoActionPresentAndIdentifierPresentOnGet() { - $entity = new stdClass; + $entity = new stdClass(); $this->controller->entity = $entity; $this->routeMatch->setParam('id', 1); $result = $this->controller->dispatch($this->request, $this->response); @@ -100,7 +108,7 @@ public function testDispatchInvokesCreateMethodWhenNoActionPresentAndPostInvoked public function testCanReceiveStringAsRequestContent() { - $string = "any content"; + $string = 'any content'; $this->request->setMethod('PUT'); $this->request->setContent($string); $this->routeMatch->setParam('id', $id = 1); @@ -119,7 +127,7 @@ public function testDispatchInvokesUpdateMethodWhenNoActionPresentAndPutInvokedW $entity = ['name' => __FUNCTION__]; $string = http_build_query($entity); $this->request->setMethod('PUT') - ->setContent($string); + ->setContent($string); $this->routeMatch->setParam('id', 1); $result = $this->controller->dispatch($this->request, $this->response); $this->assertArrayHasKey('entity', $result); @@ -138,9 +146,9 @@ public function testDispatchInvokesReplaceListMethodWhenNoActionPresentAndPutInv ['id' => uniqid(), 'name' => __FUNCTION__], ['id' => uniqid(), 'name' => __FUNCTION__], ]; - $string = http_build_query($entities); + $string = http_build_query($entities); $this->request->setMethod('PUT') - ->setContent($string); + ->setContent($string); $result = $this->controller->dispatch($this->request, $this->response); $this->assertEquals($entities, $result); $this->assertEquals('replaceList', $this->routeMatch->getParam('action')); @@ -153,9 +161,9 @@ public function testDispatchInvokesPatchListMethodWhenNoActionPresentAndPatchInv ['id' => uniqid(), 'name' => __FUNCTION__], ['id' => uniqid(), 'name' => __FUNCTION__], ]; - $string = http_build_query($entities); + $string = http_build_query($entities); $this->request->setMethod('PATCH') - ->setContent($string); + ->setContent($string); $result = $this->controller->dispatch($this->request, $this->response); $this->assertEquals($entities, $result); $this->assertEquals('patchList', $this->routeMatch->getParam('action')); @@ -163,7 +171,7 @@ public function testDispatchInvokesPatchListMethodWhenNoActionPresentAndPatchInv public function testDispatchInvokesDeleteMethodWhenNoActionPresentAndDeleteInvokedWithIdentifier() { - $entity = ['id' => 1, 'name' => __FUNCTION__]; + $entity = ['id' => 1, 'name' => __FUNCTION__]; $this->controller->entity = $entity; $this->request->setMethod('DELETE'); $this->routeMatch->setParam('id', 1); @@ -185,7 +193,7 @@ public function testDispatchInvokesDeleteListMethodWhenNoActionPresentAndDeleteI $string = http_build_query($entities); $this->request->setMethod('DELETE') - ->setContent($string); + ->setContent($string); $result = $this->controller->dispatch($this->request, $this->response); $this->assertEmpty($this->controller->entity); $this->assertEquals(204, $result->getStatusCode()); @@ -201,24 +209,24 @@ public function testDispatchInvokesOptionsMethodWhenNoActionPresentAndOptionsInv $this->assertEquals('options', $this->routeMatch->getParam('action')); $headers = $result->getHeaders(); $this->assertTrue($headers->has('Allow')); - $allow = $headers->get('Allow'); + $allow = $headers->get('Allow'); $expected = explode(', ', 'GET, POST, PUT, DELETE, PATCH, HEAD, TRACE'); sort($expected); - $test = explode(', ', $allow->getFieldValue()); + $test = explode(', ', $allow->getFieldValue()); sort($test); $this->assertEquals($expected, $test); } public function testDispatchInvokesPatchMethodWhenNoActionPresentAndPatchInvokedWithIdentifier() { - $entity = new stdClass; - $entity->name = 'foo'; - $entity->type = 'standard'; + $entity = new stdClass(); + $entity->name = 'foo'; + $entity->type = 'standard'; $this->controller->entity = $entity; - $entity = ['name' => __FUNCTION__]; - $string = http_build_query($entity); + $entity = ['name' => __FUNCTION__]; + $string = http_build_query($entity); $this->request->setMethod('PATCH') - ->setContent($string); + ->setContent($string); $this->routeMatch->setParam('id', 1); $result = $this->controller->dispatch($this->request, $this->response); $this->assertArrayHasKey('entity', $result); @@ -252,10 +260,10 @@ public function testOnDispatchHonorsStatusCodeWithHeadMethod() public function testDispatchInvokesHeadMethodWhenNoActionPresentAndHeadInvokedWithoutIdentifier() { - $entities = [ - new stdClass, - new stdClass, - new stdClass, + $entities = [ + new stdClass(), + new stdClass(), + new stdClass(), ]; $this->controller->entities = $entities; $this->request->setMethod('HEAD'); @@ -268,7 +276,7 @@ public function testDispatchInvokesHeadMethodWhenNoActionPresentAndHeadInvokedWi public function testDispatchInvokesHeadMethodWhenNoActionPresentAndHeadInvokedWithIdentifier() { - $entity = new stdClass; + $entity = new stdClass(); $this->controller->entity = $entity; $this->routeMatch->setParam('id', 1); $this->request->setMethod('HEAD'); @@ -280,7 +288,7 @@ public function testDispatchInvokesHeadMethodWhenNoActionPresentAndHeadInvokedWi $headers = $this->controller->getResponse()->getHeaders(); $this->assertTrue($headers->has('X-ZF2-Id')); - $header = $headers->get('X-ZF2-Id'); + $header = $headers->get('X-ZF2-Id'); $this->assertEquals(1, $header->getFieldValue()); } @@ -426,9 +434,9 @@ public function testParsingDataAsJsonWillReturnAsArray() public function matchingContentTypes() { return [ - 'exact-first' => ['application/hal+json'], - 'exact-second' => ['application/json'], - 'with-charset' => ['application/json; charset=utf-8'], + 'exact-first' => ['application/hal+json'], + 'exact-second' => ['application/json'], + 'with-charset' => ['application/json; charset=utf-8'], 'with-whitespace' => ['application/json '], ]; } @@ -449,7 +457,7 @@ public function nonMatchingContentTypes() { return [ 'specific-type' => ['application/xml'], - 'generic-type' => ['text/json'], + 'generic-type' => ['text/json'], ]; } @@ -475,7 +483,7 @@ public function testDispatchWithUnrecognizedMethodReturns405Response() public function testDispatchInvokesGetMethodWhenNoActionPresentAndZeroIdentifierPresentOnGet() { - $entity = new stdClass; + $entity = new stdClass(); $this->controller->entity = $entity; $this->routeMatch->setParam('id', 0); $result = $this->controller->dispatch($this->request, $this->response); @@ -497,7 +505,7 @@ public function testCanSetIdentifierName() public function testUsesConfiguredIdentifierNameToGetIdentifier() { - $r = new ReflectionObject($this->controller); + $r = new ReflectionObject($this->controller); $getIdentifier = $r->getMethod('getIdentifier'); $getIdentifier->setAccessible(true); @@ -538,25 +546,25 @@ public function testNotImplementedMethodSets504HttpCode($method, $content, array public function providerNotImplementedMethodSets504HttpCodeProvider() { return [ - ['DELETE', [], ['id' => 1]], // AbstractRestfulController::delete() - ['DELETE', [], []], // AbstractRestfulController::deleteList() - ['GET', [], ['id' => 1]], // AbstractRestfulController::get() - ['GET', [], []], // AbstractRestfulController::getList() - ['HEAD', [], ['id' => 1]], // AbstractRestfulController::head() - ['HEAD', [], []], // AbstractRestfulController::head() - ['OPTIONS', [], []], // AbstractRestfulController::options() - ['PATCH', http_build_query(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::patch() - ['PATCH', json_encode(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::patch() - ['PATCH', http_build_query(['foo' => 1]), []], // AbstractRestfulController::patchList() - ['PATCH', json_encode(['foo' => 1]), []], // AbstractRestfulController::patchList() - ['POST', http_build_query(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update() - ['POST', json_encode(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update() - ['POST', http_build_query(['foo' => 1]), []], // AbstractRestfulController::create() - ['POST', json_encode(['foo' => 1]), []], // AbstractRestfulController::create() - ['PUT', http_build_query(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update() - ['PUT', json_encode(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update() - ['PUT', http_build_query(['foo' => 1]), []], // AbstractRestfulController::replaceList() - ['PUT', json_encode(['foo' => 1]), []], // AbstractRestfulController::replaceList() + ['DELETE', [], ['id' => 1]], // AbstractRestfulController::delete() + ['DELETE', [], []], // AbstractRestfulController::deleteList() + ['GET', [], ['id' => 1]], // AbstractRestfulController::get() + ['GET', [], []], // AbstractRestfulController::getList() + ['HEAD', [], ['id' => 1]], // AbstractRestfulController::head() + ['HEAD', [], []], // AbstractRestfulController::head() + ['OPTIONS', [], []], // AbstractRestfulController::options() + ['PATCH', http_build_query(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::patch() + ['PATCH', json_encode(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::patch() + ['PATCH', http_build_query(['foo' => 1]), []], // AbstractRestfulController::patchList() + ['PATCH', json_encode(['foo' => 1]), []], // AbstractRestfulController::patchList() + ['POST', http_build_query(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update() + ['POST', json_encode(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update() + ['POST', http_build_query(['foo' => 1]), []], // AbstractRestfulController::create() + ['POST', json_encode(['foo' => 1]), []], // AbstractRestfulController::create() + ['PUT', http_build_query(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update() + ['PUT', json_encode(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update() + ['PUT', http_build_query(['foo' => 1]), []], // AbstractRestfulController::replaceList() + ['PUT', json_encode(['foo' => 1]), []], // AbstractRestfulController::replaceList() ]; } } diff --git a/test/Controller/TestAsset/BadController.php b/test/Controller/TestAsset/BadController.php index 72d39f857..a574b2514 100644 --- a/test/Controller/TestAsset/BadController.php +++ b/test/Controller/TestAsset/BadController.php @@ -1,23 +1,27 @@ classmap[$name]; - return new $classname; + return new $classname(); } } diff --git a/test/Controller/TestAsset/ControllerWithEmptyConstructor.php b/test/Controller/TestAsset/ControllerWithEmptyConstructor.php index ec791c2a5..03c6512a7 100644 --- a/test/Controller/TestAsset/ControllerWithEmptyConstructor.php +++ b/test/Controller/TestAsset/ControllerWithEmptyConstructor.php @@ -1,10 +1,12 @@ sample = $sample; + $this->sample = $sample; $this->validators = $validators; - $this->config = $config; - $this->foo = $foo; - $this->options = $options; + $this->config = $config; + $this->foo = $foo; + $this->options = $options; } } diff --git a/test/Controller/TestAsset/ControllerWithScalarParameters.php b/test/Controller/TestAsset/ControllerWithScalarParameters.php index 7cde14553..15d65ae82 100644 --- a/test/Controller/TestAsset/ControllerWithScalarParameters.php +++ b/test/Controller/TestAsset/ControllerWithScalarParameters.php @@ -1,10 +1,12 @@ method = $method; return $this; } diff --git a/test/Controller/TestAsset/RestfulContentTypeTestController.php b/test/Controller/TestAsset/RestfulContentTypeTestController.php index 67c8767a9..372a9f6ba 100644 --- a/test/Controller/TestAsset/RestfulContentTypeTestController.php +++ b/test/Controller/TestAsset/RestfulContentTypeTestController.php @@ -1,10 +1,12 @@ $id, + 'id' => $id, 'data' => $data, ]; } diff --git a/test/Controller/TestAsset/RestfulMethodNotAllowedTestController.php b/test/Controller/TestAsset/RestfulMethodNotAllowedTestController.php index c65efd817..d720709ea 100644 --- a/test/Controller/TestAsset/RestfulMethodNotAllowedTestController.php +++ b/test/Controller/TestAsset/RestfulMethodNotAllowedTestController.php @@ -1,16 +1,16 @@ entity)) { foreach ($data as $row) { foreach ($this->entity as $index => $entity) { - if ($row['id'] == $entity['id']) { + if ($row['id'] === $entity['id']) { unset($this->entity[$index]); break; } @@ -107,7 +113,7 @@ public function head($id = null) /** * Return list of allowed HTTP methods * - * @return \Zend\Http\Response + * @return Response */ public function options() { @@ -120,7 +126,7 @@ public function options() /** * Patch (partial update) an entity * - * @param int $id + * @param int $id * @param array $data * @return array */ @@ -135,8 +141,8 @@ public function patch($id, $data) /** * Replace the entire resource collection * - * @param array|\Traversable $items - * @return array|\Traversable + * @param array|Traversable $items + * @return array|Traversable */ public function replaceList($items) { @@ -146,14 +152,14 @@ public function replaceList($items) /** * Modify an entire resource collection * - * @param array|\Traversable $items - * @return array|\Traversable + * @param array|Traversable $items + * @return array|Traversable */ public function patchList($items) { //This isn't great code to have in a test class, but I seems the simplest without BC breaks. if (isset($items['name']) - && $items['name'] == 'testDispatchViaPatchWithoutIdentifierReturns405ResponseIfPatchListThrowsException' + && $items['name'] === 'testDispatchViaPatchWithoutIdentifierReturns405ResponseIfPatchListThrowsException' ) { parent::patchList($items); } diff --git a/test/Controller/TestAsset/SampleController.php b/test/Controller/TestAsset/SampleController.php index 5fb42d06d..9668ac993 100644 --- a/test/Controller/TestAsset/SampleController.php +++ b/test/Controller/TestAsset/SampleController.php @@ -1,10 +1,12 @@ event; } - public function dispatch(Request $request, Response $response = null) + public function dispatch(Request $request, ?Response $response = null) { } } diff --git a/test/DispatchListenerTest.php b/test/DispatchListenerTest.php index 41da5d19f..c4f68c48d 100644 --- a/test/DispatchListenerTest.php +++ b/test/DispatchListenerTest.php @@ -1,13 +1,16 @@ [ - Controller\TestAsset\ControllerLoaderAbstractFactory::class, - ]]); - $listener = new DispatchListener($controllerManager); + $controllerManager = new ControllerManager(new ServiceManager(), [ + 'abstract_factories' => [ + Controller\TestAsset\ControllerLoaderAbstractFactory::class, + ], + ]); + $listener = new DispatchListener($controllerManager); $event = $this->createMvcEvent('path'); @@ -59,17 +66,19 @@ public function testControllerManagerUsingAbstractFactory() $return = $listener->onDispatch($event); - $this->assertEmpty($log, var_export($log, 1)); + $this->assertEmpty($log, var_export($log, true)); $this->assertSame($event->getResponse(), $return); $this->assertSame(200, $return->getStatusCode()); } public function testUnlocatableControllerViaAbstractFactory() { - $controllerManager = new ControllerManager(new ServiceManager(), ['abstract_factories' => [ - Controller\TestAsset\UnlocatableControllerLoaderAbstractFactory::class, - ]]); - $listener = new DispatchListener($controllerManager); + $controllerManager = new ControllerManager(new ServiceManager(), [ + 'abstract_factories' => [ + Controller\TestAsset\UnlocatableControllerLoaderAbstractFactory::class, + ], + ]); + $listener = new DispatchListener($controllerManager); $event = $this->createMvcEvent('path'); @@ -95,9 +104,11 @@ public function testWillNotDispatchWhenAnMvcEventResultIsAlreadySet($alreadySetR $event->setResult($alreadySetResult); - $listener = new DispatchListener(new ControllerManager(new ServiceManager(), ['abstract_factories' => [ - Controller\TestAsset\UnlocatableControllerLoaderAbstractFactory::class, - ]])); + $listener = new DispatchListener(new ControllerManager(new ServiceManager(), [ + 'abstract_factories' => [ + Controller\TestAsset\UnlocatableControllerLoaderAbstractFactory::class, + ], + ])); $event->getApplication()->getEventManager()->attach(MvcEvent::EVENT_DISPATCH_ERROR, function () { self::fail('No dispatch failures should be raised - dispatch should be skipped'); @@ -118,13 +129,13 @@ public function alreadySetMvcEventResultProvider() [true], [false], [[]], - [new \stdClass()], + [new stdClass()], [$this], [$this->createMock(ModelInterface::class)], [$this->createMock(ResponseInterface::class)], [$this->createMock(Response::class)], [['view model data' => 'as an array']], - [['foo' => new \stdClass()]], + [['foo' => new stdClass()]], ['a response string'], ]; } diff --git a/test/Exception/InvalidMiddlewareExceptionTest.php b/test/Exception/InvalidMiddlewareExceptionTest.php index 8311d7945..1ea66f201 100644 --- a/test/Exception/InvalidMiddlewareExceptionTest.php +++ b/test/Exception/InvalidMiddlewareExceptionTest.php @@ -1,21 +1,25 @@ assertInstanceOf(InvalidMiddlewareException::class, $exception); $this->assertSame('Cannot dispatch middleware ' . $middlewareName, $exception->getMessage()); diff --git a/test/Exception/ReachedFinalHandlerExceptionTest.php b/test/Exception/ReachedFinalHandlerExceptionTest.php index 8628ddd5c..b51622f5b 100644 --- a/test/Exception/ReachedFinalHandlerExceptionTest.php +++ b/test/Exception/ReachedFinalHandlerExceptionTest.php @@ -1,10 +1,12 @@ assertFalse($listener->isEnabled()); @@ -47,8 +47,8 @@ public function testAttachesToRouteEvent() { $eventManager = $this->createMock(EventManagerInterface::class); $eventManager->expects($this->atLeastOnce()) - ->method('attach') - ->with(MvcEvent::EVENT_ROUTE); + ->method('attach') + ->with(MvcEvent::EVENT_ROUTE); $this->listener->attach($eventManager); } @@ -59,7 +59,7 @@ public function testDoesntAttachIfDisabled() $eventManager = $this->createMock(EventManagerInterface::class); $eventManager->expects($this->never()) - ->method('attach'); + ->method('attach'); $this->listener->attach($eventManager); } @@ -79,7 +79,7 @@ public function testOnRouteDoesNothingIfNotHttpEnvironment() public function testOnRouteDoesNothingIfIfMethodIsAllowed() { - $event = new MvcEvent(); + $event = new MvcEvent(); $request = new HttpRequest(); $request->setMethod('foo'); $event->setRequest($request); @@ -92,7 +92,7 @@ public function testOnRouteDoesNothingIfIfMethodIsAllowed() public function testOnRouteReturns405ResponseIfMethodNotAllowed() { - $event = new MvcEvent(); + $event = new MvcEvent(); $request = new HttpRequest(); $request->setMethod('foo'); $event->setRequest($request); diff --git a/test/MiddlewareListenerTest.php b/test/MiddlewareListenerTest.php index c11c7165c..e52704320 100644 --- a/test/MiddlewareListenerTest.php +++ b/test/MiddlewareListenerTest.php @@ -1,19 +1,24 @@ routeMatch = $this->prophesize(RouteMatch::class); $this->routeMatch->getParam('middleware', false)->willReturn($middlewareMatched); $this->routeMatch->getParams()->willReturn([]); @@ -56,7 +64,7 @@ public function createMvcEvent($middlewareMatched, $middleware = null) return new EventManager(); }, ], - 'services' => [ + 'services' => [ $middlewareMatched => $middleware, ], ]); @@ -77,7 +85,7 @@ public function createMvcEvent($middlewareMatched, $middleware = null) public function testSuccessfullyDispatchesMiddleware() { - $event = $this->createMvcEvent('path', function ($request, $response) { + $event = $this->createMvcEvent('path', function ($request, $response) { $this->assertInstanceOf(ServerRequestInterface::class, $request); $this->assertInstanceOf(ResponseInterface::class, $response); $response->getBody()->write('Test!'); @@ -86,7 +94,10 @@ public function testSuccessfullyDispatchesMiddleware() $application = $event->getApplication(); $application->getEventManager()->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) { - $this->fail(sprintf('dispatch.error triggered when it should not be: %s', var_export($e->getError(), 1))); + $this->fail(sprintf( + 'dispatch.error triggered when it should not be: %s', + var_export($e->getError(), true) + )); }); $listener = new MiddlewareListener(); @@ -105,11 +116,14 @@ public function testSuccessfullyDispatchesHttpInteropMiddleware() $middleware = $this->createMock(MiddlewareInterface::class); $middleware->expects($this->once())->method('process')->willReturn(new HtmlResponse($expectedOutput)); - $event = $this->createMvcEvent('path', $middleware); + $event = $this->createMvcEvent('path', $middleware); $application = $event->getApplication(); $application->getEventManager()->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) { - $this->fail(sprintf('dispatch.error triggered when it should not be: %s', var_export($e->getError(), 1))); + $this->fail(sprintf( + 'dispatch.error triggered when it should not be: %s', + var_export($e->getError(), true) + )); }); $listener = new MiddlewareListener(); @@ -124,7 +138,7 @@ public function testSuccessfullyDispatchesHttpInteropMiddleware() public function testMatchedRouteParamsAreInjectedToRequestAsAttributes() { $matchedRouteParam = uniqid('matched param', true); - $routeAttribute = null; + $routeAttribute = null; $event = $this->createMvcEvent( 'foo', @@ -192,14 +206,17 @@ public function testSuccessfullyDispatchesPipeOfCallableAndHttpInteropStyleMiddl $event->setRouteMatch($routeMatch->reveal()); $event->getApplication()->getEventManager()->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) { - $this->fail(sprintf('dispatch.error triggered when it should not be: %s', var_export($e->getError(), 1))); + $this->fail(sprintf( + 'dispatch.error triggered when it should not be: %s', + var_export($e->getError(), true) + )); }); $listener = new MiddlewareListener(); $return = $listener->onDispatch($event); $this->assertInstanceOf(Response::class, $return); - $this->assertInstanceOf('Zend\Http\Response', $return); + $this->assertInstanceOf(Response::class, $return); $this->assertSame(200, $return->getStatusCode()); $this->assertEquals('firstMiddlewareValue', $return->getBody()); } @@ -222,8 +239,8 @@ public function testTriggersErrorForUncallableMiddleware() public function testTriggersErrorForExceptionRaisedInMiddleware() { - $exception = new \Exception(); - $event = $this->createMvcEvent('path', function ($request, $response) use ($exception) { + $exception = new Exception(); + $event = $this->createMvcEvent('path', function ($request, $response) use ($exception) { throw $exception; }); @@ -272,7 +289,10 @@ function () { $event->setRouteMatch($routeMatch->reveal()); $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($e) { - $this->fail(sprintf('dispatch.error triggered when it should not be: %s', var_export($e->getError(), 1))); + $this->fail(sprintf( + 'dispatch.error triggered when it should not be: %s', + var_export($e->getError(), true) + )); }); $listener = new MiddlewareListener(); @@ -293,7 +313,7 @@ public function testMiddlewareWithNothingPipedReachesFinalHandlerException() $eventManager = new EventManager(); $serviceManager = $this->prophesize(ContainerInterface::class); - $application = $this->prophesize(Application::class); + $application = $this->prophesize(Application::class); $application->getEventManager()->willReturn($eventManager); $application->getServiceManager()->will(function () use ($serviceManager) { return $serviceManager->reveal(); @@ -329,7 +349,7 @@ public function testNullMiddlewareThrowsInvalidMiddlewareException() $eventManager = new EventManager(); $serviceManager = $this->prophesize(ContainerInterface::class); - $application = $this->prophesize(Application::class); + $application = $this->prophesize(Application::class); $application->getEventManager()->willReturn($eventManager); $application->getServiceManager()->will(function () use ($serviceManager) { return $serviceManager->reveal(); @@ -359,17 +379,17 @@ public function testValidMiddlewareDispatchCancelsPreviousDispatchFailures() $middlewareName = uniqid('middleware', true); $routeMatch = new RouteMatch(['middleware' => $middlewareName]); $response = new DiactorosResponse(); - /* @var $application Application|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Application|PHPUnit_Framework_MockObject_MockObject $application */ $application = $this->createMock(Application::class); $eventManager = new EventManager(); - $middleware = $this->getMockBuilder(\stdClass::class)->setMethods(['__invoke'])->getMock(); + $middleware = $this->getMockBuilder(stdClass::class)->setMethods(['__invoke'])->getMock(); $serviceManager = new ServiceManager([ 'factories' => [ 'EventManager' => function () { return new EventManager(); }, ], - 'services' => [ + 'services' => [ $middlewareName => $middleware, ], ]); @@ -400,20 +420,20 @@ public function testValidMiddlewareFiresDispatchableInterfaceEventListeners() $middlewareName = uniqid('middleware', true); $routeMatch = new RouteMatch(['middleware' => $middlewareName]); $response = new DiactorosResponse(); - /* @var $application Application|\PHPUnit_Framework_MockObject_MockObject */ - $application = $this->createMock(Application::class); - $sharedManager = new SharedEventManager(); - /* @var $sharedListener callable|\PHPUnit_Framework_MockObject_MockObject */ - $sharedListener = $this->getMockBuilder(\stdClass::class)->setMethods(['__invoke'])->getMock(); + /** @var Application|PHPUnit_Framework_MockObject_MockObject $application */ + $application = $this->createMock(Application::class); + $sharedManager = new SharedEventManager(); + /** @var callable|PHPUnit_Framework_MockObject_MockObject $sharedListener */ + $sharedListener = $this->getMockBuilder(stdClass::class)->setMethods(['__invoke'])->getMock(); $eventManager = new EventManager(); - $middleware = $this->getMockBuilder(\stdClass::class)->setMethods(['__invoke'])->getMock(); + $middleware = $this->getMockBuilder(stdClass::class)->setMethods(['__invoke'])->getMock(); $serviceManager = new ServiceManager([ 'factories' => [ 'EventManager' => function () use ($sharedManager) { return new EventManager($sharedManager); }, ], - 'services' => [ + 'services' => [ $middlewareName => $middleware, ], ]); @@ -448,17 +468,17 @@ public function testWillNotDispatchWhenAnMvcEventResultIsAlreadySet($alreadySetR { $middlewareName = uniqid('middleware', true); $routeMatch = new RouteMatch(['middleware' => $middlewareName]); - /* @var $application Application|\PHPUnit_Framework_MockObject_MockObject */ + /** @var Application|PHPUnit_Framework_MockObject_MockObject $application */ $application = $this->createMock(Application::class); $eventManager = new EventManager(); - $middleware = $this->getMockBuilder(\stdClass::class)->setMethods(['__invoke'])->getMock(); + $middleware = $this->getMockBuilder(stdClass::class)->setMethods(['__invoke'])->getMock(); $serviceManager = new ServiceManager([ 'factories' => [ 'EventManager' => function () { return new EventManager(); }, ], - 'services' => [ + 'services' => [ $middlewareName => $middleware, ], ]); @@ -498,12 +518,12 @@ public function alreadySetMvcEventResultProvider() [true], [false], [[]], - [new \stdClass()], + [new stdClass()], [$this], [$this->createMock(ModelInterface::class)], [$this->createMock(Response::class)], [['view model data' => 'as an array']], - [['foo' => new \stdClass()]], + [['foo' => new stdClass()]], ['a response string'], ]; } diff --git a/test/ModuleRouteListenerTest.php b/test/ModuleRouteListenerTest.php index 56eec1a4e..eb56c7829 100644 --- a/test/ModuleRouteListenerTest.php +++ b/test/ModuleRouteListenerTest.php @@ -1,17 +1,19 @@ router->addRoute('foo', [ - 'type' => 'Literal', + 'type' => 'Literal', 'options' => [ 'route' => '/foo', 'defaults' => [ ModuleRouteListener::MODULE_NAMESPACE => 'Foo', - 'controller' => 'Index', + 'controller' => 'Index', ], ], ]); @@ -58,7 +60,7 @@ public function testRouteReturningModuleNamespaceInRouteMatchTriggersControllerR public function testRouteNotReturningModuleNamespaceInRouteMatchLeavesControllerUntouched() { $this->router->addRoute('foo', [ - 'type' => 'Literal', + 'type' => 'Literal', 'options' => [ 'route' => '/foo', 'defaults' => [ @@ -84,12 +86,12 @@ public function testMultipleRegistrationShouldNotResultInMultiplePrefixingOfCont $moduleListener->attach($this->events); $this->router->addRoute('foo', [ - 'type' => 'Literal', + 'type' => 'Literal', 'options' => [ 'route' => '/foo', 'defaults' => [ ModuleRouteListener::MODULE_NAMESPACE => 'Foo', - 'controller' => 'Index', + 'controller' => 'Index', ], ], ]); @@ -112,12 +114,12 @@ public function testRouteMatchIsTransformedToProperControllerClassName() $moduleListener->attach($this->events); $this->router->addRoute('foo', [ - 'type' => 'Literal', + 'type' => 'Literal', 'options' => [ 'route' => '/foo', 'defaults' => [ ModuleRouteListener::MODULE_NAMESPACE => 'Foo', - 'controller' => 'some-index', + 'controller' => 'some-index', ], ], ]); diff --git a/test/ResponseSender/AbstractResponseSenderTest.php b/test/ResponseSender/AbstractResponseSenderTest.php index cdd926ac7..d4c0716ac 100644 --- a/test/ResponseSender/AbstractResponseSenderTest.php +++ b/test/ResponseSender/AbstractResponseSenderTest.php @@ -1,10 +1,12 @@ markTestSkipped('Xdebug extension needed, skipped test'); } - $headers = [ + $headers = [ 'Content-Length: 2000', - 'Transfer-Encoding: chunked' + 'Transfer-Encoding: chunked', ]; $response = new Response(); $response->getHeaders()->addHeaders($headers); @@ -35,16 +45,16 @@ public function testSendHeadersTwoTimesSendsOnlyOnce() ->getMock(); $mockSendResponseEvent->expects( - $this->any() - ) - ->method('getResponse') - ->will($this->returnValue($response)); + $this->any() + ) + ->method('getResponse') + ->will($this->returnValue($response)); $responseSender = $this->getMockForAbstractClass(AbstractResponseSender::class); $responseSender->sendHeaders($mockSendResponseEvent); $sentHeaders = xdebug_get_headers(); - $diff = array_diff($sentHeaders, $headers); + $diff = array_diff($sentHeaders, $headers); if (count($diff)) { $header = array_shift($diff); @@ -96,7 +106,7 @@ public function testSendHeadersSendsStatusLast() 'X-Test: HTTP/1.1 202 Accepted', $sentHeaders[1], 'Status header is sent last to prevent header() from overwriting the ZF status code when a Location ' - . 'header is used' + . 'header is used' ); } } diff --git a/test/ResponseSender/PhpEnvironmentResponseSenderTest.php b/test/ResponseSender/PhpEnvironmentResponseSenderTest.php index be983e243..d7b495611 100644 --- a/test/ResponseSender/PhpEnvironmentResponseSenderTest.php +++ b/test/ResponseSender/PhpEnvironmentResponseSenderTest.php @@ -1,10 +1,12 @@ getMockForAbstractClass(ResponseInterface::class); + $mockResponse = $this->getMockForAbstractClass(ResponseInterface::class); $mockSendResponseEvent = $this->getSendResponseEventMock(); $mockSendResponseEvent->expects($this->any())->method('getResponse')->will($this->returnValue($mockResponse)); $responseSender = new PhpEnvironmentResponseSender(); @@ -48,7 +53,7 @@ public function testSendResponseTwoTimesPrintsResponseOnlyOnce() protected function getSendResponseEventMock() { - $returnValue = false; + $returnValue = false; $mockSendResponseEvent = $this->getMockBuilder(SendResponseEvent::class) ->setMethods(['getResponse', 'contentSent', 'setContentSent']) ->getMock(); diff --git a/test/ResponseSender/SendResponseEventTest.php b/test/ResponseSender/SendResponseEventTest.php index e8eb9d2bc..c9b5b3a86 100644 --- a/test/ResponseSender/SendResponseEventTest.php +++ b/test/ResponseSender/SendResponseEventTest.php @@ -1,10 +1,12 @@ getMockForAbstractClass(ResponseInterface::class); + $mockResponse = $this->getMockForAbstractClass(ResponseInterface::class); $mockResponse2 = $this->getMockForAbstractClass(ResponseInterface::class); - $event = new SendResponseEvent(); + $event = new SendResponseEvent(); $event->setResponse($mockResponse); $this->assertFalse($event->headersSent()); $this->assertFalse($event->contentSent()); diff --git a/test/ResponseSender/SimpleStreamResponseSenderTest.php b/test/ResponseSender/SimpleStreamResponseSenderTest.php index aca16d9ed..68fbced06 100644 --- a/test/ResponseSender/SimpleStreamResponseSenderTest.php +++ b/test/ResponseSender/SimpleStreamResponseSenderTest.php @@ -1,10 +1,12 @@ getMockForAbstractClass(Stdlib\ResponseInterface::class); + $mockResponse = $this->getMockForAbstractClass(Stdlib\ResponseInterface::class); $mockSendResponseEvent = $this->getSendResponseEventMock($mockResponse); - $responseSender = new SimpleStreamResponseSender(); + $responseSender = new SimpleStreamResponseSender(); ob_start(); $responseSender($mockSendResponseEvent); $body = ob_get_clean(); @@ -28,14 +35,14 @@ public function testSendResponseIgnoresInvalidResponseTypes() public function testSendResponseTwoTimesPrintsResponseOnlyOnce() { - $file = fopen(__DIR__ . '/TestAsset/sample-stream-file.txt', 'rb'); + $file = fopen(__DIR__ . '/TestAsset/sample-stream-file.txt', 'rb'); $mockResponse = $this->createMock(Response\Stream::class); $mockResponse->expects($this->once())->method('getStream')->will($this->returnValue($file)); $mockSendResponseEvent = $this->getSendResponseEventMock($mockResponse); - $responseSender = new SimpleStreamResponseSender(); + $responseSender = new SimpleStreamResponseSender(); ob_start(); $responseSender($mockSendResponseEvent); - $body = ob_get_clean(); + $body = ob_get_clean(); $expected = file_get_contents(__DIR__ . '/TestAsset/sample-stream-file.txt'); $this->assertEquals($expected, $body); diff --git a/test/SendResponseListenerTest.php b/test/SendResponseListenerTest.php index d0b75d0a2..7ebbf1f8a 100644 --- a/test/SendResponseListenerTest.php +++ b/test/SendResponseListenerTest.php @@ -1,23 +1,27 @@ getEventManager()->getIdentifiers(); $expected = [SendResponseListener::class]; $this->assertEquals($expected, array_values($identifiers)); @@ -26,9 +30,9 @@ public function testEventManagerIdentifiers() public function testSendResponseTriggersSendResponseEvent() { $listener = new SendResponseListener(); - $result = []; + $result = []; $listener->getEventManager()->attach(SendResponseEvent::EVENT_SEND_RESPONSE, function ($e) use (&$result) { - $result['target'] = $e->getTarget(); + $result['target'] = $e->getTarget(); $result['response'] = $e->getResponse(); }, 10000); $mockResponse = $this->getMockForAbstractClass(ResponseInterface::class); @@ -38,8 +42,8 @@ public function testSendResponseTriggersSendResponseEvent() $mockMvcEvent->expects($this->any())->method('getResponse')->will($this->returnValue($mockResponse)); $listener->sendResponse($mockMvcEvent); $expected = [ - 'target' => $listener, - 'response' => $mockResponse + 'target' => $listener, + 'response' => $mockResponse, ]; $this->assertEquals($expected, $result); } diff --git a/test/Service/ControllerManagerFactoryTest.php b/test/Service/ControllerManagerFactoryTest.php index e2418ce9b..9df3251a2 100644 --- a/test/Service/ControllerManagerFactoryTest.php +++ b/test/Service/ControllerManagerFactoryTest.php @@ -1,14 +1,18 @@ defaultServiceConfig = [ - 'aliases' => [ + 'aliases' => [ 'SharedEventManager' => SharedEventManager::class, ], 'factories' => [ @@ -45,11 +48,11 @@ public function setUp() : void 'EventManager' => EventManagerFactory::class, SharedEventManager::class => InvokableFactory::class, ], - 'services' => [ + 'services' => [ 'config' => [], ], ]; - $this->services = new ServiceManager(); + $this->services = new ServiceManager(); (new Config($this->defaultServiceConfig))->configureServiceManager($this->services); } @@ -63,7 +66,7 @@ public function testCannotLoadInvalidDispatchable() try { $loader->get(InvalidDispatchableClass::class); $this->fail('Retrieving the invalid dispatchable should fail'); - } catch (\Exception $e) { + } catch (Throwable $e) { do { $this->assertStringNotContainsString('Should not instantiate this', $e->getMessage()); } while ($e = $e->getPrevious()); @@ -73,9 +76,11 @@ public function testCannotLoadInvalidDispatchable() public function testCannotLoadControllerFromPeer() { $services = new ServiceManager(); - (new Config(array_merge_recursive($this->defaultServiceConfig, ['services' => [ - 'foo' => $this, - ]])))->configureServiceManager($services); + (new Config(array_merge_recursive($this->defaultServiceConfig, [ + 'services' => [ + 'foo' => $this, + ], + ])))->configureServiceManager($services); $loader = $services->get('ControllerManager'); $this->expectException(Exception\ExceptionInterface::class); @@ -100,7 +105,7 @@ public function testCallPluginWithControllerPluginManager() $controllerPluginManager->setAlias('samplePlugin', SamplePlugin::class); $controllerPluginManager->setFactory(SamplePlugin::class, InvokableFactory::class); - $controller = new SampleController; + $controller = new SampleController(); $controllerPluginManager->setController($controller); $plugin = $controllerPluginManager->get('samplePlugin'); diff --git a/test/Service/HttpMethodListenerFactoryTest.php b/test/Service/HttpMethodListenerFactoryTest.php index 7eec683be..d678f3487 100644 --- a/test/Service/HttpMethodListenerFactoryTest.php +++ b/test/Service/HttpMethodListenerFactoryTest.php @@ -1,10 +1,12 @@ serviceLocator->reveal(), 'HttpMethodListener'); $this->assertTrue($listener->isEnabled()); $this->assertNotEmpty($listener->getAllowedMethods()); @@ -40,13 +40,13 @@ public function testCreateWithDefaults() public function testCreateWithConfig() { $config['http_methods_listener'] = [ - 'enabled' => false, - 'allowed_methods' => ['FOO', 'BAR'] + 'enabled' => false, + 'allowed_methods' => ['FOO', 'BAR'], ]; $this->serviceLocator->get('config')->willReturn($config); - $factory = new HttpMethodListenerFactory(); + $factory = new HttpMethodListenerFactory(); $listener = $factory($this->serviceLocator->reveal(), 'HttpMethodListener'); $listenerConfig = $config['http_methods_listener']; diff --git a/test/Service/InjectTemplateListenerFactoryTest.php b/test/Service/InjectTemplateListenerFactoryTest.php index 2fb0b4e0d..8e2d639c5 100644 --- a/test/Service/InjectTemplateListenerFactoryTest.php +++ b/test/Service/InjectTemplateListenerFactoryTest.php @@ -1,15 +1,18 @@ assertEquals('some/module', $listener->mapController("SomeModule")); + $this->assertEquals('some/module', $listener->mapController('SomeModule')); } public function testFactoryCanSetControllerMapViaArrayAccessVM() @@ -47,16 +50,16 @@ public function testFactoryCanSetControllerMapViaArrayAccessVM() // must be an array due to type hinting on setControllerMap() 'SomeModule' => 'some/module', ], - ]) + ]), ]); - $this->assertEquals('some/module', $listener->mapController("SomeModule")); + $this->assertEquals('some/module', $listener->mapController('SomeModule')); } /** * @param mixed $config * - * @return \PHPUnit_Framework_MockObject_MockObject|\Zend\Mvc\View\Http\InjectTemplateListener + * @return PHPUnit_Framework_MockObject_MockObject|InjectTemplateListener */ private function buildInjectTemplateListenerWithConfig($config) { diff --git a/test/Service/RequestFactoryTest.php b/test/Service/RequestFactoryTest.php index bf3382e6c..fb158f28d 100644 --- a/test/Service/RequestFactoryTest.php +++ b/test/Service/RequestFactoryTest.php @@ -1,10 +1,12 @@ prophesize(ContainerInterface::class)->reveal(), 'Response'); $this->assertInstanceOf(HttpResponse::class, $response); } diff --git a/test/Service/SendResponseListenerFactoryTest.php b/test/Service/SendResponseListenerFactoryTest.php index e9adc2f22..9d93b99f8 100644 --- a/test/Service/SendResponseListenerFactoryTest.php +++ b/test/Service/SendResponseListenerFactoryTest.php @@ -1,10 +1,12 @@ prophesize(SharedEventManagerInterface::class); - $events = $this->prophesize(EventManagerInterface::class); + $events = $this->prophesize(EventManagerInterface::class); $events->getSharedManager()->will([$sharedEvents, 'reveal']); $events->setIdentifiers([SendResponseListener::class, SendResponseListener::class])->shouldBeCalled(); $events->attach( - SendResponseEvent::EVENT_SEND_RESPONSE, - Argument::type(PhpEnvironmentResponseSender::class), - -1000 - )->shouldBeCalled(); + SendResponseEvent::EVENT_SEND_RESPONSE, + Argument::type(PhpEnvironmentResponseSender::class), + -1000 + ) + ->shouldBeCalled(); $events->attach( - SendResponseEvent::EVENT_SEND_RESPONSE, - Argument::type(SimpleStreamResponseSender::class), - -3000 - )->shouldBeCalled(); + SendResponseEvent::EVENT_SEND_RESPONSE, + Argument::type(SimpleStreamResponseSender::class), + -3000 + ) + ->shouldBeCalled(); $events->attach( - SendResponseEvent::EVENT_SEND_RESPONSE, - Argument::type(HttpResponseSender::class), - -4000 - )->shouldBeCalled(); + SendResponseEvent::EVENT_SEND_RESPONSE, + Argument::type(HttpResponseSender::class), + -4000 + ) + ->shouldBeCalled(); $container = $this->prophesize(ContainerInterface::class); $container->get('EventManager')->will([$events, 'reveal']); - $factory = new SendResponseListenerFactory(); + $factory = new SendResponseListenerFactory(); $listener = $factory($container->reveal()); $this->assertInstanceOf(SendResponseListener::class, $listener); $this->assertSame($events->reveal(), $listener->getEventManager()); diff --git a/test/Service/ServiceListenerFactoryTest.php b/test/Service/ServiceListenerFactoryTest.php index c969611d3..5dae48944 100644 --- a/test/Service/ServiceListenerFactoryTest.php +++ b/test/Service/ServiceListenerFactoryTest.php @@ -1,10 +1,12 @@ sm = $this->getMockBuilder(ServiceManager::class) - ->setMethods(['get']) - ->getMock(); + ->setMethods(['get']) + ->getMock(); - $this->factory = new ServiceListenerFactory(); + $this->factory = new ServiceListenerFactory(); } public function testInvalidOptionType() @@ -38,8 +36,8 @@ public function testInvalidOptionType() $this->expectException(ServiceNotCreatedException::class); $this->expectExceptionMessage('The value of service_listener_options must be an array, string given.'); $this->sm->expects($this->once()) - ->method('get') - ->will($this->returnValue(['service_listener_options' => 'string'])); + ->method('get') + ->will($this->returnValue(['service_listener_options' => 'string'])); $this->factory->__invoke($this->sm, 'ServiceListener'); } @@ -56,8 +54,8 @@ public function testMissingServiceManager() $config['service_listener_options'][0]['method'] = 'test'; $this->sm->expects($this->once()) - ->method('get') - ->will($this->returnValue($config)); + ->method('get') + ->will($this->returnValue($config)); $this->factory->__invoke($this->sm, 'ServiceListener'); } @@ -74,8 +72,8 @@ public function testInvalidTypeServiceManager() $config['service_listener_options'][0]['method'] = 'test'; $this->sm->expects($this->once()) - ->method('get') - ->will($this->returnValue($config)); + ->method('get') + ->will($this->returnValue($config)); $this->factory->__invoke($this->sm, 'ServiceListener'); } @@ -92,8 +90,8 @@ public function testMissingConfigKey() $config['service_listener_options'][0]['method'] = 'test'; $this->sm->expects($this->once()) - ->method('get') - ->will($this->returnValue($config)); + ->method('get') + ->will($this->returnValue($config)); $this->factory->__invoke($this->sm, 'ServiceListener'); } @@ -110,8 +108,8 @@ public function testInvalidTypeConfigKey() $config['service_listener_options'][0]['method'] = 'test'; $this->sm->expects($this->once()) - ->method('get') - ->will($this->returnValue($config)); + ->method('get') + ->will($this->returnValue($config)); $this->factory->__invoke($this->sm, 'ServiceListener'); } @@ -128,8 +126,8 @@ public function testMissingInterface() $config['service_listener_options'][0]['method'] = 'test'; $this->sm->expects($this->once()) - ->method('get') - ->will($this->returnValue($config)); + ->method('get') + ->will($this->returnValue($config)); $this->factory->__invoke($this->sm, 'ServiceListener'); } @@ -146,8 +144,8 @@ public function testInvalidTypeInterface() $config['service_listener_options'][0]['method'] = 'test'; $this->sm->expects($this->once()) - ->method('get') - ->will($this->returnValue($config)); + ->method('get') + ->will($this->returnValue($config)); $this->factory->__invoke($this->sm, 'ServiceListener'); } @@ -164,8 +162,8 @@ public function testMissingMethod() $config['service_listener_options'][0]['method'] = null; $this->sm->expects($this->once()) - ->method('get') - ->will($this->returnValue($config)); + ->method('get') + ->will($this->returnValue($config)); $this->factory->__invoke($this->sm, 'ServiceListener'); } @@ -182,8 +180,8 @@ public function testInvalidTypeMethod() $config['service_listener_options'][0]['method'] = 1; $this->sm->expects($this->once()) - ->method('get') - ->will($this->returnValue($config)); + ->method('get') + ->will($this->returnValue($config)); $this->factory->__invoke($this->sm, 'ServiceListener'); } diff --git a/test/Service/ServiceManagerConfigTest.php b/test/Service/ServiceManagerConfigTest.php index 1f65d1d3c..95c4ac971 100644 --- a/test/Service/ServiceManagerConfigTest.php +++ b/test/Service/ServiceManagerConfigTest.php @@ -1,19 +1,19 @@ services->get('SharedEventManager')); } @@ -58,7 +53,7 @@ protected function createEventManager(SharedEventManagerInterface $sharedManager */ public function testEventManagerAwareInterfaceIsNotInjectedIfPresentButSharedManagerIs() { - $events = $this->createEventManager(); + $events = $this->createEventManager(); EventManagerAwareObject::$defaultEvents = $events; $this->services->setAlias('EventManagerAwareObject', EventManagerAwareObject::class); @@ -79,7 +74,7 @@ public function testCanMergeCustomConfigWithDefaultConfig() 'invokables' => [ 'foo' => stdClass::class, ], - 'factories' => [ + 'factories' => [ 'bar' => function () { return new stdClass(); }, @@ -103,7 +98,7 @@ public function testCanOverrideDefaultConfigWithCustomConfig() 'invokables' => [ 'foo' => stdClass::class, ], - 'factories' => [ + 'factories' => [ 'ModuleManager' => function () { return new stdClass(); }, @@ -127,21 +122,21 @@ public function testCanAddDelegators() /* * Create delegator closure */ - $delegator = function ($container, $name, $callback, array $options = null) { - $service = $callback(); + $delegator = function ($container, $name, $callback, ?array $options = null) { + $service = $callback(); $service->bar = 'baz'; return $service; }; $config = [ - 'aliases' => [ + 'aliases' => [ 'foo' => stdClass::class, ], - 'factories' => [ + 'factories' => [ stdClass::class => InvokableFactory::class, ], 'delegators' => [ - stdClass::class => [ $delegator ], + stdClass::class => [$delegator], ], ]; @@ -166,7 +161,7 @@ public function testEventManagerInitializerCanBeReplaced() 'initializers' => [ 'EventManagerAwareInitializer' => $initializer, ], - 'factories' => [ + 'factories' => [ 'EventManagerAware' => function () use ($instance) { return $instance; }, diff --git a/test/Service/TestAsset/ControllerWithDependencies.php b/test/Service/TestAsset/ControllerWithDependencies.php index b7b4c41eb..8f87d2020 100644 --- a/test/Service/TestAsset/ControllerWithDependencies.php +++ b/test/Service/TestAsset/ControllerWithDependencies.php @@ -1,32 +1,33 @@ injectedValue = $injected; } - public function dispatch(RequestInterface $request, ResponseInterface $response = null) + public function dispatch(RequestInterface $request, ?ResponseInterface $response = null) { } } diff --git a/test/Service/TestAsset/Dispatchable.php b/test/Service/TestAsset/Dispatchable.php index 4c5de0272..11a70ce32 100644 --- a/test/Service/TestAsset/Dispatchable.php +++ b/test/Service/TestAsset/Dispatchable.php @@ -1,10 +1,12 @@ markTestSkipped(sprintf( '%s::%s skipped until zend-view and the url() view helper are updated to use zend-router', - get_class($this), + static::class, __FUNCTION__ )); $routeMatch = $this->prophesize(RouteMatch::class)->reveal(); - $mvcEvent = $this->prophesize(MvcEvent::class); + $mvcEvent = $this->prophesize(MvcEvent::class); $mvcEvent->getRouteMatch()->willReturn($routeMatch); $application = $this->prophesize(Application::class); @@ -89,7 +95,7 @@ public function testUrlHelperFactoryCanBeInvokedViaShortNameOrFullClassName($nam $this->services->setService('config', []); $manager = $this->factory->__invoke($this->services, HelperPluginManager::class); - $helper = $manager->get($name); + $helper = $manager->get($name); $this->assertAttributeSame($routeMatch, 'routeMatch', $helper, 'Route match was not injected'); $this->assertAttributeSame($router, 'router', $helper, 'Router was not injected'); @@ -100,22 +106,27 @@ public function basePathConfiguration() $names = ['basepath', 'basePath', 'BasePath', Helper\BasePath::class, 'zendviewhelperbasepath']; $configurations = [ - 'hard-coded' => [[ - 'config' => [ - 'view_manager' => [ - 'base_path' => '/foo/baz', + 'hard-coded' => [ + [ + 'config' => [ + 'view_manager' => [ + 'base_path' => '/foo/baz', + ], ], ], - ], '/foo/baz'], - - 'request-base' => [[ - 'config' => [], // fails creating plugin manager without this - 'Request' => function () { - $request = $this->prophesize(Request::class); - $request->getBasePath()->willReturn('/foo/bat'); - return $request->reveal(); - }, - ], '/foo/bat'], + '/foo/baz', + ], + 'request-base' => [ + [ + 'config' => [], // fails creating plugin manager without this + 'Request' => function () { + $request = $this->prophesize(Request::class); + $request->getBasePath()->willReturn('/foo/bat'); + return $request->reveal(); + }, + ], + '/foo/bat', + ], ]; foreach ($names as $name) { @@ -143,7 +154,7 @@ public function testBasePathHelperFactoryCanBeInvokedViaShortNameOrFullClassName } $plugins = $this->factory->__invoke($this->services, HelperPluginManager::class); - $helper = $plugins->get($name); + $helper = $plugins->get($name); $this->assertInstanceof(Helper\BasePath::class, $helper); $this->assertEquals($expected, $helper()); } @@ -171,7 +182,7 @@ public function testDoctypeHelperFactoryCanBeInvokedViaShortNameOrFullClassName( ]); $plugins = $this->factory->__invoke($this->services, HelperPluginManager::class); - $helper = $plugins->get($name); + $helper = $plugins->get($name); $this->assertInstanceof(Helper\Doctype::class, $helper); $this->assertEquals('', (string) $helper); } diff --git a/test/Service/ViewJsonStrategyFactoryTest.php b/test/Service/ViewJsonStrategyFactoryTest.php index 0768537c9..69af4a5b6 100644 --- a/test/Service/ViewJsonStrategyFactoryTest.php +++ b/test/Service/ViewJsonStrategyFactoryTest.php @@ -1,10 +1,12 @@ services[$name])); + return isset($this->services[$name]); } - public function build($name, array $options = null) + public function build($name, ?array $options = null) { if (! isset($this->services[$name])) { throw new ServiceNotFoundException(); diff --git a/test/TestAsset/Middleware.php b/test/TestAsset/Middleware.php index 289bc3b12..af2d07f75 100644 --- a/test/TestAsset/Middleware.php +++ b/test/TestAsset/Middleware.php @@ -1,20 +1,22 @@ getBody()->write(__CLASS__); + $response->getBody()->write(self::class); return $response; } } diff --git a/test/TestAsset/MiddlewareAbstractFactory.php b/test/TestAsset/MiddlewareAbstractFactory.php index ccde7d726..9c301503c 100644 --- a/test/TestAsset/MiddlewareAbstractFactory.php +++ b/test/TestAsset/MiddlewareAbstractFactory.php @@ -1,15 +1,19 @@ classmap[$name]; - return new $classname; + return new $classname(); } } diff --git a/test/TestAsset/MockSendResponseListener.php b/test/TestAsset/MockSendResponseListener.php index 850314031..1d5bce44f 100644 --- a/test/TestAsset/MockSendResponseListener.php +++ b/test/TestAsset/MockSendResponseListener.php @@ -1,10 +1,12 @@ listener = new CreateViewModelListener(); - $this->event = new MvcEvent(); + $this->listener = new CreateViewModelListener(); + $this->event = new MvcEvent(); } public function testReCastsAssocArrayEventResultAsViewModel() @@ -50,7 +55,7 @@ public function nonAssocArrayResults() [1.00], ['string'], [['foo', 'bar']], - [new stdClass], + [new stdClass()], ]; } diff --git a/test/View/DefaultRendereringStrategyTest.php b/test/View/DefaultRendereringStrategyTest.php index 8e830ab6e..aaeaeeae4 100644 --- a/test/View/DefaultRendereringStrategyTest.php +++ b/test/View/DefaultRendereringStrategyTest.php @@ -1,14 +1,15 @@ renderer = new PhpRenderer(); $this->event->setRequest($this->request) - ->setResponse($this->response); + ->setResponse($this->response); $this->strategy = new DefaultRenderingStrategy($this->view); } @@ -139,18 +143,17 @@ public function testTriggersRenderErrorEventInCaseOfRenderingException() 'invokables' => [ 'SharedEventManager' => SharedEventManager::class, ], - 'factories' => [ + 'factories' => [ 'EventManager' => function ($services) { $sharedEvents = $services->get('SharedEventManager'); - $events = new EventManager($sharedEvents); - return $events; + return new EventManager($sharedEvents); }, ], - 'services' => [ + 'services' => [ 'Request' => $this->request, 'Response' => $this->response, ], - 'shared' => [ + 'shared' => [ 'EventManager' => false, ], ]))->configureServiceManager($services); diff --git a/test/View/ExceptionStrategyTest.php b/test/View/ExceptionStrategyTest.php index d49e3f7be..bec626fa2 100644 --- a/test/View/ExceptionStrategyTest.php +++ b/test/View/ExceptionStrategyTest.php @@ -1,12 +1,15 @@ setParam('exception', $exception); $event->setError(Application::ERROR_EXCEPTION); @@ -96,7 +101,7 @@ public function testCatchesApplicationExceptions() public function testCatchesUnknownErrorTypes() { - $exception = new \Exception; + $exception = new Exception(); $event = new MvcEvent(); $event->setParam('exception', $exception); $event->setError('custom_error'); @@ -128,7 +133,7 @@ public function testEmptyErrorInEventResultsInNoOperations() public function testDoesNothingIfEventResultIsAResponse() { - $event = new MvcEvent(); + $event = new MvcEvent(); $response = new Response(); $event->setResponse($response); $event->setResult($response); @@ -163,7 +168,7 @@ public function testDetachesListeners() public function testReuseResponseStatusCodeIfItExists() { - $event = new MvcEvent(); + $event = new MvcEvent(); $response = new Response(); $response->setStatusCode(401); $event->setResponse($response); diff --git a/test/View/InjectTemplateListenerTest.php b/test/View/InjectTemplateListenerTest.php index 7cc460a39..5a7298834 100644 --- a/test/View/InjectTemplateListenerTest.php +++ b/test/View/InjectTemplateListenerTest.php @@ -1,10 +1,12 @@ true, + $controllerMap = [ + 'MappedNs' => true, 'ZendTest\MappedNs' => true, ]; - $this->listener = new InjectTemplateListener(); + $this->listener = new InjectTemplateListener(); $this->listener->setControllerMap($controllerMap); $this->event = new MvcEvent(); $this->routeMatch = new RouteMatch([]); @@ -122,7 +126,7 @@ public function testMapsSubNamespaceToSubDirectoryWithControllerFromRouteMatch() $this->routeMatch->setParam('controller', 'CiderSales'); $this->routeMatch->setParam('action', 'PinkiePieRevenue'); - $moduleRouteListener = new ModuleRouteListener; + $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->onRoute($this->event); $model = new ViewModel(); @@ -138,10 +142,10 @@ public function testMapsSubNamespaceToSubDirectoryWithControllerFromRouteMatchHa $this->routeMatch->setParam('controller', 'Sub\CiderSales'); $this->routeMatch->setParam('action', 'PinkiePieRevenue'); - $moduleRouteListener = new ModuleRouteListener; + $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->onRoute($this->event); - $model = new ViewModel(); + $model = new ViewModel(); $this->event->setResult($model); $this->listener->injectTemplate($this->event); @@ -153,7 +157,7 @@ public function testMapsSubNamespaceToSubDirectoryWithControllerFromEventTarget( $this->routeMatch->setParam(ModuleRouteListener::MODULE_NAMESPACE, 'ZendTest\Mvc\Controller\TestAsset'); $this->routeMatch->setParam('action', 'test'); - $moduleRouteListener = new ModuleRouteListener; + $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->onRoute($this->event); $myViewModel = new ViewModel(); @@ -172,10 +176,10 @@ public function testMapsSubNamespaceToSubDirectoryWithControllerFromEventTargetS $this->routeMatch->setParam('controller', 'TestAsset\SampleController'); $this->routeMatch->setParam('action', 'test'); - $moduleRouteListener = new ModuleRouteListener; + $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->onRoute($this->event); - $myViewModel = new ViewModel(); + $myViewModel = new ViewModel(); $this->event->setResult($myViewModel); $this->listener->injectTemplate($this->event); @@ -194,7 +198,7 @@ public function testMapsSubNamespaceToSubDirectoryWithControllerFromEventTargetS public function testControllerMatchedByMapIsInflected() { $this->routeMatch->setParam('controller', 'MappedNs\SubNs\Controller\Sample'); - $myViewModel = new ViewModel(); + $myViewModel = new ViewModel(); $this->event->setResult($myViewModel); $this->listener->injectTemplate($this->event); @@ -224,7 +228,7 @@ public function testFullControllerNameMatchIsMapped() public function testOnlyFullNamespaceMatchIsMapped() { $this->listener->setControllerMap([ - 'Foo' => 'foo-matched', + 'Foo' => 'foo-matched', 'Foo\Bar' => 'foo-bar-matched', ]); $template = $this->listener->mapController('Foo\BarBaz\Controller\IndexController'); @@ -243,7 +247,7 @@ public function testControllerMapMatchedPrefixReplacedByStringValue() public function testUsingNamespaceRouteParameterGivesSameResultAsFullControllerParameter() { $this->routeMatch->setParam('controller', 'MappedNs\Foo\Controller\Bar\Baz\Sample'); - $myViewModel = new ViewModel(); + $myViewModel = new ViewModel(); $this->event->setResult($myViewModel); $this->listener->injectTemplate($this->event); @@ -253,10 +257,10 @@ public function testUsingNamespaceRouteParameterGivesSameResultAsFullControllerP $this->routeMatch->setParam(ModuleRouteListener::MODULE_NAMESPACE, 'MappedNs\Foo\Controller\Bar'); $this->routeMatch->setParam('controller', 'Baz\Sample'); - $moduleRouteListener = new ModuleRouteListener; + $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->onRoute($this->event); - $myViewModel = new ViewModel(); + $myViewModel = new ViewModel(); $this->event->setResult($myViewModel); $this->listener->injectTemplate($this->event); @@ -267,7 +271,7 @@ public function testUsingNamespaceRouteParameterGivesSameResultAsFullControllerP public function testControllerMapOnlyFullNamespaceMatches() { $this->listener->setControllerMap([ - 'Foo' => 'foo-matched', + 'Foo' => 'foo-matched', 'Foo\Bar' => 'foo-bar-matched', ]); $template = $this->listener->mapController('Foo\BarBaz\Controller\IndexController'); @@ -277,7 +281,7 @@ public function testControllerMapOnlyFullNamespaceMatches() public function testControllerMapRuleSetToFalseIsIgnored() { $this->listener->setControllerMap([ - 'Foo' => 'foo-matched', + 'Foo' => 'foo-matched', 'Foo\Bar' => false, ]); $template = $this->listener->mapController('Foo\Bar\Controller\IndexController'); @@ -344,7 +348,7 @@ public function testPrefersRouteMatchControllerWithRouteMatchAndControllerMap() { $this->assertFalse($this->listener->isPreferRouteMatchController()); $controllerMap = [ - 'Some\Other\Service\Namespace\Controller\Sample' => 'another/sample' + 'Some\Other\Service\Namespace\Controller\Sample' => 'another/sample', ]; $this->routeMatch->setParam('prefer_route_match_controller', true); diff --git a/test/View/InjectViewModelListenerTest.php b/test/View/InjectViewModelListenerTest.php index f3011fafc..a40c252d6 100644 --- a/test/View/InjectViewModelListenerTest.php +++ b/test/View/InjectViewModelListenerTest.php @@ -1,10 +1,12 @@ setTerminal(true); $this->event->setResult($childModel); @@ -39,7 +43,7 @@ public function testReplacesEventModelWithChildModelIfChildIsMarkedTerminal() public function testAddsViewModelAsChildOfEventViewModelWhenChildIsNotTerminal() { - $childModel = new ViewModel(); + $childModel = new ViewModel(); $this->event->setResult($childModel); $this->listener->injectViewModel($this->event); diff --git a/test/View/RouteNotFoundStrategyTest.php b/test/View/RouteNotFoundStrategyTest.php index 4acf75baa..c1dc0530b 100644 --- a/test/View/RouteNotFoundStrategyTest.php +++ b/test/View/RouteNotFoundStrategyTest.php @@ -1,12 +1,15 @@ setResponse($response) - ->setResult($response); + ->setResult($response); $this->strategy->prepareNotFoundViewModel($event); $model = $event->getResult(); @@ -215,7 +216,7 @@ public function test404ResponsePrepares404ViewModelWithExceptionWhenAllowed() { $response = new Response(); $event = new MvcEvent(); - $exception = new \Exception(); + $exception = new Exception(); $event->setParam('exception', $exception); foreach ([true, false] as $allow) { @@ -271,8 +272,8 @@ public function test404ResponsePrepares404ViewModelWithControllerWhenAllowed() public function testInjectsHttpResponseIntoEventIfNoneAlreadyPresent() { - $event = new MvcEvent(); - $errors = [ + $event = new MvcEvent(); + $errors = [ 'not-found' => Application::ERROR_CONTROLLER_NOT_FOUND, 'invalid' => Application::ERROR_CONTROLLER_INVALID, ]; @@ -302,8 +303,8 @@ public function testAttachesListenersAtExpectedPriorities() $this->strategy->attach($events); $evs = [ - MvcEvent::EVENT_DISPATCH => -90, - MvcEvent::EVENT_DISPATCH_ERROR => 1 + MvcEvent::EVENT_DISPATCH => -90, + MvcEvent::EVENT_DISPATCH_ERROR => 1, ]; foreach ($evs as $event => $expectedPriority) { $this->assertListenerAtPriority( diff --git a/test/View/TestAsset/DumbStrategy.php b/test/View/TestAsset/DumbStrategy.php index 3369410ca..ab0dfdf11 100644 --- a/test/View/TestAsset/DumbStrategy.php +++ b/test/View/TestAsset/DumbStrategy.php @@ -1,10 +1,12 @@