From 0c92035efe397e79352d422786525628c53c59c0 Mon Sep 17 00:00:00 2001 From: stdex Date: Sat, 8 May 2021 00:58:56 +0300 Subject: [PATCH 1/3] Update dependencies --- .editorconfig | 0 .github/workflows/ci.yml | 34 +++ .gitignore | 0 .htaccess | 0 README.md | 0 composer.json | 38 +-- index.php | 0 phpcs.xml | 6 + phpunit.xml | 0 src/App.php | 228 ++++++++++-------- src/Bundle.php | 27 ++- src/Cache.php | 49 ++-- src/CallableResolver.php | 22 +- src/Config.php | 103 ++++---- src/Controller.php | 74 +++--- src/Database.php | 35 +-- src/DebugInfo.php | 14 +- src/Error.php | 32 +-- src/ExceptionHandler.php | 129 +++++----- src/FlashMessages.php | 18 +- src/Helper.php | 7 +- src/Log.php | 31 ++- src/Middleware.php | 18 +- src/Model.php | 25 +- src/ObjectCache.php | 52 ++-- src/Provider.php | 6 +- src/Registry.php | 92 +++---- src/Router.php | 20 +- src/Settings.php | 33 +-- src/SmartyViewEngine.php | 86 ------- src/Template.php | 53 ++-- src/TwigViewEngine.php | 45 ++-- src/View.php | 87 ++++--- src/exceptions/FatalErrorException.php | 2 +- src/helpers.php | 78 +++--- src/interfaces/ViewEngineInterface.php | 14 +- src/middlewares/AssetsMiddleware.php | 31 ++- src/middlewares/NegotiationMiddleware.php | 30 ++- src/providers/SmartyProvider.php | 23 -- src/providers/TwigProvider.php | 16 +- src/traits/ClassTrait.php | 29 ++- src/traits/CollectionTrait.php | 10 +- src/traits/ContainerTrait.php | 11 +- src/traits/EventsDispatcherTrait.php | 26 +- src/traits/OptionsTrait.php | 12 +- tests/app/Bundle.php | 0 tests/app/config/app.php | 21 +- tests/app/config/cache.php | 13 +- tests/app/config/controllers.php | 0 tests/app/config/helpers.php | 0 tests/app/config/providers.php | 4 - tests/app/controllers/TestController.php | 22 +- .../app/controllers/cells/TestController.php | 4 +- .../subnamespace/TestController.php | 4 +- tests/app/helpers/TestHelper.php | 0 tests/app/helpers/subnamespace/TestHelper.php | 0 tests/app/models/TestModel.php | 4 +- .../models/deep/subnamespace/TestModel.php | 0 tests/app/providers/SmartyProvider.php | 7 - tests/app/providers/TwigProvider.php | 0 tests/app/routes.php | 9 +- .../app/templates/controllers/Test/cell.twig | 0 .../app/templates/controllers/Test/helper.tpl | 1 - .../templates/controllers/Test/helper.twig | 0 .../templates/controllers/Test/template.twig | 0 .../controllers/cells/Test/display.twig | 0 .../subnamespace/Test/template.twig | 0 tests/app/templates/template3.twig | 0 tests/bundles/first/Bundle.php | 0 tests/bundles/first/classes/Animal.php | 2 +- tests/bundles/first/classes/AnimalClass.php | 2 +- tests/bundles/first/config/middlewares.php | 0 .../first/middlewares/AnimalMiddleware.php | 5 +- .../first/middlewares/ZooMiddleware.php | 5 +- tests/bundles/first/routes.php | 9 +- tests/bundles/first/templates/animal.tpl | 1 - tests/bundles/first/templates/animal.twig | 0 .../first/templates/zoo/animals/lion.twig | 0 .../first/templates/zoo/animals/zebra.twig | 0 tests/bundles/second/Bundle.php | 0 tests/bundles/second/classes/Animal.php | 2 +- tests/bundles/second/classes/AnimalClass.php | 2 +- tests/bundles/second/routes.php | 9 +- tests/bundles/second/templates/animal.tpl | 1 - tests/bundles/second/templates/animal.twig | 0 tests/bundles/third/Bundle.php | 0 tests/bundles/third/classes/Animal.php | 2 +- tests/bundles/third/classes/AnimalClass.php | 2 +- tests/bundles/third/routes.php | 9 +- tests/bundles/third/templates/animal.tpl | 1 - tests/bundles/third/templates/animal.twig | 0 tests/cases/AppTest.php | 192 ++++++++------- tests/cases/SkipTest.php | 26 +- tests/cases/Test.php | 4 +- tests/cases/traits/ClassTraitTest.php | 35 +-- tests/cases/traits/OptionsTraitTest.php | 47 ++-- tests/config/first/bundles.php | 0 tests/config/first/development/bundles.php | 0 tests/config/second/bundles.php | 0 99 files changed, 1113 insertions(+), 978 deletions(-) mode change 100644 => 100755 .editorconfig create mode 100644 .github/workflows/ci.yml mode change 100644 => 100755 .gitignore mode change 100644 => 100755 .htaccess mode change 100644 => 100755 README.md mode change 100644 => 100755 composer.json mode change 100644 => 100755 index.php create mode 100644 phpcs.xml mode change 100644 => 100755 phpunit.xml mode change 100644 => 100755 src/App.php mode change 100644 => 100755 src/Bundle.php mode change 100644 => 100755 src/Cache.php mode change 100644 => 100755 src/CallableResolver.php mode change 100644 => 100755 src/Config.php mode change 100644 => 100755 src/Controller.php mode change 100644 => 100755 src/Database.php mode change 100644 => 100755 src/DebugInfo.php mode change 100644 => 100755 src/Error.php mode change 100644 => 100755 src/ExceptionHandler.php mode change 100644 => 100755 src/FlashMessages.php mode change 100644 => 100755 src/Helper.php mode change 100644 => 100755 src/Log.php mode change 100644 => 100755 src/Middleware.php mode change 100644 => 100755 src/Model.php mode change 100644 => 100755 src/ObjectCache.php mode change 100644 => 100755 src/Provider.php mode change 100644 => 100755 src/Registry.php mode change 100644 => 100755 src/Router.php mode change 100644 => 100755 src/Settings.php delete mode 100644 src/SmartyViewEngine.php mode change 100644 => 100755 src/Template.php mode change 100644 => 100755 src/TwigViewEngine.php mode change 100644 => 100755 src/View.php mode change 100644 => 100755 src/exceptions/FatalErrorException.php mode change 100644 => 100755 src/helpers.php mode change 100644 => 100755 src/interfaces/ViewEngineInterface.php mode change 100644 => 100755 src/middlewares/AssetsMiddleware.php mode change 100644 => 100755 src/middlewares/NegotiationMiddleware.php delete mode 100644 src/providers/SmartyProvider.php mode change 100644 => 100755 src/providers/TwigProvider.php mode change 100644 => 100755 src/traits/ClassTrait.php mode change 100644 => 100755 src/traits/CollectionTrait.php mode change 100644 => 100755 src/traits/ContainerTrait.php mode change 100644 => 100755 src/traits/EventsDispatcherTrait.php mode change 100644 => 100755 src/traits/OptionsTrait.php mode change 100644 => 100755 tests/app/Bundle.php mode change 100644 => 100755 tests/app/config/app.php mode change 100644 => 100755 tests/app/config/cache.php mode change 100644 => 100755 tests/app/config/controllers.php mode change 100644 => 100755 tests/app/config/helpers.php mode change 100644 => 100755 tests/app/config/providers.php mode change 100644 => 100755 tests/app/controllers/TestController.php mode change 100644 => 100755 tests/app/controllers/cells/TestController.php mode change 100644 => 100755 tests/app/controllers/subnamespace/TestController.php mode change 100644 => 100755 tests/app/helpers/TestHelper.php mode change 100644 => 100755 tests/app/helpers/subnamespace/TestHelper.php mode change 100644 => 100755 tests/app/models/TestModel.php mode change 100644 => 100755 tests/app/models/deep/subnamespace/TestModel.php delete mode 100644 tests/app/providers/SmartyProvider.php mode change 100644 => 100755 tests/app/providers/TwigProvider.php mode change 100644 => 100755 tests/app/routes.php mode change 100644 => 100755 tests/app/templates/controllers/Test/cell.twig delete mode 100644 tests/app/templates/controllers/Test/helper.tpl mode change 100644 => 100755 tests/app/templates/controllers/Test/helper.twig mode change 100644 => 100755 tests/app/templates/controllers/Test/template.twig mode change 100644 => 100755 tests/app/templates/controllers/cells/Test/display.twig mode change 100644 => 100755 tests/app/templates/controllers/subnamespace/Test/template.twig mode change 100644 => 100755 tests/app/templates/template3.twig mode change 100644 => 100755 tests/bundles/first/Bundle.php mode change 100644 => 100755 tests/bundles/first/classes/Animal.php mode change 100644 => 100755 tests/bundles/first/classes/AnimalClass.php mode change 100644 => 100755 tests/bundles/first/config/middlewares.php mode change 100644 => 100755 tests/bundles/first/middlewares/AnimalMiddleware.php mode change 100644 => 100755 tests/bundles/first/middlewares/ZooMiddleware.php mode change 100644 => 100755 tests/bundles/first/routes.php delete mode 100644 tests/bundles/first/templates/animal.tpl mode change 100644 => 100755 tests/bundles/first/templates/animal.twig mode change 100644 => 100755 tests/bundles/first/templates/zoo/animals/lion.twig mode change 100644 => 100755 tests/bundles/first/templates/zoo/animals/zebra.twig mode change 100644 => 100755 tests/bundles/second/Bundle.php mode change 100644 => 100755 tests/bundles/second/classes/Animal.php mode change 100644 => 100755 tests/bundles/second/classes/AnimalClass.php mode change 100644 => 100755 tests/bundles/second/routes.php delete mode 100644 tests/bundles/second/templates/animal.tpl mode change 100644 => 100755 tests/bundles/second/templates/animal.twig mode change 100644 => 100755 tests/bundles/third/Bundle.php mode change 100644 => 100755 tests/bundles/third/classes/Animal.php mode change 100644 => 100755 tests/bundles/third/classes/AnimalClass.php mode change 100644 => 100755 tests/bundles/third/routes.php delete mode 100644 tests/bundles/third/templates/animal.tpl mode change 100644 => 100755 tests/bundles/third/templates/animal.twig mode change 100644 => 100755 tests/cases/AppTest.php mode change 100644 => 100755 tests/cases/SkipTest.php mode change 100644 => 100755 tests/cases/Test.php mode change 100644 => 100755 tests/cases/traits/ClassTraitTest.php mode change 100644 => 100755 tests/cases/traits/OptionsTraitTest.php mode change 100644 => 100755 tests/config/first/bundles.php mode change 100644 => 100755 tests/config/first/development/bundles.php mode change 100644 => 100755 tests/config/second/bundles.php diff --git a/.editorconfig b/.editorconfig old mode 100644 new mode 100755 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b1cdfb2 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: CI +on: [push, pull_request] +jobs: + build: + strategy: + matrix: + operating-system: [ubuntu-latest] + php-versions: ['7.3'] + runs-on: ${{ matrix.operating-system }} + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 #https://github.com/shivammathur/setup-php + with: + php-version: ${{ matrix.php-versions }} + extensions: mbstring, json, fileinfo, pdo + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + # Use composer.json for key, if composer.lock is not committed. + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + #key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + - name: Install dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader + - name: Test with phpunit + run: vendor/bin/phpunit --coverage-text + - name: Run phpcs + run: ./vendor/bin/phpcs diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/.htaccess b/.htaccess old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/composer.json b/composer.json old mode 100644 new mode 100755 index 096dbeb..ed65080 --- a/composer.json +++ b/composer.json @@ -4,22 +4,29 @@ "homepage": "http://momentphp.kminek.pl", "keywords": ["framework", "momentphp"], "require": { - "slim/slim": "3.3.*", - "illuminate/support": "5.1.*", - "illuminate/events": "5.1.*", - "illuminate/database": "5.1.*", - "illuminate/cache": "5.1.*", - "illuminate/filesystem": "5.1.*", - "smarty/smarty": "3.1.*", - "twig/twig": "1.24.*", - "monolog/monolog": "1.18.*", - "filp/whoops": "2.1.*", - "symfony/var-dumper": "3.0.*", - "willdurand/negotiation": "2.0.*", - "soundasleep/html2text": "0.2.*" + "php": "^7.3|^8.0", + "ext-json": "*", + "ext-mbstring": "*", + "ext-fileinfo": "*", + "ext-pdo": "*", + "slim/slim": "4.*", + "slim/psr7": "*", + "illuminate/container": "8.*", + "illuminate/support": "8.*", + "illuminate/events": "8.*", + "illuminate/database": "8.*", + "illuminate/cache": "8.*", + "illuminate/filesystem": "8.*", + "twig/twig": "3.*", + "monolog/monolog": "2.*", + "filp/whoops": "2.*", + "symfony/var-dumper": "5.*", + "willdurand/negotiation": "3.*", + "soundasleep/html2text": "1.*" }, "require-dev": { - "phpunit/phpunit": "4.*" + "phpunit/phpunit": "9.*", + "squizlabs/php_codesniffer": "3.*" }, "autoload": { "psr-4": { @@ -34,6 +41,9 @@ "momentphp\\tests\\": "tests" } }, + "config": { + "optimize-autoloader": true + }, "minimum-stability": "dev", "prefer-stable" : true } diff --git a/index.php b/index.php old mode 100644 new mode 100755 diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 0000000..e92c784 --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,6 @@ + + + PSR12 + src + + diff --git a/phpunit.xml b/phpunit.xml old mode 100644 new mode 100755 diff --git a/src/App.php b/src/App.php old mode 100644 new mode 100755 index 0a11d23..56d5845 --- a/src/App.php +++ b/src/App.php @@ -2,6 +2,21 @@ namespace momentphp; +use Illuminate\Container\Container; +use Illuminate\Support\Collection; +use Illuminate\Support\Str; +use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\ServerRequestInterface; +use Slim\Psr7\Environment; +use Slim\Psr7\Factory\ResponseFactory; +use Slim\Psr7\Factory\StreamFactory; +use Slim\Psr7\Factory\UriFactory; +use Slim\Psr7\Headers; +use Slim\Psr7\Request; +use Slim\Routing\RouteCollector; +use Slim\Routing\RouteResolver; +use Soundasleep\Html2Text; + /** * App */ @@ -14,7 +29,7 @@ class App /** * Globally available app * - * @var \momentphp\App + * @var App */ protected static $instance; @@ -58,8 +73,9 @@ class App * * @param array $bundles * @param array $container + * @throws \Exception */ - public function __construct($bundles = [], $container = []) + public function __construct(array $bundles = [], array $container = []) { $self = $this; static::setInstance($self); @@ -68,7 +84,7 @@ public function __construct($bundles = [], $container = []) * App */ if (!isset($container['app'])) { - $container['app'] = function () use ($self) { + $container['app'] = static function () use ($self) { return $self; }; } @@ -77,7 +93,7 @@ public function __construct($bundles = [], $container = []) * Registry */ if (!isset($container['registry'])) { - $container['registry'] = function ($c) { + $container['registry'] = static function ($c) { return new Registry($c); }; } @@ -93,7 +109,7 @@ public function __construct($bundles = [], $container = []) * Debug */ if (!isset($container['debug'])) { - $container['debug'] = function ($c) { + $container['debug'] = static function ($c) { return $c->get('config')->get('app.displayErrorDetails', false); }; } @@ -102,7 +118,7 @@ public function __construct($bundles = [], $container = []) * Debug info */ if (!isset($container['debugInfo'])) { - $container['debugInfo'] = function ($c) { + $container['debugInfo'] = static function ($c) { return new DebugInfo($c); }; } @@ -111,7 +127,7 @@ public function __construct($bundles = [], $container = []) * Console */ if (!isset($container['console'])) { - $container['console'] = function () { + $container['console'] = static function () { return (PHP_SAPI === 'cli'); }; } @@ -120,7 +136,7 @@ public function __construct($bundles = [], $container = []) * Storage path */ if (!isset($container['pathStorage'])) { - $container['pathStorage'] = function ($c) { + $container['pathStorage'] = static function ($c) { $path = $c->has('pathBase') ? [$c->get('pathBase'), 'storage'] : [sys_get_temp_dir(), 'momentphp']; return path($path); }; @@ -130,7 +146,7 @@ public function __construct($bundles = [], $container = []) * Config */ if (!isset($container['config'])) { - $container['config'] = function ($c) { + $container['config'] = static function ($c) { return new Config($c->get('app')->resourcePaths('config'), $c->get('env')); }; } @@ -139,7 +155,7 @@ public function __construct($bundles = [], $container = []) * Database */ if (!isset($container['database'])) { - $container['database'] = function ($c) { + $container['database'] = static function ($c) { return new Database($c->get('config')->get('database', []), $c->get('debug'), $c->get('app')->eventsDispatcher()); }; } @@ -148,7 +164,7 @@ public function __construct($bundles = [], $container = []) * View */ if (!isset($container['view'])) { - $container['view'] = function ($c) { + $container['view'] = static function ($c) { $engine = $c->get('config')->get('app.viewEngine', 'twig'); return new View($c, $engine); }; @@ -158,7 +174,7 @@ public function __construct($bundles = [], $container = []) * Template */ if (!isset($container['template'])) { - $container['template'] = function ($c) { + $container['template'] = static function ($c) { return new Template($c); }; } @@ -167,7 +183,7 @@ public function __construct($bundles = [], $container = []) * Flash messages */ if (!isset($container['flash'])) { - $container['flash'] = function ($c) { + $container['flash'] = static function ($c) { return new FlashMessages($c->get('view')); }; } @@ -176,7 +192,7 @@ public function __construct($bundles = [], $container = []) * Cache */ if (!isset($container['cache'])) { - $container['cache'] = function ($c) { + $container['cache'] = static function ($c) { return new Cache($c->get('config'), $c->get('app')->eventsDispatcher()); }; } @@ -185,7 +201,7 @@ public function __construct($bundles = [], $container = []) * Object cache */ if (!isset($container['objectCache'])) { - $container['objectCache'] = function () { + $container['objectCache'] = static function () { return new ObjectCache; }; } @@ -194,7 +210,7 @@ public function __construct($bundles = [], $container = []) * Log */ if (!isset($container['log'])) { - $container['log'] = function ($c) { + $container['log'] = static function ($c) { return new Log($c->get('config')->get('loggers', [])); }; } @@ -203,7 +219,7 @@ public function __construct($bundles = [], $container = []) * Error */ if (!isset($container['error'])) { - $container['error'] = function ($c) { + $container['error'] = static function ($c) { return new Error($c); }; } @@ -212,41 +228,52 @@ public function __construct($bundles = [], $container = []) * Exception handler */ if (!isset($container['exceptionHandler'])) { - $container['exceptionHandler'] = function ($c) { + $container['exceptionHandler'] = static function ($c) { return new ExceptionHandler($c); }; } /** - * Router (Slim) + * Callable resolver (Slim) */ - if (!isset($container['router'])) { - $container['router'] = function () { - return new Router; + if (!isset($container['callableResolver'])) { + $container['callableResolver'] = static function ($c) { + return new CallableResolver($c, new \Slim\CallableResolver($c)); }; } /** - * Callable resolver (Slim) + * Router (Slim) */ - if (!isset($container['callableResolver'])) { - $container['callableResolver'] = function ($c) { - return new CallableResolver($c, new \Slim\CallableResolver($c)); + if (!isset($container['router'])) { + $container['router'] = static function () use ($container) { + $callableResolver = $container['callableResolver']; + $responseFactory = new ResponseFactory(); + $routeCollector = new RouteCollector($responseFactory, $callableResolver); + return new RouteResolver($routeCollector); }; } /** * Init Slim app */ - $this->slim = new \Slim\App($container); + if (is_array($container)) { + $container = new Container($container); + } + + $responseFactory = new ResponseFactory(); + $this->slim = new \Slim\App($responseFactory, $container); $this->container($this->slim->getContainer()); /** * Settings (Slim) */ - $this->service('settings', function ($c) { - return new Settings($c->get('config'), 'app'); - }); + $this->service( + 'settings', + function ($c) { + return new Settings($c->get('config'), 'app'); + } + ); /** * Add bundles @@ -289,11 +316,11 @@ public function __construct($bundles = [], $container = []) /** * Default paths * - * @param \Illuminate\Support\Collection $bundles - * @param string $resource + * @param Collection $bundles + * @param string $resource * @return array */ - protected function defaultPaths($bundles, $resource) + protected function defaultPaths(Collection $bundles, string $resource): array { $paths = []; foreach ($bundles as $bundle) { @@ -321,7 +348,7 @@ protected function defaultPaths($bundles, $resource) * @param string $key * @param callable $callable */ - public function resource($key, $callable) + public function resource(string $key, callable $callable): void { $this->resources[$key] = $callable; } @@ -329,10 +356,11 @@ public function resource($key, $callable) /** * Return resource paths * - * @param string $key + * @param string $key * @return array + * @throws \Exception */ - public function resourcePaths($key) + public function resourcePaths(string $key): array { if (!isset($this->resources[$key])) { throw new \Exception('Undefined resource: ' . $key); @@ -344,9 +372,9 @@ public function resourcePaths($key) /** * Get the globally available app * - * @return \momentphp\App + * @return App */ - public static function getInstance() + public static function getInstance(): App { return static::$instance; } @@ -354,9 +382,9 @@ public static function getInstance() /** * Set the globally available app * - * @param \momentphp\App $app + * @param App $app */ - public static function setInstance(App $app) + public static function setInstance(App $app): void { static::$instance = $app; } @@ -364,7 +392,7 @@ public static function setInstance(App $app) /** * Register autoloader * - * @return bool + * @return bool|void */ public function registerAutoloader() { @@ -378,7 +406,7 @@ public function registerAutoloader() /** * Unregister autoloader * - * @return bool + * @return bool|void */ public function unregisterAutoloader() { @@ -393,13 +421,13 @@ public function unregisterAutoloader() * * @param string $class */ - protected function loadClass($class) + protected function loadClass(string $class): void { if ($this->bundles()->isEmpty()) { return; } $namespace = $this->bundleClass(); - if (!\Illuminate\Support\Str::startsWith($class, $namespace)) { + if (!Str::startsWith($class, $namespace)) { return; } $relativeClass = ltrim(substr($class, strlen($namespace)), '\\'); @@ -418,10 +446,10 @@ class_alias($fullClass, $class); /** * Return PHP namespace of last bundle inside collection * - * @param null|string $class + * @param string|null $relativeClass * @return string */ - public function bundleClass($relativeClass = null) + public function bundleClass(?string $relativeClass = null): string { $last = $this->bundles()->last(); $namespace = $last::classNamespace(); @@ -437,7 +465,7 @@ public function bundleClass($relativeClass = null) * @param string $name * @param callable $callable */ - public function service($name, $callable) + public function service(string $name, callable $callable): void { $container = $this->container(); $container[$name] = $callable; @@ -446,12 +474,12 @@ public function service($name, $callable) /** * Build the path for a named route including the base path (helper) * - * @param string $name - * @param array $data - * @param array $queryParams + * @param string $name + * @param array $data + * @param array $queryParams * @return string */ - public function url($name, $data = [], $queryParams = []) + public function url(string $name, array $data = [], array $queryParams = []): string { return $this->container()->get('router')->pathFor($name, $data, $queryParams); } @@ -459,10 +487,10 @@ public function url($name, $data = [], $queryParams = []) /** * Return fingerprint * - * @param string $glue + * @param string $glue * @return string */ - public function fingerprint($glue = '_') + public function fingerprint(string $glue = '_'): string { $aliases = []; foreach ($this->bundles() as $bundle) { @@ -477,10 +505,10 @@ public function fingerprint($glue = '_') /** * Return bundle(s) * - * @param null|string $alias - * @return \Illuminate\Support\Collection|\momentphp\Bundle + * @param string|null $alias + * @return Collection|Bundle */ - public function bundles($alias = null) + public function bundles(?string $alias = null) { return ($alias === null) ? $this->collection() : $this->collection()->get($alias); } @@ -488,7 +516,7 @@ public function bundles($alias = null) /** * Register providers */ - public function registerProviders() + public function registerProviders(): void { if (!$this->container()->has('config')) { return; @@ -506,14 +534,14 @@ public function registerProviders() /** * Register middlewares */ - public function registerMiddlewares() + public function registerMiddlewares(): void { if (!$this->container()->has('config')) { return; } $self = $this; $middlewares = $this->container()->get('config')->get('app.middlewares', []); - $load = function ($middlewares, $type) use ($self) { + $load = static function ($middlewares, $type) use ($self) { foreach ($middlewares as $key => $name) { if (($name === false) && ($type === 'app')) { continue; @@ -523,9 +551,12 @@ public function registerMiddlewares() return $next($request, $response); }; } - $self->service($key, function () use ($self, $name) { - return $self->container()->get('registry')->load($name); - }); + $self->service( + $key, + function () use ($self, $name) { + return $self->container()->get('registry')->load($name); + } + ); if ($type === 'app') { $self->add($key); } @@ -541,8 +572,9 @@ public function registerMiddlewares() /** * Register routes + * @throws \Exception */ - public function registerRoutes() + public function registerRoutes(): void { $app = $this; foreach ($this->resourcePaths('routes') as $path) { @@ -555,7 +587,7 @@ public function registerRoutes() /** * Boot bundles */ - public function bootBundles() + public function bootBundles(): void { foreach ($this->bundles() as $bundle) { if (method_exists($bundle, 'boot')) { @@ -567,7 +599,7 @@ public function bootBundles() /** * Boot providers */ - public function bootProviders() + public function bootProviders(): void { foreach ($this->providers as $provider) { if (method_exists($provider, 'boot')) { @@ -578,8 +610,9 @@ public function bootProviders() /** * Boot app + * @throws \Exception */ - public function boot() + public function boot(): void { if ($this->booted) { return; @@ -609,59 +642,62 @@ public function boot() /** * Run app * - * @param bool $silent - * @return \Psr\Http\Message\ResponseInterface + * @param ServerRequestInterface|null $request + * @return void + * @throws \Soundasleep\Html2TextException */ - public function run($silent = false) + public function run(?ServerRequestInterface $request = null): void { if ($this->container->has('console') && $this->container->get('console')) { global $argv; $uri = (isset($argv[1])) ? '/' . $argv[1] : '/'; $response = $this->visit($uri); - $body = (string) $response->getBody(); + $body = (string)$response->getBody(); if (!empty($body)) { - echo \Html2Text\Html2Text::convert($body); + echo Html2Text::convert($body); } } else { $this->boot(); - return $this->slim->run($silent); + $this->slim->run($request); } } /** * Simulate app request * - * @param string $uri - * @param string $method - * @return \Psr\Http\Message\ResponseInterface + * @param string $uri + * @param string $method + * @return ResponseInterface + * @throws \Exception */ - public function visit($uri, $method = 'GET') + public function visit(string $uri, string $method = 'GET'): ResponseInterface { - $env = \Slim\Http\Environment::mock([ - 'SCRIPT_NAME' => '/index.php', - 'REQUEST_URI' => $uri, - 'REQUEST_METHOD' => $method, - ]); - $uri = \Slim\Http\Uri::createFromEnvironment($env); - $headers = \Slim\Http\Headers::createFromEnvironment($env); + $env = Environment::mock( + [ + 'SCRIPT_NAME' => '/index.php', + 'REQUEST_URI' => $uri, + 'REQUEST_METHOD' => $method, + ] + ); + $uri = (new UriFactory())->createUri($uri); + $headers = Headers::createFromGlobals(); $cookies = []; - $serverParams = $env->all(); - $body = new \Slim\Http\RequestBody; + $serverParams = $env; + $body = (new StreamFactory())->createStream(); - $request = new \Slim\Http\Request($method, $uri, $headers, $cookies, $serverParams, $body); - $response = new \Slim\Http\Response; + $request = new Request($method, $uri, $headers, $cookies, $serverParams, $body); $this->boot(); - return $this->slim->process($request, $response); + return $this->slim->handle($request); } /** * Container proxy method * - * @param string $name + * @param string $name * @return mixed */ - public function __get($name) + public function __get(string $name) { return $this->container()->get($name); } @@ -669,10 +705,10 @@ public function __get($name) /** * Container proxy method * - * @param string $name - * @return mixed + * @param string $name + * @return bool */ - public function __isset($name) + public function __isset(string $name) { return $this->container()->has($name); } @@ -680,11 +716,11 @@ public function __isset($name) /** * Proxy calls to underlying Slim app * - * @param string $method - * @param array $args + * @param string $method + * @param array $args * @return mixed */ - public function __call($method, $args = []) + public function __call(string $method, array $args = []) { return call_user_func_array([$this->slim, $method], $args); } diff --git a/src/Bundle.php b/src/Bundle.php old mode 100644 new mode 100755 index 779a261..b94474e --- a/src/Bundle.php +++ b/src/Bundle.php @@ -2,6 +2,9 @@ namespace momentphp; +use Illuminate\Support\Str; +use Psr\Container\ContainerInterface; + /** * Bundle */ @@ -14,10 +17,10 @@ abstract class Bundle /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container * @param array $options */ - public function __construct(\Interop\Container\ContainerInterface $container, $options = []) + public function __construct(ContainerInterface $container, array $options = []) { $this->container($container); $this->options($options); @@ -28,7 +31,7 @@ public function __construct(\Interop\Container\ContainerInterface $container, $o * * @return string */ - public function alias() + public function alias(): string { if ($this->options('alias')) { return $this->options('alias'); @@ -39,34 +42,34 @@ public function alias() /** * Return `true` if passed resource should be skipped from loading * - * @param string $resource + * @param string $resource * @return bool */ - public function skipResource($resource) + public function skipResource(string $resource): bool { $skip = $this->options('skipResource'); if (!$skip) { return false; } - $skip = (array) $skip; - return in_array($resource, $skip); + $skip = (array)$skip; + return in_array($resource, $skip, true); } /** * Return `true` if passed class should be skipped from loading * - * @param string $class + * @param string $class * @return bool */ - public function skipClass($class) + public function skipClass(string $class): bool { $skip = $this->options('skipClass'); if (!$skip) { return false; } - $skip = (array) $skip; + $skip = (array)$skip; foreach ($skip as $cl) { - if (\Illuminate\Support\Str::startsWith($class, $cl)) { + if (Str::startsWith($class, $cl)) { return true; } } @@ -78,7 +81,7 @@ public function skipClass($class) * * @return bool */ - public function skipFingerprint() + public function skipFingerprint(): bool { $skip = $this->options('skipFingerprint'); if ($skip && ($skip === true)) { diff --git a/src/Cache.php b/src/Cache.php old mode 100644 new mode 100755 index 0fc1913..b0ca069 --- a/src/Cache.php +++ b/src/Cache.php @@ -2,6 +2,12 @@ namespace momentphp; +use Illuminate\Cache\CacheManager; +use Illuminate\Cache\MemcachedConnector; +use Illuminate\Container\Container; +use Illuminate\Events\Dispatcher; +use Illuminate\Filesystem\Filesystem; + /** * Cache */ @@ -10,7 +16,7 @@ class Cache /** * Cache manager * - * @var \Illuminate\Cache\CacheManager + * @var CacheManager */ protected $cacheManager; @@ -18,32 +24,41 @@ class Cache * Constructor * * @param Config $config - * @param null|\Illuminate\Events\Dispatcher $eventsDispatcher + * @param null|Dispatcher $eventsDispatcher */ - public function __construct(Config $config, \Illuminate\Events\Dispatcher $eventsDispatcher = null) + public function __construct(Config $config, ?Dispatcher $eventsDispatcher = null) { - $container = new \Illuminate\Container\Container; + $container = new Container; $container['config'] = $config; - $container->singleton('files', function () { - return new \Illuminate\Filesystem\Filesystem; - }); - $container->singleton('memcached.connector', function () { - return new \Illuminate\Cache\MemcachedConnector; - }); - $container->singleton('Illuminate\Contracts\Events\Dispatcher', function () use ($eventsDispatcher) { - return $eventsDispatcher; - }); - $this->cacheManager = new \Illuminate\Cache\CacheManager($container); + $container->singleton( + 'files', + function () { + return new Filesystem; + } + ); + $container->singleton( + 'memcached.connector', + function () { + return new MemcachedConnector; + } + ); + $container->singleton( + Dispatcher::class, + function () use ($eventsDispatcher) { + return $eventsDispatcher; + } + ); + $this->cacheManager = new CacheManager($container); } /** * Proxy calls to manager * - * @param string $method - * @param array $args + * @param string $method + * @param array $args * @return mixed */ - public function __call($method, $args) + public function __call(string $method, array $args) { return call_user_func_array([$this->cacheManager, $method], $args); } diff --git a/src/CallableResolver.php b/src/CallableResolver.php old mode 100644 new mode 100755 index 5006449..bffb514 --- a/src/CallableResolver.php +++ b/src/CallableResolver.php @@ -2,27 +2,30 @@ namespace momentphp; +use Psr\Container\ContainerInterface; +use Slim\Interfaces\CallableResolverInterface; + /** * CallableResolver */ -class CallableResolver implements \Slim\Interfaces\CallableResolverInterface +class CallableResolver implements CallableResolverInterface { use traits\ContainerTrait; /** * Base resolver * - * @var \Slim\Interfaces\CallableResolverInterface + * @var CallableResolverInterface */ protected $baseResolver; /** * Constructor * - * @param \Interop\Container\ContainerInterface $container - * @param array $options + * @param ContainerInterface $container + * @param CallableResolverInterface $baseResolver */ - public function __construct(\Interop\Container\ContainerInterface $container, \Slim\Interfaces\CallableResolverInterface $baseResolver) + public function __construct(ContainerInterface $container, CallableResolverInterface $baseResolver) { $this->container($container); $this->baseResolver = $baseResolver; @@ -31,20 +34,19 @@ public function __construct(\Interop\Container\ContainerInterface $container, \S /** * Resolve `$toResolve` into a callable * - * @param mixed $toResolve + * @param string|callable $toResolve * @return callable */ - public function resolve($toResolve) + public function resolve($toResolve): callable { try { - $resolved = $this->baseResolver->resolve($toResolve); - return $resolved; + return $this->baseResolver->resolve($toResolve); } catch (\Exception $e) { } $toResolveArr = explode(':', $toResolve); $class = $toResolveArr[0]; - $method = isset($toResolveArr[1]) ? $toResolveArr[1] : null; + $method = $toResolveArr[1] ?? null; $instance = $this->container()->get('registry')->load($class); return ($method) ? [$instance, $method] : $instance; diff --git a/src/Config.php b/src/Config.php old mode 100644 new mode 100755 index f214a21..aaf3ab3 --- a/src/Config.php +++ b/src/Config.php @@ -2,6 +2,8 @@ namespace momentphp; +use Illuminate\Support\Arr; + /** * Config */ @@ -48,7 +50,7 @@ class Config implements \ArrayAccess * @param array $configDirs * @param string $environment */ - public function __construct($configDirs, $environment = 'production') + public function __construct(array $configDirs, string $environment = 'production') { $this->configDirs = $configDirs; $this->environment = $environment; @@ -57,15 +59,15 @@ public function __construct($configDirs, $environment = 'production') /** * Get the specified configuration value * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return mixed */ - public function get($key, $default = null) + public function get(string $key, $default = null) { - list($group, $item) = $this->parseKey($key); + [$group, $item] = $this->parseKey($key); $this->load($group); - return array_get($this->items[$group], $item, $default); + return Arr::get($this->items[$group], $item, $default); } /** @@ -74,24 +76,24 @@ public function get($key, $default = null) * @param string $key * @param mixed $value */ - public function set($key, $value) + public function set(string $key, $value): void { list($group, $item) = $this->parseKey($key); $this->load($group); if ($item === null) { $this->items[$group] = $value; } else { - array_set($this->items[$group], $item, $value); + Arr::set($this->items[$group], $item, $value); } } /** * Determine if the given configuration value exists * - * @param string $key + * @param string $key * @return bool */ - public function has($key) + public function has(string $key): bool { $default = microtime(true); return $this->get($key, $default) !== $default; @@ -100,12 +102,12 @@ public function has($key) /** * Determine if a configuration group exists * - * @param string $key + * @param string $key * @return bool */ - public function hasGroup($key) + public function hasGroup(string $key): bool { - list($group, $item) = $this->parseKey($key); + [$group, $item] = $this->parseKey($key); return $this->exists($group); } @@ -114,7 +116,7 @@ public function hasGroup($key) * * @return array */ - public function getItems() + public function getItems(): array { return $this->items; } @@ -124,7 +126,7 @@ public function getItems() * * @return array */ - public function getConfigDirs() + public function getConfigDirs(): array { return $this->configDirs; } @@ -134,7 +136,7 @@ public function getConfigDirs() * * @return string */ - public function getEnvironment() + public function getEnvironment(): string { return $this->environment; } @@ -142,10 +144,10 @@ public function getEnvironment() /** * Parse a key into group and item * - * @param string $key + * @param string $key * @return array */ - protected function parseKey($key) + protected function parseKey(string $key): array { if (isset($this->parsed[$key])) { return $this->parsed[$key]; @@ -158,18 +160,18 @@ protected function parseKey($key) /** * Parse an array of basic segments * - * @param array $segments + * @param array $segments * @return array */ - protected function parseBasicSegments(array $segments) + protected function parseBasicSegments(array $segments): array { $group = $segments[0]; - if (count($segments) == 1) { + if (count($segments) === 1) { return [$group, null]; - } else { - $item = implode('.', array_slice($segments, 1)); - return [$group, $item]; } + + $item = implode('.', array_slice($segments, 1)); + return [$group, $item]; } /** @@ -177,7 +179,7 @@ protected function parseBasicSegments(array $segments) * * @param string $group */ - protected function load($group) + protected function load(string $group): void { $env = $this->environment; if (isset($this->items[$group])) { @@ -190,11 +192,11 @@ protected function load($group) /** * Load the given configuration group * - * @param string $environment - * @param string $group + * @param string $environment + * @param string $group * @return array */ - protected function loadItems($environment, $group) + protected function loadItems(string $environment, string $group): array { $items = []; foreach ($this->configDirs as $path) { @@ -215,10 +217,10 @@ protected function loadItems($environment, $group) /** * Determine if the given group exists * - * @param string $group + * @param string $group * @return bool */ - public function exists($group) + public function exists(string $group): bool { $key = $group; if (isset($this->exists[$key])) { @@ -238,11 +240,11 @@ public function exists($group) /** * Merge the items in the given file into the items * - * @param array $items - * @param string $file + * @param array $items + * @param string $file * @return array */ - protected function mergeEnvironment(array $items, $file) + protected function mergeEnvironment(array $items, string $file): array { return array_replace_recursive($items, $this->getRequire($file)); } @@ -250,58 +252,59 @@ protected function mergeEnvironment(array $items, $file) /** * Get the returned value of a file * - * @param string $path + * @param string $path * @return mixed + * @throws \Exception */ - protected function getRequire($path) + protected function getRequire(string $path) { if (is_file($path)) { return include $path; } - throw new Exception("File does not exist at path {$path}"); + throw new \Exception("File does not exist at path {$path}"); } /** * Determine if the given configuration option exists * - * @param string $key + * @param string $offset * @return bool */ - public function offsetExists($key) + public function offsetExists($offset): bool { - return $this->has($key); + return $this->has($offset); } /** * Get a configuration option * - * @param string $key + * @param string $offset * @return mixed */ - public function offsetGet($key) + public function offsetGet($offset) { - return $this->get($key); + return $this->get($offset); } /** * Set a configuration option * - * @param string $key + * @param string $offset * @param mixed $value */ - public function offsetSet($key, $value) + public function offsetSet($offset, $value) { - $this->set($key, $value); + $this->set($offset, $value); } /** * Unset a configuration option * - * @param string $key + * @param string $offset */ - public function offsetUnset($key) + public function offsetUnset($offset) { - $this->set($key, null); + $this->set($offset, null); } /** @@ -309,7 +312,7 @@ public function offsetUnset($key) * * @return array */ - public function files() + public function files(): array { $files = []; foreach ($this->configDirs as $path) { @@ -322,7 +325,7 @@ public function files() foreach ($regex as $o) { foreach ($o as $file) { $file = basename($file, '.php'); - if (!in_array($file, $files)) { + if (!in_array($file, $files, true)) { $files[] = $file; } } diff --git a/src/Controller.php b/src/Controller.php old mode 100644 new mode 100755 index a560834..c3980d0 --- a/src/Controller.php +++ b/src/Controller.php @@ -2,6 +2,11 @@ namespace momentphp; +use Psr\Container\ContainerInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; +use Slim\Exception\HttpNotFoundException; + /** * Controller */ @@ -14,31 +19,31 @@ abstract class Controller /** * Request * - * @var \Psr\Http\Message\RequestInterface + * @var RequestInterface */ protected $request; /** * Response * - * @var \Psr\Http\Message\ResponseInterface + * @var ResponseInterface */ protected $response; /** * View * - * @var \momentphp\View + * @var View */ protected $view; /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container * @param array $options */ - public function __construct(\Interop\Container\ContainerInterface $container, $options = []) + public function __construct(ContainerInterface $container, array $options = []) { $this->container($container); $this->options($options); @@ -54,7 +59,7 @@ public function __construct(\Interop\Container\ContainerInterface $container, $o * * @return array */ - public function implementedEvents() + public function implementedEvents(): array { return [ "controller.{static::classPrefix()}.initialize" => 'initialize', @@ -66,7 +71,7 @@ public function implementedEvents() /** * Callback called after controller creation */ - public function initialize() + public function initialize(): void { } @@ -75,7 +80,7 @@ public function initialize() * * @param string $action */ - public function beforeAction($action) + public function beforeAction(string $action): void { } @@ -84,24 +89,24 @@ public function beforeAction($action) * * @param string $action */ - public function afterAction($action) + public function afterAction(string $action): void { } /** * Return response object with rendered template * - * @param null|string $template - * @param null|string $bundle - * @return \Psr\Http\Message\ResponseInterface + * @param string|null $template + * @param string|null $bundle + * @return ResponseInterface */ - public function render($template = null, $bundle = null) + public function render(?string $template = null, ?string $bundle = null): ResponseInterface { $templateFolder = str_replace('.', '/', static::classConfigKey()); $this->view - ->request($this->request) - ->response($this->response) - ->templateFolder($templateFolder); + ->request($this->request) + ->response($this->response) + ->templateFolder($templateFolder); if ($this->view->template() === null) { $this->view->template($this->request->getAttribute('action')); } @@ -111,17 +116,19 @@ public function render($template = null, $bundle = null) if ($bundle) { $this->view->bundle($bundle); } - return $this->response->write($this->view->render()); + $this->response->getBody()->write($this->view->render()); + + return $this->response; } /** * Save a variable or an associative array of variables for use inside a template * - * @param mixed $name - * @param mixed $value - * @return \momentphp\View + * @param mixed $name + * @param mixed $value + * @return View */ - public function set($name, $value = null) + public function set($name, $value = null): View { return $this->view->set($name, $value); } @@ -129,10 +136,11 @@ public function set($name, $value = null) /** * Not found helper * - * @param null|\Psr\Http\Message\RequestInterface $request - * @param null|\Psr\Http\Message\ResponseInterface $response + * @param RequestInterface|null $request + * @param ResponseInterface|null $response + * @throws HttpNotFoundException */ - public function abort($request = null, $response = null) + public function abort(?RequestInterface $request = null, ?ResponseInterface $response = null): void { if ($request === null) { $request = $this->request; @@ -140,18 +148,18 @@ public function abort($request = null, $response = null) if ($response === null) { $response = $this->response; } - throw new \Slim\Exception\NotFoundException($request, $response); + throw new HttpNotFoundException($request); } /** * Invoke action * - * @param string $action - * @param array $args - * @param array $options - * @return string|\Psr\Http\Message\ResponseInterface + * @param string $action + * @param array $args + * @return string|ResponseInterface + * @throws \Exception */ - public function __call($action, $args = []) + public function __call(string $action, array $args = []) { if (!method_exists($this, $action)) { throw new \Exception('Missing controller action: ' . static::class . ':' . $action); @@ -159,7 +167,7 @@ public function __call($action, $args = []) $request = $args[0]; $response = $args[1]; - $params = isset($args[2]) ? $args[2] : []; + $params = $args[2] ?? []; $attributes = $request->getAttributes(); $attributes['controller'] = static::classBasename(); @@ -186,8 +194,8 @@ public function __call($action, $args = []) /** * Return model * - * @param string $name - * @return \momentphp\Model|\momentphp\Registry + * @param string $name + * @return Model|Registry */ public function __get($name) { diff --git a/src/Database.php b/src/Database.php old mode 100644 new mode 100755 index b54e6fa..014a67b --- a/src/Database.php +++ b/src/Database.php @@ -2,6 +2,10 @@ namespace momentphp; +use Illuminate\Database\Capsule\Manager; +use Illuminate\Database\ConnectionInterface; +use Illuminate\Events\Dispatcher; + /** * Database */ @@ -12,7 +16,7 @@ class Database /** * Capsule * - * @var \Illuminate\Database\Capsule\Manager + * @var Manager */ protected $capsule; @@ -26,7 +30,7 @@ class Database /** * Dispatcher * - * @var \Illuminate\Events\Dispatcher + * @var Dispatcher */ protected $eventsDispatcher; @@ -35,9 +39,9 @@ class Database * * @param array $options * @param boolean $debug - * @param null|\Illuminate\Events\Dispatcher $eventsDispatcher + * @param null|Dispatcher $eventsDispatcher */ - public function __construct($options = [], $debug = false, \Illuminate\Events\Dispatcher $eventsDispatcher = null) + public function __construct(array $options = [], bool $debug = false, ?Dispatcher $eventsDispatcher = null) { $this->options($options); $this->debug = $debug; @@ -47,12 +51,12 @@ public function __construct($options = [], $debug = false, \Illuminate\Events\Di /** * Return capsule * - * @return \Illuminate\Database\Capsule\Manager + * @return Manager */ - public function capsule() + public function capsule(): Manager { if ($this->capsule === null) { - $this->capsule = new \Illuminate\Database\Capsule\Manager; + $this->capsule = new Manager; if ($this->eventsDispatcher) { $this->capsule->setEventDispatcher($this->eventsDispatcher); @@ -74,10 +78,10 @@ public function capsule() /** * Return connection * - * @param null|string $name - * @return \Illuminate\Database\ConnectionInterface + * @param string|null $name + * @return ConnectionInterface */ - public function connection($name = null) + public function connection(?string $name = null): ConnectionInterface { if ($name === null) { if (!$this->options('default')) { @@ -97,7 +101,7 @@ public function connection($name = null) * * @return array */ - public function queryLog() + public function queryLog(): array { $queryLog = []; if ($this->options('connections')) { @@ -117,14 +121,13 @@ public function queryLog() /** * Return connection status * - * @param null|string $name - * @return false|\Illuminate\Database\ConnectionInterface + * @param string|null $name + * @return false|ConnectionInterface */ - public function connectionStatus($name = null) + public function connectionStatus(string $name = null) { try { - $connection = $this->connection($name); - return $connection; + return $this->connection($name); } catch (\Exception $e) { return false; } diff --git a/src/DebugInfo.php b/src/DebugInfo.php old mode 100644 new mode 100755 index 24a68d7..50e3f04 --- a/src/DebugInfo.php +++ b/src/DebugInfo.php @@ -2,6 +2,8 @@ namespace momentphp; +use Psr\Container\ContainerInterface; + /** * DebugInfo */ @@ -12,9 +14,9 @@ class DebugInfo /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container */ - public function __construct(\Interop\Container\ContainerInterface $container) + public function __construct(ContainerInterface $container) { $this->container($container); } @@ -22,10 +24,10 @@ public function __construct(\Interop\Container\ContainerInterface $container) /** * Return app debug info * - * @param null|string $key + * @param string|null $key * @return array */ - public function get($key = null) + public function get(?string $key = null): array { $info = []; @@ -41,7 +43,7 @@ public function get($key = null) $info['env'] = [ 'title' => '$app→env', 'description' => 'Environment', - 'value' => $this->container()->get('env'), + 'value' => $this->container()->get('env'), ]; } @@ -129,7 +131,7 @@ public function get($key = null) * * @return array */ - protected function getConfig() + protected function getConfig(): array { $c = $this->container()->get('config'); foreach ($c->files() as $file) { diff --git a/src/Error.php b/src/Error.php old mode 100644 new mode 100755 index 54a913a..1db6ab5 --- a/src/Error.php +++ b/src/Error.php @@ -2,6 +2,9 @@ namespace momentphp; +use Psr\Container\ContainerInterface; +use Psr\Http\Message\ResponseInterface; + /** * Error */ @@ -12,9 +15,9 @@ class Error /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container */ - public function __construct(\Interop\Container\ContainerInterface $container) + public function __construct(ContainerInterface $container) { $this->container($container); } @@ -22,7 +25,7 @@ public function __construct(\Interop\Container\ContainerInterface $container) /** * Register framework error handlers */ - public function register() + public function register(): void { $container = $this->container(); @@ -54,8 +57,9 @@ public function register() * @param string $file * @param int $line * @param array $context + * @throws \ErrorException */ - public function handleError($level, $message, $file = '', $line = 0, $context = []) + public function handleError(int $level, string $message, string $file = '', int $line = 0, array $context = []): void { if (error_reporting() & $level) { throw new \ErrorException($message, 0, $level, $file, $line); @@ -65,10 +69,10 @@ public function handleError($level, $message, $file = '', $line = 0, $context = /** * Handle an uncaught exception from the app * - * @param \Throwable $e - * @return void|\Psr\Http\Message\ResponseInterface + * @param \Throwable $e + * @return void|ResponseInterface */ - public function handleException($e) + public function handleException(\Throwable $e) { $handler = $this->container->get('exceptionHandler'); $handler->report($e); @@ -76,16 +80,16 @@ public function handleException($e) if ($this->container()->has('console') && $this->container()->get('console')) { echo $handler->renderForConsole($e); exit(1); - } else { - $response = $handler->renderHttpResponse($e); - return $this->container()->get('app')->respond($response); } + + $response = $handler->renderHttpResponse($e); + return $this->container()->get('app')->respond($response); } /** * Shutdown function */ - public function handleShutdown() + public function handleShutdown(): void { $error = error_get_last(); if (!is_array($error)) { @@ -108,11 +112,11 @@ public function handleShutdown() /** * Determine if the error type is fatal * - * @param int $type + * @param int $type * @return bool */ - protected function isFatal($type) + protected function isFatal(int $type): bool { - return in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE, E_USER_ERROR]); + return in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE, E_USER_ERROR], true); } } diff --git a/src/ExceptionHandler.php b/src/ExceptionHandler.php old mode 100644 new mode 100755 index a473af3..f4d705e --- a/src/ExceptionHandler.php +++ b/src/ExceptionHandler.php @@ -2,6 +2,19 @@ namespace momentphp; +use Psr\Container\ContainerInterface; +use Psr\Http\Message\ResponseInterface; +use Psr\Log\LogLevel; +use Slim\Exception\HttpException; +use Slim\Exception\HttpMethodNotAllowedException; +use Slim\Exception\HttpNotFoundException; +use Whoops\Handler\HandlerInterface; +use Whoops\Handler\JsonResponseHandler; +use Whoops\Handler\PlainTextHandler; +use Whoops\Handler\PrettyPageHandler; +use Whoops\Handler\XmlResponseHandler; +use Whoops\Run; + /** * ExceptionHandler */ @@ -12,9 +25,9 @@ class ExceptionHandler /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container */ - public function __construct(\Interop\Container\ContainerInterface $container) + public function __construct(ContainerInterface $container) { $this->container($container); } @@ -22,70 +35,66 @@ public function __construct(\Interop\Container\ContainerInterface $container) /** * Render exception for CLI * - * @param \Throwable $e + * @param \Throwable $e * @return string */ - public function renderForConsole($e) + public function renderForConsole(\Throwable $e): string { $whoops = $this->whoops(); - $whoops->pushHandler(new \Whoops\Handler\PlainTextHandler); + $whoops->pushHandler(new PlainTextHandler); return $whoops->handleException($e); } /** * Render http response for given exception * - * @param \Throwable $e - * @return \Psr\Http\Message\ResponseInterface + * @param \Throwable $e + * @return ResponseInterface */ - public function renderHttpResponse($e) + public function renderHttpResponse(\Throwable $e): ResponseInterface { - if ($this->container()->has('debug')) { - if ($this->container()->get('debug')) { - $whoops = $this->whoops(); - $whoops->pushHandler($this->whoopsHandler($e)); - return $this->container->get('response')->write($whoops->handleException($e))->withStatus(500); - } + if ($this->container()->has('debug') && $this->container()->get('debug')) { + $whoops = $this->whoops(); + $whoops->pushHandler($this->whoopsHandler($e)); + return $this->container->get('response')->write($whoops->handleException($e))->withStatus(500); } $errorController = $this->container()->get('registry')->load('ErrorController'); - if ($e instanceof \Slim\Exception\NotFoundException) { + if ($e instanceof HttpNotFoundException) { return $errorController - ->notFound($e->getRequest(), $e->getResponse()) - ->withStatus(404); + ->notFound($e->getRequest()) + ->withStatus(404); } - if ($e instanceof \Slim\Exception\MethodNotAllowedException) { + if ($e instanceof HttpMethodNotAllowedException) { return $errorController - ->notAllowed($e->getRequest(), $e->getResponse(), $e->getAllowedMethods()) - ->withStatus(405) - ->withHeader('Allow', implode(', ', $e->getAllowedMethods())); + ->notAllowed($e->getRequest(), $e->getAllowedMethods()) + ->withStatus(405) + ->withHeader('Allow', implode(', ', $e->getAllowedMethods())); } - if ($e instanceof \Slim\Exception\SlimException) { + if ($e instanceof HttpException) { $request = $e->getRequest(); - $response = $e->getResponse(); } else { $request = $this->container()->get('request'); - $response = $this->container()->get('response'); } - return $errorController->error($request, $response, [$e])->withStatus(500); + return $errorController->error($request, [$e])->withStatus(500); } /** * Return correct Whoops handler * - * @param \Throwable $e - * @return \Whoops\Handler\HandlerInterface + * @param \Throwable $e + * @return HandlerInterface */ - protected function whoopsHandler($e) + protected function whoopsHandler(\Throwable $e) { - $handler = new \Whoops\Handler\PrettyPageHandler; + $handler = new PrettyPageHandler; $handler->setPageTitle('Error'); - $request = ($e instanceof \Slim\Exception\SlimException) ? + $request = ($e instanceof HttpException) ? $e->getRequest() : $this->container()->get('request'); @@ -95,10 +104,10 @@ protected function whoopsHandler($e) switch ($request->getAttribute('mediaType')->getSubPart()) { case 'json': - $handler = new \Whoops\Handler\JsonResponseHandler; + $handler = new JsonResponseHandler; break; case 'xml': - $handler = new \Whoops\Handler\XmlResponseHandler; + $handler = new XmlResponseHandler; break; } return $handler; @@ -107,11 +116,11 @@ protected function whoopsHandler($e) /** * Return prepared Whoops instance * - * @return \Whoops\Run + * @return Run */ - protected function whoops() + protected function whoops(): Run { - $whoops = new \Whoops\Run; + $whoops = new Run; $whoops->allowQuit(false); $whoops->writeToOutput(false); return $whoops; @@ -122,7 +131,7 @@ protected function whoops() * * @param \Throwable $e */ - public function report($e) + public function report(\Throwable $e): void { if (!$this->container->has('log')) { return; @@ -134,23 +143,21 @@ public function report($e) $options = $this->container->get('config')->get('app.error', []); } - if (isset($options['skip']) && is_array($options['skip'])) { - if (in_array(get_class($e), $options['skip'])) { - return; - } + if (isset($options['skip']) && is_array($options['skip']) && in_array(get_class($e), $options['skip'], true)) { + return; } $log = $this->container->get('log'); if (isset($options['logger']) && $options['logger'] === false) { return; - } else { - $log = $log->logger($options['logger']); } + $log = $log->logger($options['logger']); + $code = (method_exists($e, 'getSeverity')) ? $e->getSeverity() : E_ERROR; $map = $this->defaultErrorLevelMap(); - $level = isset($map[$code]) ? $map[$code] : \Psr\Log\LogLevel::CRITICAL; + $level = $map[$code] ?? LogLevel::CRITICAL; $message = $e->getMessage(); if (empty($message)) { @@ -171,34 +178,34 @@ public function report($e) * * @return array */ - public function defaultErrorLevelMap() + public function defaultErrorLevelMap(): array { return [ - E_ERROR => \Psr\Log\LogLevel::CRITICAL, - E_WARNING => \Psr\Log\LogLevel::WARNING, - E_PARSE => \Psr\Log\LogLevel::ALERT, - E_NOTICE => \Psr\Log\LogLevel::NOTICE, - E_CORE_ERROR => \Psr\Log\LogLevel::CRITICAL, - E_CORE_WARNING => \Psr\Log\LogLevel::WARNING, - E_COMPILE_ERROR => \Psr\Log\LogLevel::ALERT, - E_COMPILE_WARNING => \Psr\Log\LogLevel::WARNING, - E_USER_ERROR => \Psr\Log\LogLevel::ERROR, - E_USER_WARNING => \Psr\Log\LogLevel::WARNING, - E_USER_NOTICE => \Psr\Log\LogLevel::NOTICE, - E_STRICT => \Psr\Log\LogLevel::NOTICE, - E_RECOVERABLE_ERROR => \Psr\Log\LogLevel::ERROR, - E_DEPRECATED => \Psr\Log\LogLevel::NOTICE, - E_USER_DEPRECATED => \Psr\Log\LogLevel::NOTICE, + E_ERROR => LogLevel::CRITICAL, + E_WARNING => LogLevel::WARNING, + E_PARSE => LogLevel::ALERT, + E_NOTICE => LogLevel::NOTICE, + E_CORE_ERROR => LogLevel::CRITICAL, + E_CORE_WARNING => LogLevel::WARNING, + E_COMPILE_ERROR => LogLevel::ALERT, + E_COMPILE_WARNING => LogLevel::WARNING, + E_USER_ERROR => LogLevel::ERROR, + E_USER_WARNING => LogLevel::WARNING, + E_USER_NOTICE => LogLevel::NOTICE, + E_STRICT => LogLevel::NOTICE, + E_RECOVERABLE_ERROR => LogLevel::ERROR, + E_DEPRECATED => LogLevel::NOTICE, + E_USER_DEPRECATED => LogLevel::NOTICE, ]; } /** * Return error code as string * - * @param const $code + * @param $code * @return string */ - public function codeToString($code) + public function codeToString($code): string { switch ($code) { case E_ERROR: diff --git a/src/FlashMessages.php b/src/FlashMessages.php old mode 100644 new mode 100755 index 259bcb4..1944ef1 --- a/src/FlashMessages.php +++ b/src/FlashMessages.php @@ -2,6 +2,8 @@ namespace momentphp; +use ArrayAccess; + /** * FlashMessages */ @@ -12,7 +14,7 @@ class FlashMessages /** * View * - * @var \momentphp\View + * @var View */ protected $view; @@ -46,13 +48,13 @@ class FlashMessages /** * Constructor * - * @param \momentphp\View $view + * @param View $view * @param null|array|ArrayAccess &$storage */ public function __construct(View $view, &$storage = null) { $this->view = $view; - if (is_array($storage) || $storage instanceof \ArrayAccess) { + if (is_array($storage) || $storage instanceof ArrayAccess) { $this->storage = &$storage; } elseif (is_null($storage)) { if (!isset($_SESSION)) { @@ -73,7 +75,7 @@ public function __construct(View $view, &$storage = null) * @param string $message * @param array $options */ - public function set($message, $options = []) + public function set(string $message, array $options = []) { $options += $this->options(); $messages = []; @@ -93,10 +95,10 @@ public function set($message, $options = []) /** * Render flash messages under given key * - * @param string $key - * @return string + * @param string $key + * @return string|null */ - public function render($key = 'flash') + public function render(string $key = 'flash'): ?string { if (!isset($this->storage[$this->storageKey][$key])) { return null; @@ -117,7 +119,7 @@ public function render($key = 'flash') * @param string $method * @param array $args */ - public function __call($method, $args = []) + public function __call(string $method, array $args = []) { $template = $method; if (count($args) < 1) { diff --git a/src/Helper.php b/src/Helper.php old mode 100644 new mode 100755 index 295eab9..a20d577 --- a/src/Helper.php +++ b/src/Helper.php @@ -2,6 +2,8 @@ namespace momentphp; +use Psr\Container\ContainerInterface; + /** * Helper */ @@ -21,10 +23,11 @@ abstract class Helper /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container + * @param Template $template * @param array $options */ - public function __construct(\Interop\Container\ContainerInterface $container, Template $template, $options = []) + public function __construct(ContainerInterface $container, Template $template, array $options = []) { $this->container($container); $this->template = $template; diff --git a/src/Log.php b/src/Log.php old mode 100644 new mode 100755 index c7d67a6..d1823ea --- a/src/Log.php +++ b/src/Log.php @@ -2,6 +2,8 @@ namespace momentphp; +use Monolog\Logger; + /** * Log */ @@ -15,7 +17,7 @@ class Log * * @param array $options */ - public function __construct($options = []) + public function __construct(array $options = []) { $this->options($options); } @@ -23,13 +25,14 @@ public function __construct($options = []) /** * Construct new logger * - * @param string $name - * @param array $options - * @return \Monolog\Logger + * @param string $name + * @param array $options + * @return Logger + * @throws \ReflectionException */ - public function factory($name, $options = []) + public function factory(string $name, array $options = []): Logger { - $logger = new \Monolog\Logger($name); + $logger = new Logger($name); foreach ($options['handlers'] as $handler) { if (is_object($handler)) { $logger->pushHandler($handler); @@ -47,12 +50,13 @@ public function factory($name, $options = []) /** * Get logger by name * - * @param null|string $name - * @return \Monolog\Logger + * @param string|null $name + * @return Logger + * @throws \ReflectionException */ - public function logger($name = null) + public function logger(string $name = null): Logger { - $name = ($name === null) ? $this->options('default') : $name; + $name = $name ?? $this->options('default'); if (!$this->collection()->has($name)) { $options = $this->options('loggers.' . $name); if (!$options) { @@ -67,11 +71,12 @@ public function logger($name = null) /** * Proxy calls to the default logger * - * @param string $method - * @param array $args + * @param string $method + * @param array $args * @return mixed + * @throws \ReflectionException */ - public function __call($method, $args) + public function __call(string $method, array $args) { return call_user_func_array([$this->logger(), $method], $args); } diff --git a/src/Middleware.php b/src/Middleware.php old mode 100644 new mode 100755 index b40a1f9..8dc2dbf --- a/src/Middleware.php +++ b/src/Middleware.php @@ -2,6 +2,10 @@ namespace momentphp; +use Psr\Container\ContainerInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + /** * Middleware */ @@ -14,10 +18,10 @@ abstract class Middleware /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container * @param array $options */ - public function __construct(\Interop\Container\ContainerInterface $container, $options = []) + public function __construct(ContainerInterface $container, array $options = []) { $this->container($container); $this->options($options); @@ -26,10 +30,10 @@ public function __construct(\Interop\Container\ContainerInterface $container, $o /** * Invoke middleware * - * @param \Psr\Http\Message\RequestInterface $request - * @param \Psr\Http\Message\ResponseInterface $response - * @param callable $next - * @return \Psr\Http\Message\ResponseInterface + * @param RequestInterface $request + * @param ResponseInterface $response + * @param callable $next + * @return ResponseInterface */ - abstract public function __invoke($request, $response, $next); + abstract public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface; } diff --git a/src/Model.php b/src/Model.php old mode 100644 new mode 100755 index c3cbf9c..9132b18 --- a/src/Model.php +++ b/src/Model.php @@ -2,6 +2,9 @@ namespace momentphp; +use Illuminate\Database\ConnectionInterface; +use Psr\Container\ContainerInterface; + /** * Model */ @@ -21,10 +24,10 @@ abstract class Model /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container * @param array $options */ - public function __construct(\Interop\Container\ContainerInterface $container, $options = []) + public function __construct(ContainerInterface $container, array $options = []) { $this->container($container); $this->options($options); @@ -35,10 +38,10 @@ public function __construct(\Interop\Container\ContainerInterface $container, $o /** * Return connection * - * @param null|string $connectionName - * @return \Illuminate\Database\ConnectionInterface + * @param string|null $connectionName + * @return ConnectionInterface */ - public function db($connectionName = null) + public function db(string $connectionName = null): ConnectionInterface { if ($connectionName === null) { $connectionName = $this->connection; @@ -56,7 +59,7 @@ public function db($connectionName = null) * * @return array */ - public function implementedEvents() + public function implementedEvents(): array { return [ "model.{static::classPrefix()}.initialize" => 'initialize' @@ -66,7 +69,7 @@ public function implementedEvents() /** * Model callback invoked just after model construction */ - public function initialize() + public function initialize(): void { } @@ -75,7 +78,7 @@ public function initialize() * * @return string */ - public function objectKey() + public function objectKey(): string { return get_class($this) . serialize($this->options()); } @@ -83,10 +86,10 @@ public function objectKey() /** * Return model * - * @param string $name - * @return \momentphp\Model|\momentphp\Registry + * @param string $name + * @return Model|Registry */ - public function __get($name) + public function __get(string $name) { return $this->container()->has('registry') ? $this->container()->get('registry')->models->{$name} : $this->{$name}; } diff --git a/src/ObjectCache.php b/src/ObjectCache.php old mode 100644 new mode 100755 index b86312c..246f953 --- a/src/ObjectCache.php +++ b/src/ObjectCache.php @@ -27,7 +27,7 @@ class ObjectCache * @param object $store * @param array $options */ - public function __invoke($object, $store, $options) + public function __invoke(object $object, object $store, array $options) { $this->ocOptions = array_replace_recursive($this->ocOptions, $options); $this->ocOptions['object'] = $object; @@ -37,18 +37,19 @@ public function __invoke($object, $store, $options) /** * Call and cache a class method * - * @param string $method - * @param array $args + * @param string $method + * @param array $args * @return mixed + * @throws \Exception */ - public function ocCall($method, $args = []) + public function ocCall(string $method, array $args = []) { $callback = [$this->ocOptions['object'], $method]; $cache = $this->ocOptions['enabled']; if ($cache) { - $cache = !in_array($method, $this->ocOptions['nonCacheMethods']); + $cache = !in_array($method, $this->ocOptions['nonCacheMethods'], true); } else { - $cache = in_array($method, $this->ocOptions['cacheMethods']); + $cache = in_array($method, $this->ocOptions['cacheMethods'], true); } if (!$cache) { if ($args) { @@ -58,18 +59,20 @@ public function ocCall($method, $args = []) } $key = $this->ocCacheKey($callback, $args); - $ttl = (isset($this->ocOptions['ttlMap'][$method])) ? - $this->ocOptions['ttlMap'][$method] : - $this->ocOptions['ttl']; + $ttl = $this->ocOptions['ttlMap'][$method] ?? $this->ocOptions['ttl']; - $value = $this->ocOptions['store']->remember($key, $ttl, function () use ($callback, $args) { - if ($args) { - $ret = call_user_func_array($callback, $args); - } else { - $ret = call_user_func($callback); + $value = $this->ocOptions['store']->remember( + $key, + $ttl, + function () use ($callback, $args) { + if ($args) { + $ret = call_user_func_array($callback, $args); + } else { + $ret = $callback(); + } + return $ret; } - return $ret; - }); + ); return $value; } @@ -77,11 +80,11 @@ public function ocCall($method, $args = []) /** * Return cache key * - * @param callback $callback - * @param array $args + * @param callback $callback + * @param array $args * @return string */ - protected function ocCacheKey($callback, $args = []) + protected function ocCacheKey(callable $callback, array $args = []): string { if (!method_exists($this->ocOptions['object'], 'objectKey')) { throw new \Exception('Object inside ObjectCache must implement objectKey() method'); @@ -94,10 +97,10 @@ protected function ocCacheKey($callback, $args = []) /** * Return arguments key * - * @param mixed $args + * @param mixed $args * @return string */ - protected function ocArgumentsKey($args) + protected function ocArgumentsKey($args): string { if (!$args) { return ''; @@ -109,11 +112,12 @@ protected function ocArgumentsKey($args) /** * Proxy calls to underlying object * - * @param string $method - * @param array $args + * @param string $method + * @param array $args * @return mixed + * @throws \Exception */ - public function __call($method, $args) + public function __call(string $method, array $args) { return $this->ocCall($method, $args); } diff --git a/src/Provider.php b/src/Provider.php old mode 100644 new mode 100755 index 5924522..601b4aa --- a/src/Provider.php +++ b/src/Provider.php @@ -2,6 +2,8 @@ namespace momentphp; +use Psr\Container\ContainerInterface; + /** * Provider */ @@ -14,10 +16,10 @@ abstract class Provider /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container * @param array $options */ - public function __construct(\Interop\Container\ContainerInterface $container, $options = []) + public function __construct(ContainerInterface $container, array $options = []) { $this->container($container); $this->options($options); diff --git a/src/Registry.php b/src/Registry.php old mode 100644 new mode 100755 index 39738d3..c518e30 --- a/src/Registry.php +++ b/src/Registry.php @@ -2,6 +2,9 @@ namespace momentphp; +use Illuminate\Support\Str; +use Psr\Container\ContainerInterface; + /** * Registry */ @@ -27,51 +30,53 @@ class Registry /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container */ - public function __construct(\Interop\Container\ContainerInterface $container) + public function __construct(ContainerInterface $container) { $this->container($container); - $this->factoryCallback(function ($class, $options) use ($container) { - $instance = new $class($container, $options); + $this->factoryCallback( + function ($class, $options) use ($container) { + $instance = new $class($container, $options); - if ($container->has('cache') && $container->has('objectCache') && isset($options['cache']) && is_array($options['cache'])) { - $cacheOptions = $options['cache']; - $store = $container->get('cache'); - if (isset($cacheOptions['store'])) { - $store = $store->store($cacheOptions['store']); - unset($cacheOptions['store']); - } - $nonCacheMethods = ['options']; - if (isset($cacheOptions['nonCacheMethods'])) { - foreach ($cacheOptions['nonCacheMethods'] as $method) { - if (!in_array($method, $nonCacheMethods)) { - $nonCacheMethods[] = $method; + if ($container->has('cache') && $container->has('objectCache') && isset($options['cache']) && is_array($options['cache'])) { + $cacheOptions = $options['cache']; + $store = $container->get('cache'); + if (isset($cacheOptions['store'])) { + $store = $store->store($cacheOptions['store']); + unset($cacheOptions['store']); + } + $nonCacheMethods = ['options']; + if (isset($cacheOptions['nonCacheMethods'])) { + foreach ($cacheOptions['nonCacheMethods'] as $method) { + if (!in_array($method, $nonCacheMethods, true)) { + $nonCacheMethods[] = $method; + } } } + $cacheOptions['nonCacheMethods'] = $nonCacheMethods; + $objectCache = clone $container->get('objectCache'); + $objectCache($instance, $store, $cacheOptions); + return $objectCache; } - $cacheOptions['nonCacheMethods'] = $nonCacheMethods; - $objectCache = clone $container->get('objectCache'); - $objectCache($instance, $store, $cacheOptions); - return $objectCache; - } - return $instance; - }); + return $instance; + } + ); } /** * Loads/constructs an object instance * - * @param string $name + * @param string $name * @return object + * @throws \Exception */ - public function load($name) + public function load(string $name): object { $key = $this->prefix($name); if ($this->collection()->has($key)) { - $instance = $this->collection()->get($key); - return $instance; + return $this->collection()->get($key); } if ($this->container()->has($key)) { $instance = $this->container()->get($key); @@ -85,11 +90,12 @@ public function load($name) /** * Return new instance * - * @param string $name - * @param array $options + * @param string $name + * @param array $options * @return object + * @throws \Exception */ - public function factory($name, $options = []) + public function factory(string $name, array $options = []): object { $key = $this->prefix($name); $class = $this->container()->get('app')->bundleClass($key); @@ -97,17 +103,16 @@ public function factory($name, $options = []) throw new \Exception('Class not found: ' . $class); } $factoryCallback = $this->factoryCallback(); - $instance = $factoryCallback($class, $options); - return $instance; + return $factoryCallback($class, $options); } /** * Factory callback getter/setter * - * @param null|callable $callback + * @param callable|null $callback * @return $this|\Closure */ - public function factoryCallback($callback = null) + public function factoryCallback(callable $callback = null) { if ($callback !== null) { $this->factoryCallback = $callback; @@ -119,10 +124,11 @@ public function factoryCallback($callback = null) /** * Return options from configuration * - * @param string $name + * @param string $name * @return array + * @throws \Exception */ - public function options($name) + public function options(string $name): array { $options = []; if ($this->container()->has('config')) { @@ -141,10 +147,10 @@ public function options($name) * * 'PostModel' -> 'models\PostModel' * - * @param string $name + * @param string $name * @return string */ - protected function prefix($name) + protected function prefix(string $name): string { $prefix = class_suffix($name, true); return $prefix . '\\' . $name; @@ -153,14 +159,14 @@ protected function prefix($name) /** * Loads/constructs an object instance * - * @param string $name + * @param string $name * @return object|$this */ - public function __get($name) + public function __get(string $name) { $this->path[] = $name; if (count($this->path) > 1) { - $suffix = ucfirst(str_singular($this->path[0])); + $suffix = ucfirst(Str::singular($this->path[0])); $name = implode('\\', array_slice($this->path, 1)) . $suffix; try { $instance = $this->load($name); @@ -176,10 +182,10 @@ public function __get($name) * Dynamic properties inside Twig templates * * @link http://twig.sensiolabs.org/doc/recipes.html#using-dynamic-object-properties - * @param string $name + * @param string $name * @return boolean */ - public function __isset($name) + public function __isset(string $name) { return true; } diff --git a/src/Router.php b/src/Router.php old mode 100644 new mode 100755 index eee0cf4..90ae1c5 --- a/src/Router.php +++ b/src/Router.php @@ -2,25 +2,11 @@ namespace momentphp; +use Slim\Routing\RouteCollector; + /** * Router */ -class Router extends \Slim\Router +class Router extends RouteCollector { - /** - * @return \FastRoute\Dispatcher - */ - protected function createDispatcher() - { - return $this->dispatcher ?: \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) { - foreach ($this->getRoutes() as $route) { - try { - $r->addRoute($route->getMethods(), $route->getPattern(), $route->getIdentifier()); - } catch (\FastRoute\BadRouteException $e) { - } - } - }, [ - 'routeParser' => $this->routeParser - ]); - } } diff --git a/src/Settings.php b/src/Settings.php old mode 100644 new mode 100755 index 1067c9c..a90ed18 --- a/src/Settings.php +++ b/src/Settings.php @@ -10,7 +10,7 @@ class Settings implements \ArrayAccess /** * Config * - * @var \momentphp\Config + * @var Config */ protected $config; @@ -25,8 +25,9 @@ class Settings implements \ArrayAccess * Constructor * * @param Config $config + * @param string $prefix */ - public function __construct(Config $config, $prefix) + public function __construct(Config $config, string $prefix) { $this->config = $config; $this->prefix = $prefix; @@ -35,10 +36,10 @@ public function __construct(Config $config, $prefix) /** * Return prefixed key * - * @param string $key + * @param string $key * @return string */ - protected function key($key) + protected function key(string $key): string { return $this->prefix . '.' . $key; } @@ -46,43 +47,43 @@ protected function key($key) /** * Determine if the given configuration option exists * - * @param string $key + * @param string $offset * @return bool */ - public function offsetExists($key) + public function offsetExists($offset) { - return $this->config->has($this->key($key)); + return $this->config->has($this->key($offset)); } /** * Get a configuration option * - * @param string $key + * @param string $offset * @return mixed */ - public function offsetGet($key) + public function offsetGet($offset) { - return $this->config->get($this->key($key)); + return $this->config->get($this->key($offset)); } /** * Set a configuration option * - * @param string $key + * @param string $offset * @param mixed $value */ - public function offsetSet($key, $value) + public function offsetSet($offset, $value) { - $this->config->set($this->key($key), $value); + $this->config->set($this->key($offset), $value); } /** * Unset a configuration option * - * @param string $key + * @param string $offset */ - public function offsetUnset($key) + public function offsetUnset($offset) { - $this->config->set($this->key($key), null); + $this->config->set($this->key($offset), null); } } diff --git a/src/SmartyViewEngine.php b/src/SmartyViewEngine.php deleted file mode 100644 index 4033a24..0000000 --- a/src/SmartyViewEngine.php +++ /dev/null @@ -1,86 +0,0 @@ -smarty = new \Smarty; - $this->smarty->error_reporting = E_ALL & ~E_NOTICE; - $this->smarty->escape_html = isset($options['autoescape']) ? $options['autoescape'] : false; - - $debug = isset($options['debug']) ? $options['debug'] : false; - - if ($debug) { - $this->smarty->force_compile = true; - } else { - $this->smarty->compile_check = false; - } - - if (!file_exists($options['compile'])) { - mkdir($options['compile'], 0777, true); - } - - $this->smarty->setTemplateDir($options['templates']); - $this->smarty->setCompileDir($options['compile']); - } - - /** - * Render template content - * - * @param string $template - * @param array $data - * @param null|string $bundle - * @return string - */ - public function render($template, $data = [], $bundle = null) - { - foreach ($data as $k => $v) { - $this->smarty->assign($k, $v); - } - return $this->smarty->fetch($this->template($template, $bundle)); - } - - /** - * Check if given template exists - * - * @param string $template - * @param null|string $bundle - * @return boolean - */ - public function exists($template, $bundle = null) - { - return $this->smarty->templateExists($this->template($template, $bundle)); - } - - /** - * Return template path - * - * @param string $template - * @param null|string $bundle - * @return string - */ - protected function template($template, $bundle = null) - { - if ($bundle !== null) { - $template = sprintf('[%s]', $bundle) . $template; - } - return $template . '.tpl'; - } -} diff --git a/src/Template.php b/src/Template.php old mode 100644 new mode 100755 index 2d7d041..5e5f860 --- a/src/Template.php +++ b/src/Template.php @@ -2,6 +2,11 @@ namespace momentphp; +use Psr\Container\ContainerInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; +use Slim\Psr7\Response; + /** * Template */ @@ -12,21 +17,21 @@ class Template /** * Helpers registry * - * @var \momentphp\Registry + * @var Registry */ public $registry; /** * Request * - * @var \Psr\Http\Message\RequestInterface + * @var RequestInterface */ public $request; /** * Response * - * @var \Psr\Http\Message\ResponseInterface + * @var ResponseInterface */ public $response; @@ -40,9 +45,9 @@ class Template /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container */ - public function __construct(\Interop\Container\ContainerInterface $container) + public function __construct(ContainerInterface $container) { $this->container($container); $this->registry = $this->prepareRegistry(); @@ -51,16 +56,18 @@ public function __construct(\Interop\Container\ContainerInterface $container) /** * Prepare helpers registry * - * @return \momentphp\Registry + * @return Registry */ - protected function prepareRegistry() + protected function prepareRegistry(): Registry { $registry = new Registry($this->container()); $container = $this->container(); $template = $this; - $registry->factoryCallback(function ($class, $options) use ($container, $template) { - return new $class($container, $template, $options); - }); + $registry->factoryCallback( + function ($class, $options) use ($container, $template) { + return new $class($container, $template, $options); + } + ); return $registry; } @@ -69,20 +76,20 @@ protected function prepareRegistry() * * @return string */ - public function cell() + public function cell(): string { $args = func_get_args(); $name = array_shift($args); $parts = explode(':', $name); if (count($parts) === 2) { - list($name, $action) = [$parts[0], $parts[1]]; + [$name, $action] = [$parts[0], $parts[1]]; } else { - list($name, $action) = [$parts[0], 'display']; + [$name, $action] = [$parts[0], 'display']; } $cell = $this->container()->get('registry')->load('cells\\' . $name . 'Controller'); - $response = $cell->{$action}($this->request->withAttribute('action', $action), new \Slim\Http\Response, $args); - if ($response instanceof \Psr\Http\Message\ResponseInterface) { - $response = (string) $response->getBody(); + $response = $cell->{$action}($this->request->withAttribute('action', $action), new Response, $args); + if ($response instanceof ResponseInterface) { + $response = (string)$response->getBody(); } return $response; } @@ -90,8 +97,8 @@ public function cell() /** * Allow `d()` inside templates * - * @param mixed $var - * @return string + * @param mixed $var + * @return false|string */ public function d($var) { @@ -101,10 +108,10 @@ public function d($var) /** * Return helper * - * @param string $name - * @return \momentphp\Helper|\momentphp\Registry + * @param string $name + * @return Helper|Registry */ - public function __get($name) + public function __get(string $name) { return $this->registry->helpers->{$name}; } @@ -113,10 +120,10 @@ public function __get($name) * Dynamic properties inside Twig templates * * @link http://twig.sensiolabs.org/doc/recipes.html#using-dynamic-object-properties - * @param string $name + * @param string $name * @return boolean */ - public function __isset($name) + public function __isset(string $name) { return true; } diff --git a/src/TwigViewEngine.php b/src/TwigViewEngine.php old mode 100644 new mode 100755 index 3402205..86a996f --- a/src/TwigViewEngine.php +++ b/src/TwigViewEngine.php @@ -2,15 +2,22 @@ namespace momentphp; +use momentphp\interfaces\ViewEngineInterface; +use Twig\Environment; +use Twig\Error\LoaderError; +use Twig\Error\RuntimeError; +use Twig\Error\SyntaxError; +use Twig\Loader\FilesystemLoader; + /** * TwigViewEngine */ -class TwigViewEngine implements \momentphp\interfaces\ViewEngineInterface +class TwigViewEngine implements ViewEngineInterface { /** * Twig * - * @var \Twig_Environment + * @var Environment */ public $twig; @@ -18,14 +25,15 @@ class TwigViewEngine implements \momentphp\interfaces\ViewEngineInterface * Constructor * * @param array $options + * @throws LoaderError */ - public function __construct($options = []) + public function __construct(array $options = []) { if (!file_exists($options['compile'])) { mkdir($options['compile'], 0777, true); } - $loader = new \Twig_Loader_Filesystem; + $loader = new FilesystemLoader; // register paths inside main namespace foreach ($options['templates'] as $namespace => $path) { if (file_exists($path)) { @@ -39,8 +47,8 @@ public function __construct($options = []) } } - $debug = isset($options['debug']) ? $options['debug'] : false; - $options['autoescape'] = isset($options['autoescape']) ? $options['autoescape'] : false; + $debug = $options['debug'] ?? false; + $options['autoescape'] = $options['autoescape'] ?? false; $environmentOptions = [ 'cache' => $options['compile'], @@ -48,18 +56,21 @@ public function __construct($options = []) 'debug' => $debug, ]; - $this->twig = new \Twig_Environment($loader, $environmentOptions); + $this->twig = new Environment($loader, $environmentOptions); } /** * Render template content * - * @param string $template - * @param array $data - * @param null|string $bundle + * @param string $template + * @param array $data + * @param string|null $bundle * @return string + * @throws LoaderError + * @throws RuntimeError + * @throws SyntaxError */ - public function render($template, $data = [], $bundle = null) + public function render(string $template, array $data = [], string $bundle = null): string { return $this->twig->render($this->template($template, $bundle), $data); } @@ -67,11 +78,11 @@ public function render($template, $data = [], $bundle = null) /** * Check if given template exists * - * @param string $template - * @param null|string $bundle + * @param string $template + * @param string|null $bundle * @return boolean */ - public function exists($template, $bundle = null) + public function exists(string $template, string $bundle = null): bool { return $this->twig->getLoader()->exists($this->template($template, $bundle)); } @@ -79,11 +90,11 @@ public function exists($template, $bundle = null) /** * Return template path * - * @param string $template - * @param null|string $bundle + * @param string $template + * @param string|null $bundle * @return string */ - protected function template($template, $bundle = null) + protected function template(string $template, string $bundle = null): string { if ($bundle !== null) { $template = '@' . $bundle . '/' . $template; diff --git a/src/View.php b/src/View.php old mode 100644 new mode 100755 index 37f3847..53fbdb6 --- a/src/View.php +++ b/src/View.php @@ -2,6 +2,11 @@ namespace momentphp; +use momentphp\interfaces\ViewEngineInterface; +use Psr\Container\ContainerInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + /** * View */ @@ -12,11 +17,10 @@ class View /** * Constructor * - * @param \Interop\Container\ContainerInterface $container - * @param array $options + * @param ContainerInterface $container * @param string $engine */ - public function __construct(\Interop\Container\ContainerInterface $container, $engine) + public function __construct(ContainerInterface $container, string $engine) { $this->container($container); $this->engine = $engine; @@ -32,7 +36,7 @@ public function __construct(\Interop\Container\ContainerInterface $container, $e ]; /** - * The name of the service implementing \momentphp\interfaces\ViewEngineInterface + * The name of the service implementing ViewEngineInterface * * @var string */ @@ -41,7 +45,7 @@ public function __construct(\Interop\Container\ContainerInterface $container, $e /** * View engine * - * @var \momentphp\interfaces\ViewEngineInterface + * @var ViewEngineInterface */ protected $viewEngine; @@ -76,25 +80,25 @@ public function __construct(\Interop\Container\ContainerInterface $container, $e /** * Request * - * @var \Psr\Http\Message\RequestInterface + * @var RequestInterface */ protected $request; /** * Response * - * @var \Psr\Http\Message\ResponseInterface + * @var ResponseInterface */ protected $response; /** * Save a variable or an associative array of variables for use inside a template * - * @param mixed $name - * @param mixed $value + * @param mixed $name + * @param mixed $value * @return $this */ - public function set($name, $value = null) + public function set($name, $value = null): View { if (is_array($name)) { if (is_array($value)) { @@ -112,16 +116,16 @@ public function set($name, $value = null) /** * Return view engine instance * - * @return \momentphp\interfaces\ViewEngineInterface + * @return ViewEngineInterface */ - public function viewEngine() + public function viewEngine(): ViewEngineInterface { if ($this->engine === null) { throw new \Exception('View engine service name not set'); } $viewEngine = $this->container()->get($this->engine); - if (!($viewEngine instanceof \momentphp\interfaces\ViewEngineInterface)) { - throw new \Exception('View engine must implement: ' . \momentphp\interfaces\ViewEngineInterface::class); + if (!($viewEngine instanceof ViewEngineInterface)) { + throw new \Exception('View engine must implement: ' . ViewEngineInterface::class); } return $viewEngine; } @@ -129,11 +133,12 @@ public function viewEngine() /** * Render template content * - * @param null|string $template - * @param null|string $bundle + * @param string|null $template + * @param string|null $bundle * @return string + * @throws \Exception */ - public function render($template = null, $bundle = null) + public function render(string $template = null, string $bundle = null): string { if ($template === null) { $template = $this->template; @@ -158,11 +163,12 @@ public function render($template = null, $bundle = null) /** * Check if given template exists * - * @param null|string $template - * @param null|string $bundle + * @param string|null $template + * @param string|null $bundle * @return boolean + * @throws \Exception */ - public function exists($template = null, $bundle = null) + public function exists(string $template = null, string $bundle = null): bool { if ($template === null) { $template = $this->template; @@ -176,12 +182,12 @@ public function exists($template = null, $bundle = null) /** * Return template path * - * @param string $template + * @param string $template * @return string */ - protected function path($template) + protected function path(string $template): string { - if (substr($template, 0, 1) === '/') { + if ($template[0] === '/') { return ltrim($template, '/'); } if ($this->templateFolder) { @@ -193,10 +199,11 @@ protected function path($template) /** * Return template path based on detected media type * - * @param string $template + * @param string $template * @return string + * @throws \Exception */ - protected function mediaTypeTemplate($template) + protected function mediaTypeTemplate(string $template): string { if ($this->request && $this->request->getAttribute('mediaType')) { $mediaTemplate = path([$this->request->getAttribute('mediaType')->getSubPart(), $template], '/'); @@ -208,23 +215,27 @@ protected function mediaTypeTemplate($template) /** * Universal getter/setter * - * @param string $method - * @param array $args + * @param string $method + * @param array $args * @return mixed + * @throws \Exception */ - public function __call($method, $args = []) + public function __call(string $method, array $args = []) { array_unshift($args, $method); $self = $this; - return call_user_func_array(function ($property, $value = null) use ($self) { - if (in_array($property, $self->guarded)) { - throw new \Exception('Unable to change property: ' . $property); - } - if ($value !== null) { - $self->{$property} = $value; - return $self; - } - return $self->{$property}; - }, $args); + return call_user_func_array( + function ($property, $value = null) use ($self) { + if (in_array($property, $self->guarded, true)) { + throw new \Exception('Unable to change property: ' . $property); + } + if ($value !== null) { + $self->{$property} = $value; + return $self; + } + return $self->{$property}; + }, + $args + ); } } diff --git a/src/exceptions/FatalErrorException.php b/src/exceptions/FatalErrorException.php old mode 100644 new mode 100755 index 1a28e0c..c62bac7 --- a/src/exceptions/FatalErrorException.php +++ b/src/exceptions/FatalErrorException.php @@ -64,7 +64,7 @@ public function __construct($message, $code, $severity, $filename, $lineno, $tra } } - protected function setTrace($trace) + protected function setTrace($trace): void { $traceReflector = new \ReflectionProperty('Exception', 'trace'); $traceReflector->setAccessible(true); diff --git a/src/helpers.php b/src/helpers.php old mode 100644 new mode 100755 index fc98bc6..6a51fdf --- a/src/helpers.php +++ b/src/helpers.php @@ -1,18 +1,21 @@ {$service}; + return App::getInstance()->{$service}; } } @@ -20,11 +23,11 @@ function app($service = null) /** * Return filesystem path * - * @param array $parts - * @param string $ds + * @param array $parts + * @param string $ds * @return string */ - function path($parts = [], $ds = DIRECTORY_SEPARATOR) + function path(array $parts = [], string $ds = DIRECTORY_SEPARATOR): string { return implode($ds, $parts); } @@ -34,11 +37,11 @@ function path($parts = [], $ds = DIRECTORY_SEPARATOR) /** * Dump variable using `symfony/var-dumper` * - * @param mixed $var - * @param bool $return - * @return void|string + * @param mixed $var + * @param bool $return + * @return false|string */ - function d($var, $return = false) + function d($var, bool $return = false) { if ($return === true) { ob_start(); @@ -53,11 +56,12 @@ function d($var, $return = false) /** * Return class namespace * - * @param string $class - * @param null|string $append + * @param string $class + * @param string|null $append * @return string + * @throws ReflectionException */ - function class_namespace($class, $append = null) + function class_namespace(string $class, string $append = null): string { $reflector = new \ReflectionClass($class); $namespaceName = $reflector->getNamespaceName(); @@ -72,11 +76,12 @@ function class_namespace($class, $append = null) /** * Return class filesystem path * - * @param string $class - * @param null|string $append + * @param string $class + * @param string|null $append * @return string + * @throws ReflectionException */ - function class_path($class, $append = null) + function class_path(string $class, string $append = null): string { $reflector = new \ReflectionClass($class); $basePath = dirname($reflector->getFileName()); @@ -95,11 +100,11 @@ function class_path($class, $append = null) * 'TestController' -> 'tests' (pluralize enabled) * 'Controller' -> '' * - * @param string $class - * @param boolean $pluralize + * @param string $class + * @param boolean $pluralize * @return string */ - function class_prefix($class, $pluralize = false) + function class_prefix(string $class, bool $pluralize = false): string { return class_part($class, 'prefix', $pluralize); } @@ -113,11 +118,11 @@ function class_prefix($class, $pluralize = false) * 'TestController' -> 'controllers' (pluralize enabled) * 'Controller' => 'Controller' * - * @param string $class - * @param boolean $pluralize + * @param string $class + * @param boolean $pluralize * @return string */ - function class_suffix($class, $pluralize = false) + function class_suffix(string $class, bool $pluralize = false): string { return class_part($class, 'suffix', $pluralize); } @@ -127,20 +132,20 @@ function class_suffix($class, $pluralize = false) /** * Return class part * - * @param string $class - * @param string $type - * @param boolean $pluralize + * @param string $class + * @param string $type + * @param boolean $pluralize * @return string */ - function class_part($class, $type, $pluralize = false) + function class_part(string $class, string $type, bool $pluralize = false): string { $classBasename = class_basename($class); - $classArr = explode('_', \Illuminate\Support\Str::snake($classBasename)); + $classArr = explode('_', Str::snake($classBasename)); $suffix = ucfirst(array_pop($classArr)); - $prefix = ucfirst(\Illuminate\Support\Str::camel(implode('_', $classArr))); + $prefix = ucfirst(Str::camel(implode('_', $classArr))); $result = $$type; if ($pluralize) { - $result = lcfirst(\Illuminate\Support\Str::plural($result)); + $result = lcfirst(Str::plural($result)); } return $result; } @@ -150,10 +155,11 @@ function class_part($class, $type, $pluralize = false) /** * Return class config key * - * @param string $class + * @param string $class * @return string + * @throws ReflectionException */ - function class_config_key($class) + function class_config_key(string $class): string { $namespaceArr = explode('\\', class_namespace($class)); $found = false; @@ -183,11 +189,11 @@ function class_config_key($class) /** * Gets the value of an environment variable - supports boolean, empty and null * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return mixed */ - function env($key, $default = null) + function env(string $key, $default = null) { $value = getenv($key); @@ -213,7 +219,7 @@ function env($key, $default = null) return; } - if (strlen($value) > 1 && \Illuminate\Support\Str::startsWith($value, '"') && \Illuminate\Support\Str::endsWith($value, '"')) { + if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) { return substr($value, 1, -1); } diff --git a/src/interfaces/ViewEngineInterface.php b/src/interfaces/ViewEngineInterface.php old mode 100644 new mode 100755 index 38d5a89..f364de6 --- a/src/interfaces/ViewEngineInterface.php +++ b/src/interfaces/ViewEngineInterface.php @@ -10,19 +10,19 @@ interface ViewEngineInterface /** * Render template content * - * @param string $template - * @param array $data - * @param string|null $bundle + * @param string $template + * @param array $data + * @param string|null $bundle * @return string */ - public function render($template, $data = [], $bundle = null); + public function render(string $template, array $data = [], string $bundle = null): string; /** * Check if given template exists * - * @param string $template - * @param string|null $bundle + * @param string $template + * @param string|null $bundle * @return boolean */ - public function exists($template, $bundle = null); + public function exists(string $template, string $bundle = null): bool; } diff --git a/src/middlewares/AssetsMiddleware.php b/src/middlewares/AssetsMiddleware.php old mode 100644 new mode 100755 index 4e8ca11..d9912e5 --- a/src/middlewares/AssetsMiddleware.php +++ b/src/middlewares/AssetsMiddleware.php @@ -2,22 +2,27 @@ namespace momentphp\middlewares; +use momentphp\Middleware; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; +use Slim\Psr7\Factory\StreamFactory; + /** * AssetMiddleware */ -class AssetsMiddleware extends \momentphp\Middleware +class AssetsMiddleware extends Middleware { /** * Invoke middleware * - * @param \Psr\Http\Message\RequestInterface $request - * @param \Psr\Http\Message\ResponseInterface $response + * @param RequestInterface $request + * @param ResponseInterface $response * @param callable $next - * @return \Psr\Http\Message\ResponseInterface + * @return ResponseInterface */ - public function __invoke($request, $response, $next) + public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface { - if (!$request->isGet()) { + if ($request->getMethod() === 'GET') { return $next($request, $response); } $path = $request->getUri()->getPath(); @@ -38,17 +43,17 @@ public function __invoke($request, $response, $next) return $next($request, $response); } return $response->withStatus(200)->withHeader('Content-Type', $this->mimeType($file))->withBody( - new \Slim\Http\Body(fopen($file, 'r')) + (new StreamFactory())->createStreamFromFile($file) ); } /** * Return file mime type * - * @param string $filename + * @param string $file * @return string */ - protected function mimeType($file) + protected function mimeType(string $file): string { $mimeTypes = [ 'txt' => 'text/plain', @@ -108,13 +113,15 @@ protected function mimeType($file) $ext = strtolower(array_pop($fileArr)); if (array_key_exists($ext, $mimeTypes)) { return $mimeTypes[$ext]; - } elseif (function_exists('finfo_open')) { + } + + if (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME); $mimeType = finfo_file($finfo, $file); finfo_close($finfo); return $mimeType; - } else { - return 'application/octet-stream'; } + + return 'application/octet-stream'; } } diff --git a/src/middlewares/NegotiationMiddleware.php b/src/middlewares/NegotiationMiddleware.php old mode 100644 new mode 100755 index 36352c3..c249d98 --- a/src/middlewares/NegotiationMiddleware.php +++ b/src/middlewares/NegotiationMiddleware.php @@ -2,45 +2,53 @@ namespace momentphp\middlewares; +use momentphp\Middleware; +use Negotiation\Accept; +use Negotiation\Negotiator; +use Psr\Container\ContainerInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + /** * BundleAssetMiddleware */ -class NegotiationMiddleware extends \momentphp\Middleware +class NegotiationMiddleware extends Middleware { /** * Negotiator * - * @var \Negotiation\Negotiator + * @var Negotiator */ protected $negotiator; /** * Constructor * - * @param \Interop\Container\ContainerInterface $container + * @param ContainerInterface $container * @param array $options */ - public function __construct(\Interop\Container\ContainerInterface $container, $options = []) + public function __construct(ContainerInterface $container, array $options = []) { parent::__construct($container, $options); - $this->negotiator = new \Negotiation\Negotiator; + $this->negotiator = new Negotiator; } /** * Invoke middleware * - * @param \Psr\Http\Message\RequestInterface $request - * @param \Psr\Http\Message\ResponseInterface $response + * @param RequestInterface $request + * @param ResponseInterface $response * @param callable $next - * @return \Psr\Http\Message\ResponseInterface + * @return ResponseInterface + * @throws \Negotiation\Exception\Exception */ - public function __invoke($request, $response, $next) + public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface { $acceptHeader = $request->getHeaderLine('accept'); if (!empty($acceptHeader)) { $mediaType = $this->negotiator->getBest($acceptHeader, $this->priorities()); } else { - $mediaType = new \Negotiation\Accept($this->priorities()[0]); + $mediaType = new Accept($this->priorities()[0]); } if (!$mediaType) { return $next($request, $response); @@ -55,7 +63,7 @@ public function __invoke($request, $response, $next) * * @return array */ - protected function priorities() + protected function priorities(): array { return $this->options('mediaType'); } diff --git a/src/providers/SmartyProvider.php b/src/providers/SmartyProvider.php deleted file mode 100644 index fc48da6..0000000 --- a/src/providers/SmartyProvider.php +++ /dev/null @@ -1,23 +0,0 @@ -options(); - if ($this->container()->has('debug')) { - $options['debug'] = $this->container()->get('debug'); - } - $this->container()->get('app')->service('smarty', function () use ($options) { - return new \momentphp\SmartyViewEngine($options); - }); - } -} diff --git a/src/providers/TwigProvider.php b/src/providers/TwigProvider.php old mode 100644 new mode 100755 index 8309e40..b7a50fd --- a/src/providers/TwigProvider.php +++ b/src/providers/TwigProvider.php @@ -2,13 +2,18 @@ namespace momentphp\providers; +use momentphp\Provider; +use momentphp\TwigViewEngine; +use Twig\Error\LoaderError; + /** * TwigProvider */ -class TwigProvider extends \momentphp\Provider +class TwigProvider extends Provider { /** * Register service + * @throws LoaderError */ public function __invoke() { @@ -16,8 +21,11 @@ public function __invoke() if ($this->container()->has('debug')) { $options['debug'] = $this->container()->get('debug'); } - $this->container()->get('app')->service('twig', function () use ($options) { - return new \momentphp\TwigViewEngine($options); - }); + $this->container()->get('app')->service( + 'twig', + function () use ($options) { + return new TwigViewEngine($options); + } + ); } } diff --git a/src/traits/ClassTrait.php b/src/traits/ClassTrait.php old mode 100644 new mode 100755 index f1e9957..e0903d4 --- a/src/traits/ClassTrait.php +++ b/src/traits/ClassTrait.php @@ -10,10 +10,11 @@ trait ClassTrait /** * Proxy call to `class_namespace()` * - * @param string $append + * @param string|null $append * @return string + * @throws \ReflectionException */ - public static function classNamespace($append = null) + public static function classNamespace(string $append = null): string { return class_namespace(static::class, $append); } @@ -21,10 +22,11 @@ public static function classNamespace($append = null) /** * Proxy call to `class_path()` * - * @param string $append + * @param string|null $append * @return string + * @throws \ReflectionException */ - public static function classPath($append = null) + public static function classPath(string $append = null): string { return class_path(static::class, $append); } @@ -32,10 +34,10 @@ public static function classPath($append = null) /** * Proxy call to `class_prefix()` * - * @param bool $pluralize + * @param bool $pluralize * @return string */ - public static function classPrefix($pluralize = false) + public static function classPrefix(bool $pluralize = false): string { return class_prefix(static::class, $pluralize); } @@ -43,10 +45,10 @@ public static function classPrefix($pluralize = false) /** * Proxy call to `class_suffix()` * - * @param bool $pluralize + * @param bool $pluralize * @return string */ - public static function classSuffix($pluralize = false) + public static function classSuffix(bool $pluralize = false): string { return class_suffix(static::class, $pluralize); } @@ -54,11 +56,11 @@ public static function classSuffix($pluralize = false) /** * Proxy call to `class_part()` * - * @param string $type - * @param bool $pluralize + * @param string $type + * @param bool $pluralize * @return string */ - public static function classPart($type, $pluralize = false) + public static function classPart(string $type, bool $pluralize = false): string { return class_part(static::class, $type, $pluralize); } @@ -67,8 +69,9 @@ public static function classPart($type, $pluralize = false) * Proxy call to `class_config_key()` * * @return string + * @throws \ReflectionException */ - public static function classConfigKey() + public static function classConfigKey(): string { return class_config_key(static::class); } @@ -78,7 +81,7 @@ public static function classConfigKey() * * @return string */ - public static function classBasename() + public static function classBasename(): string { return class_basename(static::class); } diff --git a/src/traits/CollectionTrait.php b/src/traits/CollectionTrait.php old mode 100644 new mode 100755 index 6f9fc2d..213975d --- a/src/traits/CollectionTrait.php +++ b/src/traits/CollectionTrait.php @@ -2,6 +2,8 @@ namespace momentphp\traits; +use Illuminate\Support\Collection; + /** * CollectionTrait */ @@ -10,15 +12,15 @@ trait CollectionTrait /** * Collection * - * @var \Illuminate\Support\Collection + * @var Collection */ protected $collection; /** * Collection getter/setter * - * @param \Illuminate\Support\Collection|null $collection - * @return \Illuminate\Support\Collection|object + * @param Collection|null $collection + * @return Collection|object */ public function collection(Collection $collection = null) { @@ -27,7 +29,7 @@ public function collection(Collection $collection = null) return $this; } if ($this->collection === null) { - $this->collection = new \Illuminate\Support\Collection; + $this->collection = new Collection; } return $this->collection; } diff --git a/src/traits/ContainerTrait.php b/src/traits/ContainerTrait.php old mode 100644 new mode 100755 index e104312..61ebd09 --- a/src/traits/ContainerTrait.php +++ b/src/traits/ContainerTrait.php @@ -2,6 +2,9 @@ namespace momentphp\traits; +use momentphp\App; +use Psr\Container\ContainerInterface; + /** * ContainerTrait */ @@ -10,24 +13,24 @@ trait ContainerTrait /** * App * - * @var \momentphp\App + * @var App */ public $app; /** * Container * - * @var \Interop\Container\ContainerInterface + * @var ContainerInterface */ protected $container; /** * Container getter/setter * - * @param ContainerInterface|null $container + * @param ContainerInterface|null $container * @return ContainerInterface|object */ - public function container(\Interop\Container\ContainerInterface $container = null) + public function container(ContainerInterface $container = null) { if ($container !== null) { $this->container = $container; diff --git a/src/traits/EventsDispatcherTrait.php b/src/traits/EventsDispatcherTrait.php old mode 100644 new mode 100755 index 748c8fb..a436472 --- a/src/traits/EventsDispatcherTrait.php +++ b/src/traits/EventsDispatcherTrait.php @@ -2,6 +2,9 @@ namespace momentphp\traits; +use Illuminate\Container\Container; +use Illuminate\Events\Dispatcher; + /** * EventsDispatcherTrait */ @@ -10,23 +13,23 @@ trait EventsDispatcherTrait /** * Dispatcher * - * @var \Illuminate\Events\Dispatcher + * @var Dispatcher */ protected $eventsDispatcher; /** * Dispatcher getter/setter * - * @return \Illuminate\Events\Dispatcher|object + * @return Dispatcher|object */ - public function eventsDispatcher(\Illuminate\Events\Dispatcher $dispatcher = null) + public function eventsDispatcher(Dispatcher $dispatcher = null) { if ($dispatcher !== null) { $this->eventsDispatcher = $dispatcher; return $this; } if ($this->eventsDispatcher === null) { - $this->eventsDispatcher = new \Illuminate\Events\Dispatcher(new \Illuminate\Container\Container); + $this->eventsDispatcher = new Dispatcher(new Container); } return $this->eventsDispatcher; } @@ -36,17 +39,20 @@ public function eventsDispatcher(\Illuminate\Events\Dispatcher $dispatcher = nul * * @param object $object */ - public function bindImplementedEvents($object) + public function bindImplementedEvents(object $object): void { if (!method_exists($object, 'implementedEvents')) { return; } foreach ($object->implementedEvents() as $event => $handler) { - $this->eventsDispatcher()->listen($event, function () use ($object, $handler) { - $args = func_get_args(); - array_shift($args); - return call_user_func_array([$object, $handler], $args); - }); + $this->eventsDispatcher()->listen( + $event, + function () use ($object, $handler) { + $args = func_get_args(); + array_shift($args); + return call_user_func_array([$object, $handler], $args); + } + ); } } } diff --git a/src/traits/OptionsTrait.php b/src/traits/OptionsTrait.php old mode 100644 new mode 100755 index f6de88f..6a94d77 --- a/src/traits/OptionsTrait.php +++ b/src/traits/OptionsTrait.php @@ -2,6 +2,8 @@ namespace momentphp\traits; +use Illuminate\Support\Arr; + /** * OptionsTrait */ @@ -24,8 +26,8 @@ trait OptionsTrait /** * Options getter/setter * - * @param null|string|array $key - * @param null|mixed $value + * @param null|string|array $key + * @param null|mixed $value * @return mixed */ public function options($key = null, $value = null) @@ -40,18 +42,18 @@ public function options($key = null, $value = null) // options set if (is_array($key)) { foreach ($key as $innerKey => $innerValue) { - \Illuminate\Support\Arr::set($this->options, $innerKey, $innerValue); + Arr::set($this->options, $innerKey, $innerValue); } return $this; } // options set if (func_num_args() === 2) { - \Illuminate\Support\Arr::set($this->options, $key, $value); + Arr::set($this->options, $key, $value); return $this; } // options get - return \Illuminate\Support\Arr::get($this->options, $key); + return Arr::get($this->options, $key); } } diff --git a/tests/app/Bundle.php b/tests/app/Bundle.php old mode 100644 new mode 100755 diff --git a/tests/app/config/app.php b/tests/app/config/app.php old mode 100644 new mode 100755 index f0009e9..dfb061a --- a/tests/app/config/app.php +++ b/tests/app/config/app.php @@ -1,33 +1,24 @@ 'UTF-8', - 'timezone' => 'UTC', - 'locale' => 'en', - 'error' => [ - 'level' => -1, - 'logger' => false, - 'skip' => [ - \Slim\Exception\NotFoundException::class, - \Slim\Exception\MethodNotAllowedException::class, + HttpNotFoundException::class, + HttpMethodNotAllowedException::class, ], - ], - 'viewEngine' => 'twig', - 'providers' => [ - 'smarty' => 'SmartyProvider', 'twig' => 'TwigProvider', ], - 'middlewares' => [ 'app' => [ 'animal' => 'AnimalMiddleware', @@ -36,11 +27,9 @@ 'zoo' => 'ZooMiddleware', ], ], - 'httpVersion' => '1.1', 'responseChunkSize' => 4096, 'outputBuffering' => 'prepend', 'determineRouteBeforeAppMiddleware' => false, 'displayErrorDetails' => true, - ]; diff --git a/tests/app/config/cache.php b/tests/app/config/cache.php old mode 100644 new mode 100755 index 39f80a2..705c289 --- a/tests/app/config/cache.php +++ b/tests/app/config/cache.php @@ -1,27 +1,22 @@ 'file', - 'stores' => [ - 'file' => [ 'driver' => 'file', 'path' => path([app('pathStorage'), 'cache', app()->fingerprint()]), ], - 'memcached' => [ - 'driver' => 'memcached', + 'driver' => 'memcached', 'servers' => [ [ - 'host' => '127.0.0.1', 'port' => 11211, 'weight' => 100, + 'host' => '127.0.0.1', + 'port' => 11211, + 'weight' => 100, ], ], ], - ], - 'prefix' => app()->fingerprint(), - ]; diff --git a/tests/app/config/controllers.php b/tests/app/config/controllers.php old mode 100644 new mode 100755 diff --git a/tests/app/config/helpers.php b/tests/app/config/helpers.php old mode 100644 new mode 100755 diff --git a/tests/app/config/providers.php b/tests/app/config/providers.php old mode 100644 new mode 100755 index 93115d0..870d2f7 --- a/tests/app/config/providers.php +++ b/tests/app/config/providers.php @@ -1,10 +1,6 @@ [ - 'templates' => app()->resourcePaths('templates'), - 'compile' => path([app('pathStorage'), 'templates', 'smarty', app()->fingerprint()]), - ], 'Twig' => [ 'templates' => app()->resourcePaths('templates'), 'compile' => path([app('pathStorage'), 'templates', 'twig', app()->fingerprint()]), diff --git a/tests/app/controllers/TestController.php b/tests/app/controllers/TestController.php old mode 100644 new mode 100755 index 3d3a13b..952532a --- a/tests/app/controllers/TestController.php +++ b/tests/app/controllers/TestController.php @@ -6,61 +6,61 @@ class TestController extends \momentphp\Controller { public $callbacksCount = 0; - public function initialize() + public function initialize(): void { $this->callbacksCount++; } - public function beforeAction($action) + public function beforeAction(string $action): void { if ($action === 'callbacks') { $this->callbacksCount++; } } - public function afterAction($action) + public function afterAction(string $action): void { if ($action === 'callbacks') { $this->callbacksCount++; } } - protected function hello($name = 'stranger') + protected function hello($name = 'stranger'): string { return 'hello ' . $name; } - protected function callbacks() + protected function callbacks(): string { $this->callbacksCount++; return ''; } - protected function attributes() + protected function attributes(): string { return sprintf('%s:%s', $this->request->getAttribute('controller'), $this->request->getAttribute('action')); } - protected function template() + protected function template(): void { } - protected function template2() + protected function template2(): void { $this->view->template('template'); } - protected function template3() + protected function template3(): void { $this->view->template('/template3'); } - protected function helper($viewEngine = 'smarty') + protected function helper($viewEngine = 'twig'): void { $this->view->engine($viewEngine); } - protected function cell() + protected function cell(): void { } } diff --git a/tests/app/controllers/cells/TestController.php b/tests/app/controllers/cells/TestController.php old mode 100644 new mode 100755 index 8a79468..5a0c065 --- a/tests/app/controllers/cells/TestController.php +++ b/tests/app/controllers/cells/TestController.php @@ -4,9 +4,9 @@ class TestController extends \momentphp\Controller { - protected function display($limit = 5) + protected function display($limit = 5): void { $limit = $this->options('limit') + $limit; - $this->set('limit', (string) $limit); + $this->set('limit', (string)$limit); } } diff --git a/tests/app/controllers/subnamespace/TestController.php b/tests/app/controllers/subnamespace/TestController.php old mode 100644 new mode 100755 index 5d12daf..3631838 --- a/tests/app/controllers/subnamespace/TestController.php +++ b/tests/app/controllers/subnamespace/TestController.php @@ -4,12 +4,12 @@ class TestController extends \momentphp\Controller { - protected function hello($name = 'stranger') + protected function hello($name = 'stranger'): string { return 'hello ' . $name; } - protected function template() + protected function template(): void { } } diff --git a/tests/app/helpers/TestHelper.php b/tests/app/helpers/TestHelper.php old mode 100644 new mode 100755 diff --git a/tests/app/helpers/subnamespace/TestHelper.php b/tests/app/helpers/subnamespace/TestHelper.php old mode 100644 new mode 100755 diff --git a/tests/app/models/TestModel.php b/tests/app/models/TestModel.php old mode 100644 new mode 100755 index d9bd7ff..9f91fd8 --- a/tests/app/models/TestModel.php +++ b/tests/app/models/TestModel.php @@ -6,12 +6,12 @@ class TestModel extends \momentphp\Model { protected $str = ['hello']; - public function initialize() + public function initialize(): void { $this->str[] = 'world'; } - public function greet() + public function greet(): string { return implode(' ', $this->str); } diff --git a/tests/app/models/deep/subnamespace/TestModel.php b/tests/app/models/deep/subnamespace/TestModel.php old mode 100644 new mode 100755 diff --git a/tests/app/providers/SmartyProvider.php b/tests/app/providers/SmartyProvider.php deleted file mode 100644 index c33f09d..0000000 --- a/tests/app/providers/SmartyProvider.php +++ /dev/null @@ -1,7 +0,0 @@ -get('/', function () { - return 'MomentPHP'; -}); +$app->get( + '/', + function () { + return 'MomentPHP'; + } +); diff --git a/tests/app/templates/controllers/Test/cell.twig b/tests/app/templates/controllers/Test/cell.twig old mode 100644 new mode 100755 diff --git a/tests/app/templates/controllers/Test/helper.tpl b/tests/app/templates/controllers/Test/helper.tpl deleted file mode 100644 index d9839e6..0000000 --- a/tests/app/templates/controllers/Test/helper.tpl +++ /dev/null @@ -1 +0,0 @@ -{$this->Test->test()}{$this->subnamespace->Test->test()} diff --git a/tests/app/templates/controllers/Test/helper.twig b/tests/app/templates/controllers/Test/helper.twig old mode 100644 new mode 100755 diff --git a/tests/app/templates/controllers/Test/template.twig b/tests/app/templates/controllers/Test/template.twig old mode 100644 new mode 100755 diff --git a/tests/app/templates/controllers/cells/Test/display.twig b/tests/app/templates/controllers/cells/Test/display.twig old mode 100644 new mode 100755 diff --git a/tests/app/templates/controllers/subnamespace/Test/template.twig b/tests/app/templates/controllers/subnamespace/Test/template.twig old mode 100644 new mode 100755 diff --git a/tests/app/templates/template3.twig b/tests/app/templates/template3.twig old mode 100644 new mode 100755 diff --git a/tests/bundles/first/Bundle.php b/tests/bundles/first/Bundle.php old mode 100644 new mode 100755 diff --git a/tests/bundles/first/classes/Animal.php b/tests/bundles/first/classes/Animal.php old mode 100644 new mode 100755 index 65376d5..f3b51f5 --- a/tests/bundles/first/classes/Animal.php +++ b/tests/bundles/first/classes/Animal.php @@ -4,7 +4,7 @@ class Animal { - public function makeNoise() + public function makeNoise(): string { return 'lion from first bundle'; } diff --git a/tests/bundles/first/classes/AnimalClass.php b/tests/bundles/first/classes/AnimalClass.php old mode 100644 new mode 100755 index bd88d17..c43520a --- a/tests/bundles/first/classes/AnimalClass.php +++ b/tests/bundles/first/classes/AnimalClass.php @@ -4,7 +4,7 @@ class AnimalClass { - public function makeNoise() + public function makeNoise(): string { return 'lion from first bundle'; } diff --git a/tests/bundles/first/config/middlewares.php b/tests/bundles/first/config/middlewares.php old mode 100644 new mode 100755 diff --git a/tests/bundles/first/middlewares/AnimalMiddleware.php b/tests/bundles/first/middlewares/AnimalMiddleware.php old mode 100644 new mode 100755 index dcfbb37..47e87c4 --- a/tests/bundles/first/middlewares/AnimalMiddleware.php +++ b/tests/bundles/first/middlewares/AnimalMiddleware.php @@ -2,9 +2,12 @@ namespace momentphp\tests\bundles\first\middlewares; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + class AnimalMiddleware extends \momentphp\Middleware { - public function __invoke($request, $response, $next) + public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface { return $next($request, $response->withHeader('X-Animal', $this->options('type'))); } diff --git a/tests/bundles/first/middlewares/ZooMiddleware.php b/tests/bundles/first/middlewares/ZooMiddleware.php old mode 100644 new mode 100755 index 78e3018..1f1c054 --- a/tests/bundles/first/middlewares/ZooMiddleware.php +++ b/tests/bundles/first/middlewares/ZooMiddleware.php @@ -2,9 +2,12 @@ namespace momentphp\tests\bundles\first\middlewares; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + class ZooMiddleware extends \momentphp\Middleware { - public function __invoke($request, $response, $next) + public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface { return $next($request, $response->withHeader('X-Zoo', $this->options('animals'))); } diff --git a/tests/bundles/first/routes.php b/tests/bundles/first/routes.php old mode 100644 new mode 100755 index 2e35716..54967da --- a/tests/bundles/first/routes.php +++ b/tests/bundles/first/routes.php @@ -1,5 +1,8 @@ get('/animal', function () { - return 'lion from first bundle'; -}); +$app->get( + '/animal', + function () { + return 'lion from first bundle'; + } +); diff --git a/tests/bundles/first/templates/animal.tpl b/tests/bundles/first/templates/animal.tpl deleted file mode 100644 index a7f5ec7..0000000 --- a/tests/bundles/first/templates/animal.tpl +++ /dev/null @@ -1 +0,0 @@ -lion {$name} from first bundle diff --git a/tests/bundles/first/templates/animal.twig b/tests/bundles/first/templates/animal.twig old mode 100644 new mode 100755 diff --git a/tests/bundles/first/templates/zoo/animals/lion.twig b/tests/bundles/first/templates/zoo/animals/lion.twig old mode 100644 new mode 100755 diff --git a/tests/bundles/first/templates/zoo/animals/zebra.twig b/tests/bundles/first/templates/zoo/animals/zebra.twig old mode 100644 new mode 100755 diff --git a/tests/bundles/second/Bundle.php b/tests/bundles/second/Bundle.php old mode 100644 new mode 100755 diff --git a/tests/bundles/second/classes/Animal.php b/tests/bundles/second/classes/Animal.php old mode 100644 new mode 100755 index 5925428..d53d7ac --- a/tests/bundles/second/classes/Animal.php +++ b/tests/bundles/second/classes/Animal.php @@ -4,7 +4,7 @@ class Animal { - public function makeNoise() + public function makeNoise(): string { return 'zebra from second bundle'; } diff --git a/tests/bundles/second/classes/AnimalClass.php b/tests/bundles/second/classes/AnimalClass.php old mode 100644 new mode 100755 index 57824fe..fda8124 --- a/tests/bundles/second/classes/AnimalClass.php +++ b/tests/bundles/second/classes/AnimalClass.php @@ -4,7 +4,7 @@ class AnimalClass { - public function makeNoise() + public function makeNoise(): string { return 'zebra from second bundle'; } diff --git a/tests/bundles/second/routes.php b/tests/bundles/second/routes.php old mode 100644 new mode 100755 index 4c95bba..32174aa --- a/tests/bundles/second/routes.php +++ b/tests/bundles/second/routes.php @@ -1,5 +1,8 @@ get('/animal', function () { - return 'zebra from second bundle'; -}); +$app->get( + '/animal', + function () { + return 'zebra from second bundle'; + } +); diff --git a/tests/bundles/second/templates/animal.tpl b/tests/bundles/second/templates/animal.tpl deleted file mode 100644 index 40a32bf..0000000 --- a/tests/bundles/second/templates/animal.tpl +++ /dev/null @@ -1 +0,0 @@ -zebra {$name} from second bundle diff --git a/tests/bundles/second/templates/animal.twig b/tests/bundles/second/templates/animal.twig old mode 100644 new mode 100755 diff --git a/tests/bundles/third/Bundle.php b/tests/bundles/third/Bundle.php old mode 100644 new mode 100755 diff --git a/tests/bundles/third/classes/Animal.php b/tests/bundles/third/classes/Animal.php old mode 100644 new mode 100755 index e91f2d4..defb4ac --- a/tests/bundles/third/classes/Animal.php +++ b/tests/bundles/third/classes/Animal.php @@ -4,7 +4,7 @@ class Animal { - public function makeNoise() + public function makeNoise(): string { return 'monkey from third bundle'; } diff --git a/tests/bundles/third/classes/AnimalClass.php b/tests/bundles/third/classes/AnimalClass.php old mode 100644 new mode 100755 index 3a732f2..b23c104 --- a/tests/bundles/third/classes/AnimalClass.php +++ b/tests/bundles/third/classes/AnimalClass.php @@ -4,7 +4,7 @@ class AnimalClass { - public function makeNoise() + public function makeNoise(): string { return 'monkey from third bundle'; } diff --git a/tests/bundles/third/routes.php b/tests/bundles/third/routes.php old mode 100644 new mode 100755 index de3d42f..9e5604e --- a/tests/bundles/third/routes.php +++ b/tests/bundles/third/routes.php @@ -1,5 +1,8 @@ get('/animal', function () { - return 'monkey from third bundle'; -}); +$app->get( + '/animal', + function () { + return 'monkey from third bundle'; + } +); diff --git a/tests/bundles/third/templates/animal.tpl b/tests/bundles/third/templates/animal.tpl deleted file mode 100644 index 7445e18..0000000 --- a/tests/bundles/third/templates/animal.tpl +++ /dev/null @@ -1 +0,0 @@ -monkey {$name} from third bundle diff --git a/tests/bundles/third/templates/animal.twig b/tests/bundles/third/templates/animal.twig old mode 100644 new mode 100755 diff --git a/tests/cases/AppTest.php b/tests/cases/AppTest.php old mode 100644 new mode 100755 index 1d3fd70..d9a768f --- a/tests/cases/AppTest.php +++ b/tests/cases/AppTest.php @@ -2,23 +2,28 @@ namespace momentphp\tests\cases; +use Illuminate\Container\Container; +use momentphp\App; + class AppTest extends Test { public $app; - public function setUp() + public function setUp(): void { - $this->app = new \momentphp\App([ - \momentphp\tests\bundles\first\Bundle::class => ['alias' => 'first'], - \momentphp\tests\bundles\second\Bundle::class => ['alias' => 'second'], - \momentphp\tests\bundles\third\Bundle::class => ['alias' => 'third'], - \momentphp\tests\app\Bundle::class => ['alias' => 'app'], - ], [ - 'settings' => ['displayErrorDetails' => true] - ]); + $this->app = new App( + [ + \momentphp\tests\bundles\first\Bundle::class => ['alias' => 'first'], + \momentphp\tests\bundles\second\Bundle::class => ['alias' => 'second'], + \momentphp\tests\bundles\third\Bundle::class => ['alias' => 'third'], + \momentphp\tests\app\Bundle::class => ['alias' => 'app'], + ], [ + 'settings' => ['displayErrorDetails' => true] + ] + ); } - public function tearDown() + public function tearDown(): void { unset($this->app); } @@ -27,14 +32,20 @@ public function testRouteOverwriting() { $app = $this->app; $app->booted = true; - $app->get('/test', function () { - return 'first'; - }); - $app->get('/test', function () { - return 'second'; - })->setName('second'); + $app->get( + '/test', + function () { + return 'first'; + } + ); + $app->get( + '/test', + function () { + return 'second'; + } + )->setName('second'); $res = $app->visit('/test'); - $this->assertEquals('first', (string) $res->getBody()); + self::assertEquals('first', (string)$res->getBody()); } public function testResourcePaths() @@ -42,26 +53,35 @@ public function testResourcePaths() $app = $this->app; $app->booted = true; - $this->assertEquals([ - $app->bundles('first')->classPath('config'), - $app->bundles('second')->classPath('config'), - $app->bundles('third')->classPath('config'), - $app->bundles('app')->classPath('config'), - ], $app->resourcePaths('config')); - - $this->assertEquals([ - $app->bundles('app')->alias() => $app->bundles('app')->classPath('templates'), - $app->bundles('third')->alias() => $app->bundles('third')->classPath('templates'), - $app->bundles('second')->alias() => $app->bundles('second')->classPath('templates'), - $app->bundles('first')->alias() => $app->bundles('first')->classPath('templates'), - ], $app->resourcePaths('templates')); - - $this->assertEquals([ - $app->bundles('app')->classPath('routes.php'), - $app->bundles('third')->classPath('routes.php'), - $app->bundles('second')->classPath('routes.php'), - $app->bundles('first')->classPath('routes.php'), - ], $app->resourcePaths('routes')); + self::assertEquals( + [ + $app->bundles('first')->classPath('config'), + $app->bundles('second')->classPath('config'), + $app->bundles('third')->classPath('config'), + $app->bundles('app')->classPath('config'), + ], + $app->resourcePaths('config') + ); + + self::assertEquals( + [ + $app->bundles('app')->alias() => $app->bundles('app')->classPath('templates'), + $app->bundles('third')->alias() => $app->bundles('third')->classPath('templates'), + $app->bundles('second')->alias() => $app->bundles('second')->classPath('templates'), + $app->bundles('first')->alias() => $app->bundles('first')->classPath('templates'), + ], + $app->resourcePaths('templates') + ); + + self::assertEquals( + [ + $app->bundles('app')->classPath('routes.php'), + $app->bundles('third')->classPath('routes.php'), + $app->bundles('second')->classPath('routes.php'), + $app->bundles('first')->classPath('routes.php'), + ], + $app->resourcePaths('routes') + ); } public function testFingerprint() @@ -69,9 +89,9 @@ public function testFingerprint() $app = $this->app; $app->booted = true; $aliases = 'first_second_third_app'; - $this->assertEquals($aliases, $app->fingerprint()); + self::assertEquals($aliases, $app->fingerprint()); $aliases = 'first.second.third.app'; - $this->assertEquals($aliases, $app->fingerprint('.')); + self::assertEquals($aliases, $app->fingerprint('.')); } public function testAutoloader() @@ -80,7 +100,7 @@ public function testAutoloader() $app->booted = true; $class = $app->bundleClass('classes\Animal'); $animal = new $class; - $this->assertEquals('monkey from third bundle', $animal->makeNoise()); + self::assertEquals('monkey from third bundle', $animal->makeNoise()); } public function testCallableResolver() @@ -90,9 +110,9 @@ public function testCallableResolver() $app->get('/hello/{name}', 'TestController:hello'); $app->get('/subnamespace/hello/{name}', 'subnamespace\TestController:hello'); $res = $app->visit('/hello/john'); - $this->assertEquals('hello john', (string) $res->getBody()); + self::assertEquals('hello john', (string)$res->getBody()); $res = $app->visit('/subnamespace/hello/john'); - $this->assertEquals('hello john', (string) $res->getBody()); + self::assertEquals('hello john', (string)$res->getBody()); } public function testControllerCallbacks() @@ -100,13 +120,17 @@ public function testControllerCallbacks() $app = $this->app; $app->booted = true; $controllerClass = $app->bundleClass('controllers\TestController'); - $controller = new $controllerClass(new \Slim\Container([ - 'app' => function () use ($app) { - return $app; - } - ])); + $controller = new $controllerClass( + new Container( + [ + 'app' => function () use ($app) { + return $app; + } + ] + ) + ); $controller->callbacks($app->request, $app->response, []); - $this->assertEquals(4, $controller->callbacksCount); + self::assertEquals(4, $controller->callbacksCount); } public function testRequestAttributes() @@ -115,20 +139,23 @@ public function testRequestAttributes() $app->booted = true; $app->get('/attributes', 'TestController:attributes'); $res = $app->visit('/attributes'); - $this->assertEquals('TestController:attributes', (string) $res->getBody()); + self::assertEquals('TestController:attributes', (string)$res->getBody()); } public function testMiddlewares() { $app = $this->app; $app->boot(); - $app->get('/route-middleware', function () { - return 'route middleware'; - })->add('zoo'); + $app->get( + '/route-middleware', + function () { + return 'route middleware'; + } + )->add('zoo'); $res = $app->visit('/'); - $this->assertEquals(['lion'], $res->getHeader('X-Animal')); + self::assertEquals(['lion'], $res->getHeader('X-Animal')); $res = $app->visit('/route-middleware'); - $this->assertEquals(['lion'], $res->getHeader('X-Zoo')); + self::assertEquals(['lion'], $res->getHeader('X-Zoo')); } public function testViewEngines() @@ -136,17 +163,10 @@ public function testViewEngines() $app = $this->app; $app->registerProviders(); - $this->assertEquals('monkey james from third bundle', trim($app->smarty->render('animal', ['name' => 'james']))); - $this->assertEquals('monkey james from third bundle', trim($app->twig->render('animal', ['name' => 'james']))); - - $this->assertEquals('zebra james from second bundle', trim($app->smarty->render('animal', ['name' => 'james'], 'second'))); - $this->assertEquals('zebra james from second bundle', trim($app->twig->render('animal', ['name' => 'james'], 'second'))); - - $this->assertEquals(true, trim($app->smarty->exists('animal', 'third'))); - $this->assertEquals(true, trim($app->twig->exists('animal', 'third'))); - - $this->assertEquals(false, trim($app->smarty->exists('nonexistenttemplate', 'third'))); - $this->assertEquals(false, trim($app->twig->exists('nonexistenttemplate', 'third'))); + self::assertEquals('monkey james from third bundle', trim($app->twig->render('animal', ['name' => 'james']))); + self::assertEquals('zebra james from second bundle', trim($app->twig->render('animal', ['name' => 'james'], 'second'))); + self::assertEquals(true, trim($app->twig->exists('animal', 'third'))); + self::assertEquals(false, trim($app->twig->exists('nonexistenttemplate', 'third'))); } public function testView() @@ -154,15 +174,15 @@ public function testView() $app = $this->app; $app->registerProviders(); $view = clone $app->view; - $this->assertEquals('monkey james from third bundle', trim($view->template('animal')->set('name', 'james')->render())); + self::assertEquals('monkey james from third bundle', trim($view->template('animal')->set('name', 'james')->render())); $view = clone $app->view; - $this->assertEquals('monkey james from third bundle', trim($view->set('name', 'james')->render('animal'))); + self::assertEquals('monkey james from third bundle', trim($view->set('name', 'james')->render('animal'))); $view = clone $app->view; - $this->assertEquals('zebra', trim($view->render('/zoo/animals/zebra'))); + self::assertEquals('zebra', trim($view->render('/zoo/animals/zebra'))); $view->templateFolder('zoo/animals'); - $this->assertEquals('zebra', trim($view->template('zebra')->render())); - $this->assertEquals('lion', trim($view->template('lion')->render())); - $this->assertEquals('monkey james from third bundle', trim($view->template('/animal')->set('name', 'james')->render())); + self::assertEquals('zebra', trim($view->template('zebra')->render())); + self::assertEquals('lion', trim($view->template('lion')->render())); + self::assertEquals('monkey james from third bundle', trim($view->template('/animal')->set('name', 'james')->render())); } public function testControllerTemplates() @@ -174,13 +194,13 @@ public function testControllerTemplates() $app->get('/template3', 'TestController:template3'); $app->get('/subnamespace/template', 'subnamespace\TestController:template'); $res = $app->visit('/template'); - $this->assertEquals('template', trim((string) $res->getBody())); + self::assertEquals('template', trim((string)$res->getBody())); $res = $app->visit('/template2'); - $this->assertEquals('template', trim((string) $res->getBody())); + self::assertEquals('template', trim((string)$res->getBody())); $res = $app->visit('/template3'); - $this->assertEquals('template3', trim((string) $res->getBody())); + self::assertEquals('template3', trim((string)$res->getBody())); $res = $app->visit('/subnamespace/template'); - $this->assertEquals('subnamespace template', trim((string) $res->getBody())); + self::assertEquals('subnamespace template', trim((string)$res->getBody())); } public function testHelpers() @@ -189,9 +209,9 @@ public function testHelpers() $app->boot(); $app->get('/helper/{viewService}', 'TestController:helper'); $res = $app->visit('/helper/smarty'); - $this->assertEquals('ipsumipsums', trim((string)$res->getBody())); + self::assertEquals('ipsumipsums', trim((string)$res->getBody())); $res = $app->visit('/helper/twig'); - $this->assertEquals('ipsumipsums', trim((string)$res->getBody())); + self::assertEquals('ipsumipsums', trim((string)$res->getBody())); } public function testCells() @@ -200,34 +220,34 @@ public function testCells() $app->boot(); $app->get('/cell', 'TestController:cell'); $res = $app->visit('/cell'); - $this->assertEquals('110', trim((string)$res->getBody())); + self::assertEquals('110', trim((string)$res->getBody())); } public function testModels() { $app = $this->app; - $this->assertEquals('hello world', $app->registry->models->Test->greet()); + self::assertEquals('hello world', $app->registry->models->Test->greet()); $model1 = $app->registry->models->Test; $model2 = $app->registry->models->Test; - $same = (spl_object_hash($model1) === spl_object_hash($model1)); - $this->assertEquals(true, $same); - $this->assertEquals('subnamespace hello world', $app->registry->models->deep->subnamespace->Test->greet()); + $same = (spl_object_hash($model1) === spl_object_hash($model2)); + self::assertEquals(true, $same); + self::assertEquals('subnamespace hello world', $app->registry->models->deep->subnamespace->Test->greet()); } public function testCache() { $app = $this->app; - $this->assertEquals(null, $app->cache->get('lorem')); + self::assertEquals(null, $app->cache->get('lorem')); $app->cache->put('lorem', 'ipsum', 1); - $this->assertEquals('ipsum', $app->cache->get('lorem')); + self::assertEquals('ipsum', $app->cache->get('lorem')); $app->cache->forget('lorem'); if (!class_exists('Memcached')) { return; } $memcached = $app->cache->store('memcached'); - $this->assertEquals(null, $memcached->get('lorem')); + self::assertEquals(null, $memcached->get('lorem')); $memcached->put('lorem', 'ipsum', 1); - $this->assertEquals('ipsum', $memcached->get('lorem')); + self::assertEquals('ipsum', $memcached->get('lorem')); $memcached->forget('lorem'); } } diff --git a/tests/cases/SkipTest.php b/tests/cases/SkipTest.php old mode 100644 new mode 100755 index 17879b9..90eff03 --- a/tests/cases/SkipTest.php +++ b/tests/cases/SkipTest.php @@ -2,6 +2,8 @@ namespace momentphp\tests\cases; +use momentphp\App; + /** * @runTestsInSeparateProcesses * @preserveGlobalState disabled @@ -10,23 +12,25 @@ class SkipTest extends Test { public function testSkip() { - $app = new \momentphp\App([ - \momentphp\tests\bundles\first\Bundle::class => ['alias' => 'first', 'skipResource' => ['routes']], - \momentphp\tests\bundles\second\Bundle::class => ['alias' => 'second', 'skipResource' => ['routes']], - \momentphp\tests\bundles\third\Bundle::class => [ - 'alias' => 'third', - 'skipClass' => 'classes', - ], - \momentphp\tests\app\Bundle::class => ['alias' => 'app', 'skipResource' => ['routes']], - ]); + $app = new App( + [ + \momentphp\tests\bundles\first\Bundle::class => ['alias' => 'first', 'skipResource' => ['routes']], + \momentphp\tests\bundles\second\Bundle::class => ['alias' => 'second', 'skipResource' => ['routes']], + \momentphp\tests\bundles\third\Bundle::class => [ + 'alias' => 'third', + 'skipClass' => 'classes', + ], + \momentphp\tests\app\Bundle::class => ['alias' => 'app', 'skipResource' => ['routes']], + ] + ); $app->booted = true; $app->registerRoutes(); $cl = $app->bundleClass('classes\Animal'); $animal = new $cl; - $this->assertEquals('zebra from second bundle', $animal->makeNoise()); + self::assertEquals('zebra from second bundle', $animal->makeNoise()); $res = $app->visit('/animal'); - $this->assertEquals('monkey from third bundle', (string) $res->getBody()); + self::assertEquals('monkey from third bundle', (string)$res->getBody()); } } diff --git a/tests/cases/Test.php b/tests/cases/Test.php old mode 100644 new mode 100755 index 94de96a..10e4940 --- a/tests/cases/Test.php +++ b/tests/cases/Test.php @@ -2,8 +2,8 @@ namespace momentphp\tests\cases; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -abstract class Test extends PHPUnit_Framework_TestCase +abstract class Test extends TestCase { } diff --git a/tests/cases/traits/ClassTraitTest.php b/tests/cases/traits/ClassTraitTest.php old mode 100644 new mode 100755 index 7cca2db..df68a3b --- a/tests/cases/traits/ClassTraitTest.php +++ b/tests/cases/traits/ClassTraitTest.php @@ -2,28 +2,31 @@ namespace momentphp\tests\cases\traits; +use momentphp\traits\ClassTrait; +use PHPUnit\Framework\TestCase; + class ClassTraitConsumer { - use \momentphp\traits\ClassTrait; + use ClassTrait; } class Consumer { - use \momentphp\traits\ClassTrait; + use ClassTrait; } -class ClassTraitTest extends \PHPUnit_Framework_TestCase +class ClassTraitTest extends TestCase { public $consumer; public $consumerShort; - public function setUp() + public function setUp(): void { $this->consumer = new ClassTraitConsumer; $this->consumerShort = new Consumer; } - public function tearDown() + public function tearDown(): void { unset($this->consumer, $this->consumerShort); } @@ -31,38 +34,38 @@ public function tearDown() public function testClassNamespace() { $consumer = $this->consumer; - $this->assertEquals('momentphp\\tests\\cases\\traits', $consumer::classNamespace()); - $this->assertEquals('momentphp\\tests\\cases\\traits\\foobar', $consumer::classNamespace('foobar')); + self::assertEquals('momentphp\\tests\\cases\\traits', $consumer::classNamespace()); + self::assertEquals('momentphp\\tests\\cases\\traits\\foobar', $consumer::classNamespace('foobar')); } public function testClassPath() { $consumer = $this->consumer; - $this->assertEquals(__DIR__, $consumer::classPath()); - $this->assertEquals(__DIR__ . DIRECTORY_SEPARATOR . 'foobar', $consumer::classPath('foobar')); + self::assertEquals(__DIR__, $consumer::classPath()); + self::assertEquals(__DIR__ . DIRECTORY_SEPARATOR . 'foobar', $consumer::classPath('foobar')); } public function testClassPrefix() { $consumer = $this->consumer; $consumerShort = $this->consumerShort; - $this->assertEquals('ClassTrait', $consumer::classPrefix()); - $this->assertEquals('classTraits', $consumer::classPrefix(true)); - $this->assertEquals('', $consumerShort::classPrefix()); + self::assertEquals('ClassTrait', $consumer::classPrefix()); + self::assertEquals('classTraits', $consumer::classPrefix(true)); + self::assertEquals('', $consumerShort::classPrefix()); } public function testClassSuffix() { $consumer = $this->consumer; $consumerShort = $this->consumerShort; - $this->assertEquals('Consumer', $consumer::classSuffix()); - $this->assertEquals('consumers', $consumer::classSuffix(true)); - $this->assertEquals('Consumer', $consumerShort::classSuffix()); + self::assertEquals('Consumer', $consumer::classSuffix()); + self::assertEquals('consumers', $consumer::classSuffix(true)); + self::assertEquals('Consumer', $consumerShort::classSuffix()); } public function testClassConfigKey() { $consumer = $this->consumer; - $this->assertEquals('tests.cases.traits.ClassTrait', $consumer::classConfigKey()); + self::assertEquals('tests.cases.traits.ClassTrait', $consumer::classConfigKey()); } } diff --git a/tests/cases/traits/OptionsTraitTest.php b/tests/cases/traits/OptionsTraitTest.php old mode 100644 new mode 100755 index df49cfe..659c3b2 --- a/tests/cases/traits/OptionsTraitTest.php +++ b/tests/cases/traits/OptionsTraitTest.php @@ -2,11 +2,12 @@ namespace momentphp\tests\cases\traits; -use PHPUnit_Framework_TestCase; +use momentphp\traits\OptionsTrait; +use PHPUnit\Framework\TestCase; class OptionsTraitConsumer { - use \momentphp\traits\OptionsTrait; + use OptionsTrait; protected $defaults = [ 'lorem' => 'ipsum', @@ -14,54 +15,60 @@ class OptionsTraitConsumer ]; } -class OptionsTraitTest extends PHPUnit_Framework_TestCase +class OptionsTraitTest extends TestCase { public $consumer; - public function setUp() + public function setUp(): void { $this->consumer = new OptionsTraitConsumer; } - public function tearDown() + public function tearDown(): void { unset($this->consumer); } public function testGet() { - $this->assertEquals([ - 'lorem' => 'ipsum', - 'some' => ['deep' => 'option'], - ], $this->consumer->options()); + self::assertEquals( + [ + 'lorem' => 'ipsum', + 'some' => ['deep' => 'option'], + ], + $this->consumer->options() + ); - $this->assertEquals('ipsum', $this->consumer->options('lorem')); - $this->assertEquals('option', $this->consumer->options('some.deep')); - $this->assertEquals(null, $this->consumer->options('notfound')); + self::assertEquals('ipsum', $this->consumer->options('lorem')); + self::assertEquals('option', $this->consumer->options('some.deep')); + self::assertEquals(null, $this->consumer->options('notfound')); } public function testSet() { $result = $this->consumer->options('new', 'option'); - $this->assertEquals('option', $this->consumer->options('new')); - $this->assertInstanceOf(OptionsTraitConsumer::class, $result); + self::assertEquals('option', $this->consumer->options('new')); + self::assertInstanceOf(OptionsTraitConsumer::class, $result); $this->consumer->options('some.deep', 'option2'); - $this->assertEquals(['deep' => 'option2'], $this->consumer->options('some')); + self::assertEquals(['deep' => 'option2'], $this->consumer->options('some')); } public function testSetArray() { $this->consumer->options(['lorem' => 'ipsum2', 'some.deep' => 'option2']); - $this->assertEquals([ - 'lorem' => 'ipsum2', - 'some' => ['deep' => 'option2'], - ], $this->consumer->options()); + self::assertEquals( + [ + 'lorem' => 'ipsum2', + 'some' => ['deep' => 'option2'], + ], + $this->consumer->options() + ); } public function testSetReplace() { $this->consumer->options(null, ['new' => 'array']); - $this->assertEquals(['new' => 'array'], $this->consumer->options()); + self::assertEquals(['new' => 'array'], $this->consumer->options()); } } diff --git a/tests/config/first/bundles.php b/tests/config/first/bundles.php old mode 100644 new mode 100755 diff --git a/tests/config/first/development/bundles.php b/tests/config/first/development/bundles.php old mode 100644 new mode 100755 diff --git a/tests/config/second/bundles.php b/tests/config/second/bundles.php old mode 100644 new mode 100755 From 9b664496b7aef438e862922d8a614ff75c783cff Mon Sep 17 00:00:00 2001 From: stdex Date: Sat, 8 May 2021 01:51:43 +0300 Subject: [PATCH 2/3] Update dependencies --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1cdfb2..0452cdc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,5 +30,5 @@ jobs: run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Test with phpunit run: vendor/bin/phpunit --coverage-text - - name: Run phpcs + - name: Run phpcs run: ./vendor/bin/phpcs From d0dc9230f1f9bcfdd527e8f01096ce45e9a921e2 Mon Sep 17 00:00:00 2001 From: stdex Date: Sun, 29 Aug 2021 23:51:12 +0300 Subject: [PATCH 3/3] Update dependencies --- composer.json | 5 +- src/App.php | 23 +- src/Controller.php | 15 +- src/Error.php | 5 +- src/ExceptionHandler.php | 25 ++- src/Model.php | 2 +- src/PsrContainer.php | 75 +++++++ src/components/Collection/Collection.php | 197 ++++++++++++++++++ .../Collection/CollectionInterface.php | 23 ++ .../Compatibility/DefaultServicesProvider.php | 191 +++++++++++++++++ src/components/Http/Request.php | 41 ++++ src/components/Http/Response.php | 17 ++ src/middlewares/WhoopsMiddleware.php | 7 + src/traits/ClassTrait.php | 2 +- 14 files changed, 595 insertions(+), 33 deletions(-) create mode 100755 src/PsrContainer.php create mode 100755 src/components/Collection/Collection.php create mode 100755 src/components/Collection/CollectionInterface.php create mode 100755 src/components/Compatibility/DefaultServicesProvider.php create mode 100755 src/components/Http/Request.php create mode 100755 src/components/Http/Response.php create mode 100755 src/middlewares/WhoopsMiddleware.php diff --git a/composer.json b/composer.json index ed65080..6bd6a4d 100755 --- a/composer.json +++ b/composer.json @@ -4,14 +4,15 @@ "homepage": "http://momentphp.kminek.pl", "keywords": ["framework", "momentphp"], "require": { - "php": "^7.3|^8.0", + "php": "^7.4|^8.0", "ext-json": "*", "ext-mbstring": "*", "ext-fileinfo": "*", "ext-pdo": "*", "slim/slim": "4.*", "slim/psr7": "*", - "illuminate/container": "8.*", + "pimple/pimple": "^3.0", + "zeuxisoo/slim-whoops": "0.7.*", "illuminate/support": "8.*", "illuminate/events": "8.*", "illuminate/database": "8.*", diff --git a/src/App.php b/src/App.php index 56d5845..dfcc02f 100755 --- a/src/App.php +++ b/src/App.php @@ -2,7 +2,6 @@ namespace momentphp; -use Illuminate\Container\Container; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Psr\Http\Message\ResponseInterface; @@ -102,7 +101,9 @@ public function __construct(array $bundles = [], array $container = []) * Env */ if (!isset($container['env'])) { - $container['env'] = 'production'; + $container['env'] = static function ($c) { + return 'production'; + }; } /** @@ -202,7 +203,7 @@ public function __construct(array $bundles = [], array $container = []) */ if (!isset($container['objectCache'])) { $container['objectCache'] = static function () { - return new ObjectCache; + return new ObjectCache(); }; } @@ -227,11 +228,13 @@ public function __construct(array $bundles = [], array $container = []) /** * Exception handler */ + /* if (!isset($container['exceptionHandler'])) { $container['exceptionHandler'] = static function ($c) { return new ExceptionHandler($c); }; } + */ /** * Callable resolver (Slim) @@ -242,13 +245,14 @@ public function __construct(array $bundles = [], array $container = []) }; } + $responseFactory = new ResponseFactory(); + /** * Router (Slim) */ if (!isset($container['router'])) { - $container['router'] = static function () use ($container) { + $container['router'] = static function () use ($container, $responseFactory) { $callableResolver = $container['callableResolver']; - $responseFactory = new ResponseFactory(); $routeCollector = new RouteCollector($responseFactory, $callableResolver); return new RouteResolver($routeCollector); }; @@ -257,12 +261,7 @@ public function __construct(array $bundles = [], array $container = []) /** * Init Slim app */ - if (is_array($container)) { - $container = new Container($container); - } - - $responseFactory = new ResponseFactory(); - $this->slim = new \Slim\App($responseFactory, $container); + $this->slim = new \Slim\App($responseFactory, (new PsrContainer($container))); $this->container($this->slim->getContainer()); /** @@ -468,7 +467,7 @@ public function bundleClass(?string $relativeClass = null): string public function service(string $name, callable $callable): void { $container = $this->container(); - $container[$name] = $callable; + $container->set($name, $callable); } /** diff --git a/src/Controller.php b/src/Controller.php index c3980d0..a4c987c 100755 --- a/src/Controller.php +++ b/src/Controller.php @@ -5,12 +5,14 @@ use Psr\Container\ContainerInterface; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Server\RequestHandlerInterface; use Slim\Exception\HttpNotFoundException; /** * Controller */ -abstract class Controller +abstract class Controller implements RequestHandlerInterface { use traits\ContainerTrait; use traits\OptionsTrait; @@ -50,8 +52,9 @@ public function __construct(ContainerInterface $container, array $options = []) if ($this->container()->has('view')) { $this->view = clone $this->container()->get('view'); } + $this->container()->get('app')->bindImplementedEvents($this); - $this->container()->get('app')->eventsDispatcher()->fire("controller.{static::classPrefix()}.initialize", [$this]); + $this->container()->get('app')->eventsDispatcher()->dispatch("controller.{static::classPrefix()}.initialize", [$this]); } /** @@ -68,6 +71,10 @@ public function implementedEvents(): array ]; } + public function handle(ServerRequestInterface $request): ResponseInterface + { + } + /** * Callback called after controller creation */ @@ -177,9 +184,9 @@ public function __call(string $action, array $args = []) $this->request = $request; $this->response = $response; - $this->container()->get('app')->eventsDispatcher()->fire("controller.{static::classPrefix()}.beforeAction", [$this, $action]); + $this->container()->get('app')->eventsDispatcher()->dispatch("controller.{static::classPrefix()}.beforeAction", [$this, $action]); $actionResponse = call_user_func_array([$this, $action], $params); - $this->container()->get('app')->eventsDispatcher()->fire("controller.{static::classPrefix()}.afterAction", [$this, $action]); + $this->container()->get('app')->eventsDispatcher()->dispatch("controller.{static::classPrefix()}.afterAction", [$this, $action]); if ($actionResponse === null) { if ($this->view === null) { diff --git a/src/Error.php b/src/Error.php index 1db6ab5..5a8a514 100755 --- a/src/Error.php +++ b/src/Error.php @@ -3,6 +3,7 @@ namespace momentphp; use Psr\Container\ContainerInterface; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; /** @@ -39,10 +40,6 @@ public function register(): void } if ($container->has('exceptionHandler')) { - unset($container['notFoundHandler']); - unset($container['notAllowedHandler']); - unset($container['errorHandler']); - unset($container['phpErrorHandler']); set_error_handler([$this, 'handleError']); set_exception_handler([$this, 'handleException']); register_shutdown_function([$this, 'handleShutdown']); diff --git a/src/ExceptionHandler.php b/src/ExceptionHandler.php index f4d705e..ce4d9e0 100755 --- a/src/ExceptionHandler.php +++ b/src/ExceptionHandler.php @@ -3,6 +3,7 @@ namespace momentphp; use Psr\Container\ContainerInterface; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Log\LogLevel; use Slim\Exception\HttpException; @@ -22,14 +23,20 @@ class ExceptionHandler { use traits\ContainerTrait; + protected RequestInterface $request; + protected ResponseInterface $response; + /** * Constructor * * @param ContainerInterface $container */ - public function __construct(ContainerInterface $container) + public function __construct(ContainerInterface $container, RequestInterface $request, ResponseInterface $response) { $this->container($container); + + $this->request = $request; + $this->response = $response; } /** @@ -41,7 +48,7 @@ public function __construct(ContainerInterface $container) public function renderForConsole(\Throwable $e): string { $whoops = $this->whoops(); - $whoops->pushHandler(new PlainTextHandler); + $whoops->pushHandler(new PlainTextHandler()); return $whoops->handleException($e); } @@ -56,7 +63,7 @@ public function renderHttpResponse(\Throwable $e): ResponseInterface if ($this->container()->has('debug') && $this->container()->get('debug')) { $whoops = $this->whoops(); $whoops->pushHandler($this->whoopsHandler($e)); - return $this->container->get('response')->write($whoops->handleException($e))->withStatus(500); + return $this->response->write($whoops->handleException($e))->withStatus(500); } $errorController = $this->container()->get('registry')->load('ErrorController'); @@ -77,7 +84,7 @@ public function renderHttpResponse(\Throwable $e): ResponseInterface if ($e instanceof HttpException) { $request = $e->getRequest(); } else { - $request = $this->container()->get('request'); + $request = $this->request; } return $errorController->error($request, [$e])->withStatus(500); @@ -91,12 +98,12 @@ public function renderHttpResponse(\Throwable $e): ResponseInterface */ protected function whoopsHandler(\Throwable $e) { - $handler = new PrettyPageHandler; + $handler = new PrettyPageHandler(); $handler->setPageTitle('Error'); $request = ($e instanceof HttpException) ? $e->getRequest() : - $this->container()->get('request'); + $this->request; if (!$request->getAttribute('mediaType')) { // NegotiationMiddleware not present return $handler; @@ -104,10 +111,10 @@ protected function whoopsHandler(\Throwable $e) switch ($request->getAttribute('mediaType')->getSubPart()) { case 'json': - $handler = new JsonResponseHandler; + $handler = new JsonResponseHandler(); break; case 'xml': - $handler = new XmlResponseHandler; + $handler = new XmlResponseHandler(); break; } return $handler; @@ -120,7 +127,7 @@ protected function whoopsHandler(\Throwable $e) */ protected function whoops(): Run { - $whoops = new Run; + $whoops = new Run(); $whoops->allowQuit(false); $whoops->writeToOutput(false); return $whoops; diff --git a/src/Model.php b/src/Model.php index 9132b18..67faed9 100755 --- a/src/Model.php +++ b/src/Model.php @@ -32,7 +32,7 @@ public function __construct(ContainerInterface $container, array $options = []) $this->container($container); $this->options($options); $this->container()->get('app')->bindImplementedEvents($this); - $this->container()->get('app')->eventsDispatcher()->fire("model.{static::classPrefix()}.initialize", [$this]); + $this->container()->get('app')->eventsDispatcher()->dispatch("model.{static::classPrefix()}.initialize", [$this]); } /** diff --git a/src/PsrContainer.php b/src/PsrContainer.php new file mode 100755 index 0000000..58ff905 --- /dev/null +++ b/src/PsrContainer.php @@ -0,0 +1,75 @@ +offsetGet($id); + } + + /** + * Returns true if the container can return an entry for the given identifier. + * Returns false otherwise. + * + * @param string $id Identifier of the entry to look for. + * + * @return boolean + */ + public function has($id) + { + return $this->offsetExists($id); + } + + public function set($id, $value) + { + $this->offsetSet($id, $value); + } + + /******************************************************************************** + * Magic methods for convenience + *******************************************************************************/ + + public function __get($name) + { + return $this->get($name); + } + + public function __set($name, $value) + { + $this->set($name, $value); + } + + public function __isset($name) + { + return $this->has($name); + } +} diff --git a/src/components/Collection/Collection.php b/src/components/Collection/Collection.php new file mode 100755 index 0000000..99959f9 --- /dev/null +++ b/src/components/Collection/Collection.php @@ -0,0 +1,197 @@ + $value) { + $this->set($key, $value); + } + } + + /******************************************************************************** + * Collection interface + *******************************************************************************/ + + /** + * Set collection item + * + * @param string $key The data key + * @param mixed $value The data value + */ + public function set($key, $value) + { + $this->data[$key] = $value; + } + + /** + * Get collection item for key + * + * @param string $key The data key + * @param mixed $default The default value to return if data key does not exist + * + * @return mixed The key's value, or the default value + */ + public function get($key, $default = null) + { + return $this->has($key) ? $this->data[$key] : $default; + } + + /** + * Add item to collection + * + * @param array $items Key-value array of data to append to this collection + */ + public function replace(array $items) + { + foreach ($items as $key => $value) { + $this->set($key, $value); + } + } + + /** + * Get all items in collection + * + * @return array The collection's source data + */ + public function all() + { + return $this->data; + } + + /** + * Get collection keys + * + * @return array The collection's source data keys + */ + public function keys() + { + return array_keys($this->data); + } + + /** + * Does this collection have a given key? + * + * @param string $key The data key + * + * @return bool + */ + public function has($key) + { + return array_key_exists($key, $this->data); + } + + /** + * Remove item from collection + * + * @param string $key The data key + */ + public function remove($key) + { + unset($this->data[$key]); + } + + /** + * Remove all items from collection + */ + public function clear() + { + $this->data = []; + } + + /******************************************************************************** + * ArrayAccess interface + *******************************************************************************/ + + /** + * Does this collection have a given key? + * + * @param string $key The data key + * + * @return bool + */ + public function offsetExists($key) + { + return $this->has($key); + } + + /** + * Get collection item for key + * + * @param string $key The data key + * + * @return mixed The key's value, or the default value + */ + public function offsetGet($key) + { + return $this->get($key); + } + + /** + * Set collection item + * + * @param string $key The data key + * @param mixed $value The data value + */ + public function offsetSet($key, $value) + { + $this->set($key, $value); + } + + /** + * Remove item from collection + * + * @param string $key The data key + */ + public function offsetUnset($key) + { + $this->remove($key); + } + + /** + * Get number of items in collection + * + * @return int + */ + public function count() + { + return count($this->data); + } + + /******************************************************************************** + * IteratorAggregate interface + *******************************************************************************/ + + /** + * Get collection iterator + * + * @return \ArrayIterator + */ + public function getIterator() + { + return new ArrayIterator($this->data); + } +} diff --git a/src/components/Collection/CollectionInterface.php b/src/components/Collection/CollectionInterface.php new file mode 100755 index 0000000..7184d21 --- /dev/null +++ b/src/components/Collection/CollectionInterface.php @@ -0,0 +1,23 @@ +get('environment')); + }; + } + + if (!isset($container['response'])) { + /** + * PSR-7 Response object + * + * @param Container $container + * + * @return ResponseInterface + */ + $container['response'] = function ($container) { + $headers = new Headers(['Content-Type' => 'text/html; charset=UTF-8']); + $response = new Response(200, $headers); + + return $response->withProtocolVersion($container->get('settings')['httpVersion']); + }; + } + + if (!isset($container['router'])) { + /** + * This service MUST return a SHARED instance + * of \Slim\Interfaces\RouterInterface. + * + * @return RouterInterface + */ + $container['router'] = function () { + return new Router; + }; + } + + if (!isset($container['foundHandler'])) { + /** + * This service MUST return a SHARED instance + * of \Slim\Interfaces\InvocationStrategyInterface. + * + * @return InvocationStrategyInterface + */ + $container['foundHandler'] = function () { + return new RequestResponse; + }; + } + + if (!isset($container['phpErrorHandler'])) { + /** + * This service MUST return a callable + * that accepts three arguments: + * + * 1. Instance of \Psr\Http\Message\ServerRequestInterface + * 2. Instance of \Psr\Http\Message\ResponseInterface + * 3. Instance of \Error + * + * The callable MUST return an instance of + * \Psr\Http\Message\ResponseInterface. + * + * @param Container $container + * + * @return callable + */ + $container['phpErrorHandler'] = function ($container) { + return new PhpError($container->get('settings')['displayErrorDetails']); + }; + } + + if (!isset($container['errorHandler'])) { + /** + * This service MUST return a callable + * that accepts three arguments: + * + * 1. Instance of \Psr\Http\Message\ServerRequestInterface + * 2. Instance of \Psr\Http\Message\ResponseInterface + * 3. Instance of \Exception + * + * The callable MUST return an instance of + * \Psr\Http\Message\ResponseInterface. + * + * @param Container $container + * + * @return callable + */ + $container['errorHandler'] = function ($container) { + return new Error($container->get('settings')['displayErrorDetails']); + }; + } + + if (!isset($container['notFoundHandler'])) { + /** + * This service MUST return a callable + * that accepts two arguments: + * + * 1. Instance of \Psr\Http\Message\ServerRequestInterface + * 2. Instance of \Psr\Http\Message\ResponseInterface + * + * The callable MUST return an instance of + * \Psr\Http\Message\ResponseInterface. + * + * @return callable + */ + $container['notFoundHandler'] = function () { + return new NotFound; + }; + } + + if (!isset($container['notAllowedHandler'])) { + /** + * This service MUST return a callable + * that accepts three arguments: + * + * 1. Instance of \Psr\Http\Message\ServerRequestInterface + * 2. Instance of \Psr\Http\Message\ResponseInterface + * 3. Array of allowed HTTP methods + * + * The callable MUST return an instance of + * \Psr\Http\Message\ResponseInterface. + * + * @return callable + */ + $container['notAllowedHandler'] = function () { + return new NotAllowed; + }; + } + + if (!isset($container['callableResolver'])) { + /** + * Instance of \Slim\Interfaces\CallableResolverInterface + * + * @param Container $container + * + * @return CallableResolverInterface + */ + $container['callableResolver'] = function ($container) { + return new CallableResolver($container); + }; + } + } +} diff --git a/src/components/Http/Request.php b/src/components/Http/Request.php new file mode 100755 index 0000000..f4937a7 --- /dev/null +++ b/src/components/Http/Request.php @@ -0,0 +1,41 @@ +get('Cookie', [])); + $serverParams = $environment->all(); + $body = new RequestBody(); + $uploadedFiles = UploadedFile::createFromEnvironment($environment); + + $request = new static($method, $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles); + + if ($method === 'POST' && + in_array($request->getMediaType(), ['application/x-www-form-urlencoded', 'multipart/form-data']) + ) { + // parsed body must be $_POST + $request = $request->withParsedBody($_POST); + } + return $request; + } +} diff --git a/src/components/Http/Response.php b/src/components/Http/Response.php new file mode 100755 index 0000000..af4fb4d --- /dev/null +++ b/src/components/Http/Response.php @@ -0,0 +1,17 @@ +