├── .editorconfig ├── .github └── workflows │ └── build.yml ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── composer.json ├── phpstan.neon ├── phpstyle.php └── src ├── Application.php ├── Application └── Application.php ├── Component ├── AbstractComponent.php ├── Collection.php ├── Collector.php └── ComponentInterface.php ├── ComponentCollection.php ├── Components.php ├── Configuration.php ├── Container ├── AurynContainer.php ├── Container.php ├── ContainerException.php ├── ContainerInterface.php ├── Exception │ ├── ContainerException.php │ └── NotFoundException.php ├── LeagueContainer.php ├── NotFoundException.php ├── Parameter.php ├── ReflectionContainer.php └── VanillaContainer.php ├── Debug ├── Debugger.php ├── DebuggerInterface.php ├── ErrorHandler.php ├── ErrorHandlerIntegration.php ├── ErrorHandlerInterface.php ├── Vanilla │ └── Debugger.php ├── VanillaErrorHandler.php ├── Whoops │ └── Debugger.php ├── WhoopsDebugger.php └── WhoopsErrorHandler.php ├── Dispatching ├── BaseRouter.php ├── Dispatcher.php ├── DispatcherInterface.php ├── FastRoute │ ├── Dispatcher.php │ └── Router.php ├── Phroute │ ├── Dispatcher.php │ └── Router.php ├── Router.php ├── RouterInterface.php └── Vanilla │ ├── Dispatcher.php │ └── Router.php ├── ErrorHandler ├── ErrorHandlerInterface.php └── Whoops.php ├── Http ├── HttpIntegration.php ├── LICENSE.md ├── Message.php ├── Request.php ├── Response.php ├── ServerRequest.php ├── Stream.php ├── UploadedFile.php └── Uri.php ├── Integration ├── Configuration.php ├── ConfigurationIntegration.php └── IntegrationInterface.php ├── IoC ├── Auryn.php ├── Auryn │ └── Container.php ├── AurynContainer.php ├── BaseContainer.php ├── Container.php ├── ContainerInterface.php ├── DependencyInjectorInterface.php ├── League │ └── Container.php ├── LeagueContainer.php └── Vanilla │ ├── Container.php │ └── Exception │ └── NotFoundException.php ├── Middleware ├── Callback.php ├── Delegate.php ├── Dispatcher.php ├── DispatcherInterface.php ├── Doublepass.php ├── Handler.php ├── HandlerInterface.php ├── Handlers │ ├── Handler030.php │ ├── Handler041.php │ ├── Handler050.php │ └── Handler100.php ├── Interop.php ├── Middleware.php ├── MiddlewareIntegration.php ├── MiddlewareInterface.php ├── Stratigility │ └── Middleware.php ├── StratigilityDispatcher.php ├── StratigilityMiddleware.php ├── Vanilla │ ├── Delegate.php │ └── Middleware.php ├── VanillaDelegate.php ├── VanillaMiddleware.php ├── Version.php └── Wrapper.php ├── Routing ├── Dispatcher.php ├── DispatcherInterface.php ├── FastRoute │ ├── Dispatcher.php │ └── Router.php ├── FastRouteDispatcher.php ├── FastRouteRouter.php ├── Phroute │ ├── Dispatcher.php │ └── Router.php ├── PhrouteDispatcher.php ├── PhrouteResolver.php ├── PhrouteRouter.php ├── PhrouteWrapper.php ├── Route.php ├── RouteInterface.php ├── Router.php ├── RouterInterface.php ├── RoutingIntegration.php └── Vanilla │ ├── Dispatcher.php │ └── Router.php ├── System.php ├── System ├── Handler.php ├── Lastone.php └── Routing.php └── Template ├── Renderer.php ├── RendererIntegration.php ├── RendererInterface.php ├── Twig.php ├── Twig └── Renderer.php ├── TwigLoader.php ├── TwigRenderer.php ├── Vanilla └── Renderer.php └── VanillaRenderer.php /.editorconfig: -------------------------------------------------------------------------------- 1 | ; This file is for unifying the coding style for different editors and IDEs. 2 | ; More information at http://editorconfig.org 3 | 4 | root = true 5 | 6 | [*] 7 | charset = utf-8 8 | indent_size = 4 9 | indent_style = space 10 | end_of_line = lf 11 | insert_final_newline = true 12 | trim_trailing_whitespace = true 13 | 14 | [*.md] 15 | trim_trailing_whitespace = false -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [ 'master' ] 4 | pull_request: 5 | branches: [ 'master' ] 6 | 7 | permissions: 8 | contents: read 9 | 10 | jobs: 11 | run: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | php-versions: [ '5.3', '5.4', '5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3' ] 17 | name: Run Unit Test on PHP ${{ matrix.php-versions }} 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v3 21 | 22 | - name: Install PHP 23 | uses: shivammathur/setup-php@v2 24 | with: 25 | php-version: ${{ matrix.php-versions }} 26 | 27 | - name: Check the PHP version 28 | run: php -v 29 | 30 | - name: Validate composer.json and composer.lock 31 | run: composer validate --strict 32 | 33 | - name: Install dependencies 34 | run: composer install --prefer-dist --no-progress 35 | 36 | - name: Install third-party packages for PHP 5.3 37 | if: ${{ matrix.php-versions == '5.3' }} 38 | run: composer require http-interop/http-middleware:^0.4.1 twig/twig --dev 39 | 40 | - name: Install third-party packages not for PHP 5.3 41 | if: ${{ matrix.php-versions != '5.3' }} 42 | run: composer require filp/whoops league/container nikic/fast-route phroute/phroute rdlowrey/auryn twig/twig zendframework/zend-diactoros http-interop/http-middleware:^0.4.1 --dev 43 | 44 | - name: Install third-party packages for PHP 5.4 45 | if: ${{ matrix.php-versions == '5.4' }} 46 | run: composer require zendframework/zend-stratigility --dev 47 | 48 | - name: Install third-party packages for PHP 5.5 49 | if: ${{ matrix.php-versions == '5.5' }} 50 | run: composer require zendframework/zend-stratigility --dev 51 | 52 | - name: Install third-party packages for PHP 7.1 53 | if: ${{ matrix.php-versions == '7.1' }} 54 | run: composer require zendframework/zend-stratigility --dev 55 | 56 | - name: Install third-party packages for PHP 7.2 57 | if: ${{ matrix.php-versions == '7.2' }} 58 | run: composer require zendframework/zend-stratigility --dev 59 | 60 | - name: Install third-party packages for PHP 7.3 61 | if: ${{ matrix.php-versions == '7.3' }} 62 | run: composer require zendframework/zend-stratigility --dev 63 | 64 | - name: Install third-party packages for PHP 7.4 65 | if: ${{ matrix.php-versions == '7.4' }} 66 | run: composer require zendframework/zend-stratigility --dev 67 | 68 | - name: Run test suite 69 | run: vendor/bin/phpunit --coverage-clover=coverage.clover 70 | 71 | - name: Upload coverage to Codecov 72 | uses: codecov/codecov-action@v4 73 | env: 74 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Rougin Gutib 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Slytherin 2 | 3 | [![Latest Version on Packagist][ico-version]][link-packagist] 4 | [![Software License][ico-license]][link-license] 5 | [![Build Status][ico-build]][link-build] 6 | [![Coverage Status][ico-coverage]][link-coverage] 7 | [![Total Downloads][ico-downloads]][link-downloads] 8 | 9 | Slytherin is a simple and extensible PHP micro-framework that tries to achieve a [SOLID-based design](https://en.wikipedia.org/wiki/SOLID) for creating web applications. It uses [Composer](https://getcomposer.org/) as the dependency package manager to add, update or even remove external packages. 10 | 11 | ## Background 12 | 13 | In the current state of PHP ecosystem, the mostly used PHP frameworks like [Symfony](http://symfony.com) and [Laravel](https://laravel.com) provide a great set of tools for every PHP software engineer. While the said PHP frameworks provide a kitchen-sink solution for every need (e.g., content management system (CMS), CRUD, etc.), they are sometimes overkill, overwhelming at first, or sometimes uses a strict directory structure. 14 | 15 | With this, Slytherin tries an alternative approach to only require the basic tools like [HTTP][link-wiki-http] and [Routing][link-wiki-routing] and let the application evolve from a simple API tool to a full-featured web application. With no defined directory structure, Slytherin can be used to mix and match any structure based on the application's requirements and to encourage the use of open-source packages in the PHP ecosystem. 16 | 17 | ## Basic Example 18 | 19 | Below is an example code for creating a simple application using Slytherin: 20 | 21 | ``` php 22 | // app/web/index.php 23 | 24 | use Rougin\Slytherin\Application; 25 | 26 | // Load the Composer autoloader ---- 27 | $root = dirname(dirname(__DIR__)); 28 | 29 | require "$root/vendor/autoload.php"; 30 | // --------------------------------- 31 | 32 | // Create a new application instance --- 33 | $app = new Application; 34 | // ------------------------------------- 35 | 36 | // Create a new HTTP route --- 37 | $app->get('/', function () 38 | { 39 | return 'Hello world!'; 40 | }); 41 | // --------------------------- 42 | 43 | // Then run the application after --- 44 | echo $app->run(); 45 | // ---------------------------------- 46 | ``` 47 | 48 | Kindly check the [The First "Hello World"][link-wiki-example] page in the wiki for more information in the provided sample code above. 49 | 50 | ## Upgrade Guide 51 | 52 | As Slytherin is evolving as a micro-framework, there might be some breaking changes in its internal code during development. The said changes can be found in the [Upgrade Guide][link-wiki-upgrade] page. 53 | 54 | ## Changelog 55 | 56 | Please see [CHANGELOG][link-changelog] for more information what has changed recently. 57 | 58 | ## Testing 59 | 60 | To check all written test cases, kindly install the specified third-party packages first: 61 | 62 | ``` bash 63 | $ composer request filp/whoops --dev 64 | $ composer request league/container --dev 65 | $ composer request nikic/fast-route --dev 66 | $ composer request phroute/phroute --dev 67 | $ composer request rdlowrey/auryn --dev 68 | $ composer request twig/twig --dev 69 | $ composer request zendframework/zend-diactoros --dev 70 | $ composer request zendframework/zend-stratigility --dev 71 | $ composer test 72 | ``` 73 | 74 | ## Credits 75 | 76 | Slytherin is inspired by the following packages below and their respective implementations. Their contributions improved [my understanding][link-homepage] of writing frameworks and creating application logic from scratch: 77 | 78 | * [Awesome PHP!](https://github.com/ziadoz/awesome-php) by [Jamie York](https://github.com/ziadoz); 79 | * [Codeigniter](https://codeigniter.com) by [EllisLab](https://ellislab.com)/[British Columbia Institute of Technology](http://www.bcit.ca); 80 | * [Fucking Small](https://github.com/trq/fucking-small) by [Tony Quilkey](https://github.com/trq); 81 | * [Laravel](https://laravel.com) by [Taylor Otwell](https://github.com/taylorotwell); 82 | * [No Framework Tutorial](https://github.com/PatrickLouys/no-framework-tutorial) by [Patrick Louys](https://github.com/PatrickLouys); 83 | * [PHP Design Patterns](http://designpatternsphp.readthedocs.org/en/latest) by [Dominik Liebler](https://github.com/domnikl); 84 | * [PHP Standard Recommendations](http://www.php-fig.org/psr) by [PHP-FIG](http://www.php-fig.org); 85 | * [Symfony](http://symfony.com) by [SensioLabs](https://sensiolabs.com); and 86 | * All of the [contributors][link-contributors] in this package. 87 | 88 | ## License 89 | 90 | The MIT License (MIT). Please see [LICENSE][link-license] for more information. 91 | 92 | [ico-build]: https://img.shields.io/github/actions/workflow/status/rougin/slytherin/build.yml?style=flat-square 93 | [ico-coverage]: https://img.shields.io/codecov/c/github/rougin/slytherin?style=flat-square 94 | [ico-downloads]: https://img.shields.io/packagist/dt/rougin/slytherin.svg?style=flat-square 95 | [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square 96 | [ico-version]: https://img.shields.io/packagist/v/rougin/slytherin.svg?style=flat-square 97 | 98 | [link-build]: https://github.com/rougin/slytherin/actions 99 | [link-changelog]: https://github.com/rougin/slytherin/blob/master/CHANGELOG.md 100 | [link-contributors]: https://github.com/rougin/slytherin/contributors 101 | [link-coverage]: https://app.codecov.io/gh/rougin/slytherin 102 | [link-downloads]: https://packagist.org/packages/rougin/slytherin 103 | [link-homepage]: https://roug.in 104 | [link-license]: https://github.com/rougin/slytherin/blob/master/LICENSE.md 105 | [link-packagist]: https://packagist.org/packages/rougin/slytherin 106 | [link-wiki-example]: https://github.com/rougin/slytherin/wiki/The-First-%22Hello-World%22 107 | [link-wiki-http]: https://github.com/rougin/slytherin/wiki/Http 108 | [link-wiki-routing]: https://github.com/rougin/slytherin/wiki/Routing 109 | [link-wiki-upgrade]: https://github.com/rougin/slytherin/wiki/Upgrade-Guide -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rougin/slytherin", 3 | "description": "A simple and extensible PHP micro-framework.", 4 | "keywords": [ "micro-framework", "php-framework" ], 5 | "homepage": "https://roug.in/slytherin/", 6 | "license": "MIT", 7 | "authors": 8 | [ 9 | { 10 | "email": "rougingutib@gmail.com", 11 | "homepage": "https://roug.in/", 12 | "name": "Rougin Gutib", 13 | "role": "Software Engineer" 14 | } 15 | ], 16 | "require": 17 | { 18 | "php": ">=5.3.0", 19 | "psr/http-message": "~1.0", 20 | "psr/container": "~1.0" 21 | }, 22 | "require-dev": 23 | { 24 | "phpunit/phpunit": "~4.2|~5.7|~6.0|~7.0|~8.0|~9.0", 25 | "sanmai/phpunit-legacy-adapter": "~6.1|~8.0" 26 | }, 27 | "autoload": 28 | { 29 | "psr-4": 30 | { 31 | "Rougin\\Slytherin\\": "src" 32 | } 33 | }, 34 | "autoload-dev": 35 | { 36 | "psr-4": 37 | { 38 | "Rougin\\Slytherin\\": "tests" 39 | } 40 | }, 41 | "scripts": 42 | { 43 | "test": "phpunit" 44 | } 45 | } -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | level: 9 3 | paths: 4 | - src 5 | - tests 6 | excludePaths: 7 | analyse: 8 | - src/Middleware/Handlers 9 | - src/Middleware/Interop.php -------------------------------------------------------------------------------- /phpstyle.php: -------------------------------------------------------------------------------- 1 | true); 10 | 11 | $cscp = 'control_structure_continuation_position'; 12 | $rules[$cscp] = ['position' => 'next_line']; 13 | 14 | $braces = array(); 15 | $braces['control_structures_opening_brace'] = 'next_line_unless_newline_at_signature_end'; 16 | $braces['functions_opening_brace'] = 'next_line_unless_newline_at_signature_end'; 17 | $braces['anonymous_functions_opening_brace'] = 'next_line_unless_newline_at_signature_end'; 18 | $braces['anonymous_classes_opening_brace'] = 'next_line_unless_newline_at_signature_end'; 19 | $braces['allow_single_line_empty_anonymous_classes'] = false; 20 | $braces['allow_single_line_anonymous_functions'] = false; 21 | 22 | $rules['braces_position'] = $braces; 23 | 24 | $rules['phpdoc_var_annotation_correct_order'] = true; 25 | 26 | $rules['single_quote'] = ['strings_containing_single_quote_chars' => true]; 27 | 28 | $rules['no_unused_imports'] = true; 29 | 30 | $rules['align_multiline_comment'] = true; 31 | 32 | $rules['trim_array_spaces'] = true; 33 | 34 | $visibility = array('elements' => array()); 35 | $visibility['elements'] = array('method', 'property'); 36 | $rules['visibility_required'] = $visibility; 37 | 38 | $rules['phpdoc_types_order'] = ['null_adjustment' => 'always_last']; 39 | 40 | $rules['new_with_parentheses'] = ['named_class' => false]; 41 | 42 | $rules['concat_space'] = ['spacing' => 'one']; 43 | 44 | $rules['no_empty_phpdoc'] = true; 45 | 46 | $groups = []; 47 | $groups[] = ['deprecated', 'link', 'see', 'since']; 48 | $groups[] = ['author', 'copyright', 'license']; 49 | $groups[] = ['category', 'package', 'subpackage']; 50 | $groups[] = ['property', 'property-read', 'property-write']; 51 | $groups[] = ['param']; 52 | $groups[] = ['return', 'throws']; 53 | $rules['phpdoc_separation'] = ['groups' => $groups]; 54 | 55 | $align = ['align' => 'vertical']; 56 | $align['tags'] = ['method', 'param', 'property', 'throws', 'type', 'var']; 57 | $rules['phpdoc_align'] = $align; 58 | 59 | $rules['statement_indentation'] = false; 60 | 61 | $rules['align_multiline_comment'] = true; 62 | // ----------------------------------------- 63 | 64 | $finder = new \PhpCsFixer\Finder; 65 | 66 | $finder->in((array) $paths); 67 | 68 | $config = new \PhpCsFixer\Config; 69 | 70 | $config->setRules($rules); 71 | 72 | return $config->setFinder($finder); 73 | -------------------------------------------------------------------------------- /src/Application.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Application extends Routing 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Application/Application.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Application extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Component/AbstractComponent.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | abstract class AbstractComponent implements ComponentInterface 15 | { 16 | /** 17 | * Type of the component: 18 | * container, dispatcher, debugger, http, middleware, template 19 | * 20 | * @var string 21 | */ 22 | protected $type = ''; 23 | 24 | /** 25 | * Returns the type of the component. 26 | * 27 | * @return string 28 | */ 29 | public function getType() 30 | { 31 | return $this->type; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Component/Collector.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | class Collector 18 | { 19 | /** 20 | * @var \Rougin\Slytherin\Component\ComponentInterface[] 21 | */ 22 | protected $items = array(); 23 | 24 | /** 25 | * @param \Rougin\Slytherin\Component\ComponentInterface[]|string[] $items 26 | */ 27 | public function __construct(array $items = array()) 28 | { 29 | foreach ($items as $item) 30 | { 31 | if (is_string($item)) 32 | { 33 | /** @var \Rougin\Slytherin\Component\ComponentInterface */ 34 | $item = new $item; 35 | } 36 | 37 | array_push($this->items, $item); 38 | } 39 | } 40 | 41 | /** 42 | * Creates a new collection. 43 | * 44 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 45 | * 46 | * @return \Rougin\Slytherin\Component\Collection 47 | */ 48 | public function make(ContainerInterface $container) 49 | { 50 | $collection = new Collection; 51 | 52 | $collection->setContainer($container); 53 | 54 | // If there is a defined container, set it first ----------------- 55 | foreach ($this->items as $item) 56 | { 57 | if ($item->getType() === 'container') 58 | { 59 | /** @var \Rougin\Slytherin\Container\ContainerInterface */ 60 | $result = $item->get(); 61 | 62 | $collection->setDependencyInjector($result); 63 | } 64 | } 65 | // --------------------------------------------------------------- 66 | 67 | foreach ($this->items as $item) 68 | { 69 | if ($item->getType() === 'dispatcher') 70 | { 71 | /** @var \Rougin\Slytherin\Dispatching\DispatcherInterface */ 72 | $result = $item->get(); 73 | 74 | $collection->setDispatcher($result); 75 | } 76 | 77 | if (in_array($item->getType(), array('debugger', 'error_handler'))) 78 | { 79 | /** @var \Rougin\Slytherin\Debug\DebuggerInterface */ 80 | $result = $item->get(); 81 | 82 | $collection->setErrorHandler($result); 83 | } 84 | 85 | if ($item->getType() === 'http') 86 | { 87 | /** @var array */ 88 | $result = $item->get(); 89 | 90 | /** @var \Psr\Http\Message\ServerRequestInterface */ 91 | $request = $result[0]; 92 | 93 | /** @var \Psr\Http\Message\ResponseInterface */ 94 | $response = $result[1]; 95 | 96 | $collection->setHttp($request, $response); 97 | } 98 | 99 | if ($item->getType() === 'middleware') 100 | { 101 | /** @var \Rougin\Slytherin\Middleware\DispatcherInterface */ 102 | $result = $item->get(); 103 | 104 | $collection->setMiddleware($result); 105 | } 106 | 107 | if ($item->getType() === 'template') 108 | { 109 | /** @var \Rougin\Slytherin\Template\RendererInterface */ 110 | $result = $item->get(); 111 | 112 | $collection->setTemplate($result); 113 | } 114 | } 115 | 116 | return $collection; 117 | } 118 | 119 | /** 120 | * Initializes the specified components. 121 | * 122 | * @param \Rougin\Slytherin\Component\ComponentInterface[]|string[] $components 123 | * @param \Rougin\Slytherin\IoC\ContainerInterface $container 124 | * 125 | * @return \Rougin\Slytherin\Component\Collection 126 | */ 127 | public static function get(array $components, ContainerInterface $container = null) 128 | { 129 | $self = new Collector($components); 130 | 131 | if (! $container) 132 | { 133 | $container = new Container; 134 | } 135 | 136 | return $self->make($container); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/Component/ComponentInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | interface ComponentInterface 15 | { 16 | /** 17 | * Returns an instance from the named class. 18 | * 19 | * @return mixed 20 | */ 21 | public function get(); 22 | 23 | /** 24 | * Returns the type of the component. 25 | * Could be: container, dispatcher, debugger, http, middleware, template 26 | * 27 | * @return string 28 | */ 29 | public function getType(); 30 | } 31 | -------------------------------------------------------------------------------- /src/ComponentCollection.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class ComponentCollection extends Components 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Components.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Components extends Collection 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Configuration.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Configuration extends Integration\Configuration 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Container/AurynContainer.php: -------------------------------------------------------------------------------- 1 | 16 | * @author Rougin Gutib 17 | * 18 | * @link https://github.com/rdlowrey/auryn 19 | * @link https://github.com/elazar/auryn-container-interop 20 | * 21 | * @method alias($original, $alias) 22 | * @method share($nameOrInstance) 23 | */ 24 | class AurynContainer implements ContainerInterface 25 | { 26 | /** 27 | * @var array 28 | */ 29 | protected $has = array(); 30 | 31 | /** 32 | * @var \Auryn\Injector 33 | */ 34 | protected $injector; 35 | 36 | /** 37 | * @var array 38 | */ 39 | protected $items = array(); 40 | 41 | /** 42 | * @param \Auryn\Injector $injector 43 | */ 44 | public function __construct(Injector $injector) 45 | { 46 | $this->injector = $injector; 47 | } 48 | 49 | /** 50 | * @deprecated since ~0.9, use "set" instead. 51 | * 52 | * Adds a new instance to the container. 53 | * 54 | * @param string $id 55 | * @param mixed|null $concrete 56 | * 57 | * @return self 58 | */ 59 | public function add($id, $concrete = null) 60 | { 61 | return $this->set($id, $concrete); 62 | } 63 | 64 | /** 65 | * Finds an entry of the container by its identifier and returns it. 66 | * 67 | * @param string $id 68 | * 69 | * @return mixed 70 | * @throws \Psr\Container\NotFoundExceptionInterface 71 | * @throws \Psr\Container\ContainerExceptionInterface 72 | */ 73 | public function get($id) 74 | { 75 | if (! $this->has($id)) 76 | { 77 | $message = 'Alias (%s) is not being managed by the container'; 78 | 79 | throw new Exception\NotFoundException(sprintf($message, $id)); 80 | } 81 | 82 | if (array_key_exists($id, $this->items)) 83 | { 84 | return $this->items[$id]; 85 | } 86 | 87 | return $this->injector->make($id); 88 | } 89 | 90 | /** 91 | * Returns true if the container can return an entry for the given identifier. 92 | * 93 | * @param string $id 94 | * 95 | * @return boolean 96 | */ 97 | public function has($id) 98 | { 99 | if (array_key_exists($id, $this->items)) 100 | { 101 | return true; 102 | } 103 | 104 | $filter = Injector::I_BINDINGS | Injector::I_DELEGATES; 105 | 106 | $filter = $filter | Injector::I_PREPARES | Injector::I_ALIASES; 107 | 108 | $filter = $filter | Injector::I_SHARES; 109 | 110 | $definitions = $this->injector->inspect($id, $filter); 111 | 112 | $definitions = array_filter($definitions); 113 | 114 | return ! empty($definitions) ?: class_exists($id); 115 | } 116 | 117 | /** 118 | * Sets a new instance to the container. 119 | * 120 | * @param string $id 121 | * @param mixed $concrete 122 | * 123 | * @return self 124 | */ 125 | public function set($id, $concrete) 126 | { 127 | $params = is_array($concrete) ? $concrete : array(); 128 | 129 | if (! $concrete || is_array($concrete)) 130 | { 131 | $concrete = $this->injector->make($id, $params); 132 | } 133 | 134 | $this->items[$id] = $concrete; 135 | 136 | return $this; 137 | } 138 | 139 | /** 140 | * Calls methods from the \Auryn\Injector instance. 141 | * 142 | * @param string $method 143 | * @param mixed[] $params 144 | * 145 | * @return mixed 146 | */ 147 | public function __call($method, $params) 148 | { 149 | /** @var callable $class */ 150 | $class = array($this->injector, $method); 151 | 152 | return call_user_func_array($class, $params); 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /src/Container/Container.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Container implements ContainerInterface 15 | { 16 | /** 17 | * @var array 18 | */ 19 | protected $items = array(); 20 | 21 | /** 22 | * Initializes the container instance. 23 | * 24 | * @param array $items 25 | */ 26 | public function __construct(array $items = array()) 27 | { 28 | $this->items = $items; 29 | } 30 | 31 | /** 32 | * @deprecated since ~0.9, use "set" instead. 33 | * 34 | * Adds a new instance to the container. 35 | * 36 | * @param string $id 37 | * @param mixed $concrete 38 | * 39 | * @return self 40 | */ 41 | public function add($id, $concrete) 42 | { 43 | return $this->set($id, $concrete); 44 | } 45 | 46 | /** 47 | * Creates an alias for a specified class. 48 | * 49 | * @param string $id 50 | * @param string $original 51 | * 52 | * @return self 53 | */ 54 | public function alias($id, $original) 55 | { 56 | $this->items[$id] = $this->get($original); 57 | 58 | return $this; 59 | } 60 | 61 | /** 62 | * Finds an entry of the container by its identifier and returns it. 63 | * 64 | * @param string $id 65 | * 66 | * @return mixed 67 | * @throws \Psr\Container\NotFoundExceptionInterface 68 | * @throws \Psr\Container\ContainerExceptionInterface 69 | */ 70 | public function get($id) 71 | { 72 | if (! $this->has($id)) 73 | { 74 | $message = 'Alias (%s) is not being managed by the container'; 75 | 76 | throw new Exception\NotFoundException(sprintf($message, $id)); 77 | } 78 | 79 | $entry = $this->items[(string) $id]; 80 | 81 | if (is_object($entry)) 82 | { 83 | return $entry; 84 | } 85 | 86 | $message = sprintf('Alias (%s) is not an object', $id); 87 | 88 | throw new Exception\ContainerException($message); 89 | } 90 | 91 | /** 92 | * Returns true if the container can return an entry for the given identifier. 93 | * 94 | * @param string $id 95 | * 96 | * @return boolean 97 | */ 98 | public function has($id) 99 | { 100 | return isset($this->items[$id]); 101 | } 102 | 103 | /** 104 | * Sets a new instance to the container. 105 | * 106 | * @param string $id 107 | * @param mixed $concrete 108 | * 109 | * @return self 110 | */ 111 | public function set($id, $concrete) 112 | { 113 | $this->items[$id] = $concrete; 114 | 115 | return $this; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/Container/ContainerException.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class ContainerException extends \Exception implements ContainerExceptionInterface 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Container/ContainerInterface.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | interface ContainerInterface extends PsrContainerInterface 17 | { 18 | /** 19 | * Sets a new instance to the container. 20 | * 21 | * @param string $id 22 | * @param mixed $concrete 23 | * 24 | * @return self 25 | */ 26 | public function set($id, $concrete); 27 | } 28 | -------------------------------------------------------------------------------- /src/Container/Exception/ContainerException.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class ContainerException extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Container/Exception/NotFoundException.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class NotFoundException extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Container/LeagueContainer.php: -------------------------------------------------------------------------------- 1 | 15 | * 16 | * @link https://container.thephpleague.com 17 | */ 18 | class LeagueContainer extends League implements ContainerInterface 19 | { 20 | /** 21 | * Sets a new instance to the container. 22 | * 23 | * @param string $id 24 | * @param mixed $concrete 25 | * @param boolean $shared 26 | * 27 | * @return self 28 | */ 29 | public function set($id, $concrete, $shared = false) 30 | { 31 | // Backward compatibility on versions >=3.0 --- 32 | $exists = method_exists($this, 'addShared'); 33 | 34 | if ($shared && $exists) 35 | { 36 | /** @var callable */ 37 | $class = array($this, 'addShared'); 38 | 39 | $params = array($id, $concrete); 40 | 41 | call_user_func_array($class, $params); 42 | } 43 | // -------------------------------------------- 44 | 45 | // Added $shared for backward compatibility --- 46 | /** @phpstan-ignore-next-line */ 47 | $this->add($id, $concrete, $shared); 48 | // -------------------------------------------- 49 | 50 | return $this; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Container/NotFoundException.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class NotFoundException extends \InvalidArgumentException implements NotFoundExceptionInterface 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Container/Parameter.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Parameter 15 | { 16 | /** 17 | * @var \ReflectionParameter 18 | */ 19 | protected $param; 20 | 21 | /** 22 | * Initializes the parameter instance. 23 | * 24 | * @param \ReflectionParameter $param 25 | */ 26 | public function __construct(\ReflectionParameter $param) 27 | { 28 | $this->param = $param; 29 | } 30 | 31 | /** 32 | * Returns a \ReflectionClass object for the parameter being reflected or "null". 33 | * 34 | * @return \ReflectionClass|null 35 | * 36 | * @codeCoverageIgnore 37 | */ 38 | public function getClass() 39 | { 40 | $php8 = version_compare(PHP_VERSION, '8.0.0', '>='); 41 | 42 | if (! $php8) 43 | { 44 | return call_user_func(array($this->param, 'getClass')); 45 | } 46 | 47 | $type = call_user_func(array($this->param, 'getType')); 48 | 49 | $builtIn = true; 50 | 51 | if ($type) 52 | { 53 | $builtIn = call_user_func(array($type, 'isBuiltin')); 54 | } 55 | 56 | if ($builtIn) 57 | { 58 | return null; 59 | } 60 | 61 | /** @var callable */ 62 | $class = array($type, 'getName'); 63 | 64 | return new \ReflectionClass(call_user_func($class)); 65 | } 66 | 67 | /** 68 | * @return string 69 | */ 70 | public function getName() 71 | { 72 | return $this->getClass() ? $this->getClass()->getName() : $this->param->getName(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/Container/ReflectionContainer.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class ReflectionContainer implements PsrContainer 17 | { 18 | /** 19 | * @var \Psr\Container\ContainerInterface|null 20 | */ 21 | protected $container = null; 22 | 23 | /** 24 | * @param \Psr\Container\ContainerInterface|null $container 25 | */ 26 | public function __construct(PsrContainer $container = null) 27 | { 28 | $this->container = $container; 29 | } 30 | 31 | /** 32 | * Finds an entry of the container by its identifier and returns it. 33 | * 34 | * @param string $id 35 | * 36 | * @return mixed 37 | * @throws \Psr\Container\NotFoundExceptionInterface 38 | * @throws \Psr\Container\ContainerExceptionInterface 39 | * 40 | * @link https://petersuhm.com/recursively-resolving-dependencies-with-phps-reflection-api-part-1 41 | */ 42 | public function get($id) 43 | { 44 | if (! $this->has($id)) 45 | { 46 | $message = 'Alias (%s) is not being managed by the container'; 47 | 48 | throw new Exception\NotFoundException(sprintf($message, $id)); 49 | } 50 | 51 | if ($this->container && $this->container->has($id)) 52 | { 53 | return $this->container->get((string) $id); 54 | } 55 | 56 | /** @var class-string $id */ 57 | $reflection = new \ReflectionClass((string) $id); 58 | 59 | if ($constructor = $reflection->getConstructor()) 60 | { 61 | $arguments = $this->resolve($constructor); 62 | 63 | return $reflection->newInstanceArgs($arguments); 64 | } 65 | 66 | return new $id; 67 | } 68 | 69 | /** 70 | * Resolves the specified parameters from a container. 71 | * 72 | * @param \ReflectionFunctionAbstract $reflector 73 | * @param array $parameters 74 | * 75 | * @return array 76 | */ 77 | public function getArguments(\ReflectionFunctionAbstract $reflector, $parameters = array()) 78 | { 79 | $items = $reflector->getParameters(); 80 | 81 | $result = array(); 82 | 83 | foreach ($items as $key => $item) 84 | { 85 | $argument = $this->getArgument($item); 86 | 87 | $name = (string) $item->getName(); 88 | 89 | if (array_key_exists($name, $parameters)) 90 | { 91 | $result[$key] = $parameters[$name]; 92 | } 93 | 94 | if ($argument) 95 | { 96 | $result[$key] = $argument; 97 | } 98 | } 99 | 100 | return $result; 101 | } 102 | 103 | /** 104 | * Returns true if the container can return an entry for the given identifier. 105 | * 106 | * @param string $id 107 | * 108 | * @return boolean 109 | */ 110 | public function has($id) 111 | { 112 | $fromContainer = false; 113 | 114 | if ($this->container) 115 | { 116 | $fromContainer = $this->container->has($id); 117 | } 118 | 119 | return class_exists($id) || $fromContainer; 120 | } 121 | 122 | /** 123 | * Returns an argument based on the given parameter. 124 | * 125 | * @param \ReflectionParameter $parameter 126 | * 127 | * @return mixed|null 128 | */ 129 | protected function getArgument(\ReflectionParameter $parameter) 130 | { 131 | try 132 | { 133 | $argument = $parameter->getDefaultValue(); 134 | } 135 | catch (\ReflectionException $exception) 136 | { 137 | // Backward compatibility for ReflectionParameter --- 138 | $param = new Parameter($parameter); 139 | // -------------------------------------------------- 140 | 141 | $argument = null; 142 | 143 | if ($this->has($name = $param->getName())) 144 | { 145 | $argument = $this->get((string) $name); 146 | } 147 | } 148 | 149 | return $argument; 150 | } 151 | 152 | /** 153 | * Resolves the specified parameters from a container. 154 | * 155 | * @param \ReflectionFunction|\ReflectionMethod $reflection 156 | * 157 | * @return array 158 | */ 159 | protected function resolve($reflection) 160 | { 161 | $items = $reflection->getParameters(); 162 | 163 | $result = array(); 164 | 165 | foreach ($items as $key => $item) 166 | { 167 | $result[$key] = $this->getArgument($item); 168 | } 169 | 170 | return $result; 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /src/Container/VanillaContainer.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class VanillaContainer extends Container 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Debug/Debugger.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Debugger extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Debug/DebuggerInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | interface DebuggerInterface extends ErrorHandlerInterface 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Debug/ErrorHandler.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class ErrorHandler implements ErrorHandlerInterface 15 | { 16 | /** 17 | * @var string 18 | */ 19 | protected $environment = ''; 20 | 21 | /** 22 | * @param string $environment 23 | */ 24 | public function __construct($environment = 'development') 25 | { 26 | $this->environment = $environment; 27 | } 28 | 29 | /** 30 | * @deprecated since ~0.9, already not part of the "ErrorHandlerInterface". 31 | * 32 | * Sets up the environment to be used. 33 | * 34 | * @param string $environment 35 | * 36 | * @return self 37 | */ 38 | public function setEnvironment($environment) 39 | { 40 | $this->environment = $environment; 41 | 42 | return $this; 43 | } 44 | 45 | /** 46 | * @deprecated since ~0.9, already not part of the "ErrorHandlerInterface". 47 | * 48 | * Returns the specified environment. 49 | * 50 | * @return string 51 | */ 52 | public function getEnvironment() 53 | { 54 | return $this->environment; 55 | } 56 | 57 | /** 58 | * Registers the instance as an error handler. 59 | * 60 | * @return void 61 | */ 62 | public function display() 63 | { 64 | error_reporting(E_ALL); 65 | 66 | ini_set('display_errors', '1'); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/Debug/ErrorHandlerIntegration.php: -------------------------------------------------------------------------------- 1 | 18 | */ 19 | class ErrorHandlerIntegration implements IntegrationInterface 20 | { 21 | /** 22 | * Defines the specified integration. 23 | * 24 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 25 | * @param \Rougin\Slytherin\Integration\Configuration $config 26 | * 27 | * @return \Rougin\Slytherin\Container\ContainerInterface 28 | */ 29 | public function define(ContainerInterface $container, Configuration $config) 30 | { 31 | /** @var string */ 32 | $environment = $config->get('app.environment', 'development'); 33 | 34 | if ($environment !== 'development') 35 | { 36 | return $container; 37 | } 38 | 39 | $handler = new ErrorHandler($environment); 40 | 41 | if (interface_exists('Whoops\RunInterface')) 42 | { 43 | $whoops = new \Whoops\Run; 44 | 45 | $handler = new WhoopsErrorHandler($whoops, $environment); 46 | } 47 | 48 | return $container->set(System::DEBUGGER, $handler); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Debug/ErrorHandlerInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | interface ErrorHandlerInterface 15 | { 16 | /** 17 | * Registers the instance as an error handler. 18 | * 19 | * @return void 20 | */ 21 | public function display(); 22 | } 23 | -------------------------------------------------------------------------------- /src/Debug/Vanilla/Debugger.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Debugger extends VanillaErrorHandler 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Debug/VanillaErrorHandler.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class VanillaErrorHandler extends ErrorHandler 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Debug/Whoops/Debugger.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Debugger extends WhoopsErrorHandler 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Debug/WhoopsDebugger.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class WhoopsDebugger extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Debug/WhoopsErrorHandler.php: -------------------------------------------------------------------------------- 1 | 16 | * 17 | * @link https://filp.github.io/whoops 18 | */ 19 | class WhoopsErrorHandler implements ErrorHandlerInterface 20 | { 21 | /** 22 | * @var string 23 | */ 24 | protected $environment = ''; 25 | 26 | /** 27 | * @var \Whoops\Run 28 | */ 29 | protected $whoops; 30 | 31 | /** 32 | * @param \Whoops\Run $whoops 33 | * @param string $environment 34 | */ 35 | public function __construct(Run $whoops, $environment = 'development') 36 | { 37 | $this->environment = $environment; 38 | 39 | $this->whoops = $whoops; 40 | } 41 | 42 | /** 43 | * @deprecated since ~0.9, already not part of the "ErrorHandlerInterface". 44 | * 45 | * Sets up the environment to be used. 46 | * 47 | * @param string $environment 48 | * 49 | * @return self 50 | */ 51 | public function setEnvironment($environment) 52 | { 53 | $this->environment = $environment; 54 | 55 | return $this; 56 | } 57 | 58 | /** 59 | * @deprecated since ~0.9, already not part of the "ErrorHandlerInterface". 60 | * 61 | * Returns the specified environment. 62 | * 63 | * @return string 64 | */ 65 | public function getEnvironment() 66 | { 67 | return $this->environment; 68 | } 69 | 70 | /** 71 | * @deprecated since ~0.9, use magic method "__call" instead. 72 | * 73 | * Returns a listing of handlers. 74 | * 75 | * @return \Whoops\Handler\HandlerInterface[] 76 | */ 77 | public function getHandlers() 78 | { 79 | return $this->whoops->getHandlers(); 80 | } 81 | 82 | /** 83 | * Registers the instance as an error handler. 84 | * 85 | * @return void 86 | */ 87 | public function display() 88 | { 89 | $handler = new PrettyPageHandler; 90 | 91 | error_reporting(E_ALL); 92 | 93 | $this->__call('pushHandler', array($handler)); 94 | 95 | $this->whoops->register(); 96 | } 97 | 98 | /** 99 | * @deprecated since ~0.9, use magic method "__call" instead. 100 | * 101 | * Sets a handler. 102 | * 103 | * @param callable|\Whoops\Handler\HandlerInterface $handler 104 | * 105 | * @return void 106 | */ 107 | public function setHandler($handler) 108 | { 109 | $this->whoops->pushHandler($handler); 110 | } 111 | 112 | /** 113 | * Calls methods from the \Whoops\Run instance. 114 | * 115 | * @param string $method 116 | * @param mixed[] $params 117 | * 118 | * @return mixed 119 | */ 120 | public function __call($method, $params) 121 | { 122 | /** @var callable */ 123 | $class = array($this->whoops, $method); 124 | 125 | return call_user_func_array($class, $params); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/Dispatching/BaseRouter.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | abstract class BaseRouter extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/Dispatcher.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Dispatcher extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/DispatcherInterface.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | interface DispatcherInterface extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/FastRoute/Dispatcher.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Dispatcher extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/FastRoute/Router.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Router extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/Phroute/Dispatcher.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Dispatcher extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/Phroute/Router.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Router extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/Router.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Router extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/RouterInterface.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | interface RouterInterface extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/Vanilla/Dispatcher.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Dispatcher extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Dispatching/Vanilla/Router.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Router extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/ErrorHandler/ErrorHandlerInterface.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | interface ErrorHandlerInterface extends DebuggerInterface 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/ErrorHandler/Whoops.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Whoops extends Debugger 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Http/HttpIntegration.php: -------------------------------------------------------------------------------- 1 | 22 | */ 23 | class HttpIntegration implements IntegrationInterface 24 | { 25 | /** 26 | * @var string|null 27 | */ 28 | protected $preferred = null; 29 | 30 | /** 31 | * Defines the specified integration. 32 | * 33 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 34 | * @param \Rougin\Slytherin\Integration\Configuration $config 35 | * 36 | * @return \Rougin\Slytherin\Container\ContainerInterface 37 | */ 38 | public function define(ContainerInterface $container, Configuration $config) 39 | { 40 | $globals = $this->globals($config); 41 | 42 | /** @var array */ 43 | $server = $globals[0]; 44 | 45 | /** @var array */ 46 | $cookies = $globals[1]; 47 | 48 | /** @var array */ 49 | $query = $globals[2]; 50 | 51 | /** @var array> */ 52 | $files = $globals[3]; 53 | 54 | /** @var array|object|null */ 55 | $parsed = $globals[4]; 56 | 57 | $headers = $this->headers($server); 58 | 59 | $request = new ServerRequest($server, $cookies, $query, $files, $parsed); 60 | 61 | foreach ($headers as $key => $value) 62 | { 63 | $request = $request->withHeader($key, $value); 64 | } 65 | 66 | return $this->resolve($container, $request, new Response); 67 | } 68 | 69 | /** 70 | * Returns the PHP's global variables. 71 | * 72 | * @param \Rougin\Slytherin\Integration\Configuration $config 73 | * 74 | * @return array 75 | */ 76 | protected function globals(Configuration $config) 77 | { 78 | $cookies = $config->get('app.http.cookies', array()); 79 | 80 | $files = $config->get('app.http.files', array()); 81 | 82 | $get = $config->get('app.http.get', array()); 83 | 84 | $post = $config->get('app.http.post', array()); 85 | 86 | $server = $config->get('app.http.server', $this->server()); 87 | 88 | return array($server, $cookies, $get, $files, $post); 89 | } 90 | 91 | /** 92 | * Converts $_SERVER parameters to message header values. 93 | * 94 | * @param array $server 95 | * 96 | * @return array 97 | */ 98 | protected function headers(array $server) 99 | { 100 | $headers = array(); 101 | 102 | foreach ((array) $server as $key => $value) 103 | { 104 | $http = strpos($key, 'HTTP_') === 0; 105 | 106 | $string = strtolower(substr($key, 5)); 107 | 108 | $string = str_replace('_', ' ', $string); 109 | 110 | $string = ucwords(strtolower($string)); 111 | 112 | $key = str_replace(' ', '-', $string); 113 | 114 | $http && $headers[$key] = $value; 115 | } 116 | 117 | return $headers; 118 | } 119 | 120 | /** 121 | * Checks on what object will be defined to container. 122 | * 123 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 124 | * @param \Psr\Http\Message\ServerRequestInterface $request 125 | * @param \Psr\Http\Message\ResponseInterface $response 126 | * 127 | * @return \Rougin\Slytherin\Container\ContainerInterface 128 | */ 129 | protected function resolve(ContainerInterface $container, ServerRequestInterface $request, ResponseInterface $response) 130 | { 131 | $class = 'Zend\Diactoros\ServerRequestFactory'; 132 | 133 | $empty = $this->preferred === null; 134 | 135 | $wantZend = $this->preferred === 'diactoros'; 136 | 137 | if (($empty || $wantZend) && class_exists($class)) 138 | { 139 | $response = new ZendResponse; 140 | 141 | $request = ServerRequestFactory::fromGlobals(); 142 | } 143 | 144 | if (! $container->has(System::REQUEST)) 145 | { 146 | $container->set(System::REQUEST, $request); 147 | } 148 | 149 | if (! $container->has(System::RESPONSE)) 150 | { 151 | $container->set(System::RESPONSE, $response); 152 | } 153 | 154 | return $container; 155 | } 156 | 157 | /** 158 | * Returns a sample of $_SERVER values. 159 | * 160 | * @return array 161 | */ 162 | protected function server() 163 | { 164 | $server = array('SERVER_PORT' => '8000'); 165 | 166 | $server['REQUEST_METHOD'] = 'GET'; 167 | 168 | $server['REQUEST_URI'] = '/'; 169 | 170 | $server['SERVER_NAME'] = 'localhost'; 171 | 172 | $server['HTTP_CONTENT_TYPE'] = 'text/plain'; 173 | 174 | return $server; 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/Http/LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright (c) Fabien Potencier 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is furnished 8 | to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. -------------------------------------------------------------------------------- /src/Http/Message.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * For the full copyright and license information, please view the LICENSE 9 | * file that was distributed with this source code. 10 | */ 11 | 12 | namespace Rougin\Slytherin\Http; 13 | 14 | use Psr\Http\Message\StreamInterface; 15 | use Psr\Http\Message\MessageInterface; 16 | 17 | /** 18 | * Message 19 | * 20 | * @package Slytherin 21 | * 22 | * @author Kévin Dunglas 23 | * @author Rougin Gutib 24 | */ 25 | class Message implements MessageInterface 26 | { 27 | /** 28 | * @var \Psr\Http\Message\StreamInterface 29 | */ 30 | protected $body; 31 | 32 | /** 33 | * @var array 34 | */ 35 | protected $headers = array(); 36 | 37 | /** 38 | * @var string 39 | */ 40 | protected $version = '1.1'; 41 | 42 | /** 43 | * Initializes the message instance. 44 | * 45 | * @param \Psr\Http\Message\StreamInterface|null $body 46 | * @param array $headers 47 | * @param string $version 48 | */ 49 | public function __construct(StreamInterface $body = null, array $headers = array(), $version = '1.1') 50 | { 51 | if ($body === null) 52 | { 53 | $resource = fopen('php://temp', 'r+'); 54 | 55 | $resource = ! $resource ? null : $resource; 56 | 57 | $body = new Stream($resource); 58 | } 59 | 60 | $this->headers = $headers; 61 | 62 | $this->body = $body; 63 | 64 | $this->version = $version; 65 | } 66 | 67 | /** 68 | * Returns the body of the message. 69 | * 70 | * @return \Psr\Http\Message\StreamInterface 71 | */ 72 | public function getBody() 73 | { 74 | return $this->body; 75 | } 76 | 77 | /** 78 | * Retrieves a message header value by the given case-insensitive name. 79 | * 80 | * @param string $name 81 | * 82 | * @return string[] 83 | */ 84 | public function getHeader($name) 85 | { 86 | return $this->hasHeader($name) ? $this->headers[$name] : array(); 87 | } 88 | 89 | /** 90 | * Retrieves a comma-separated string of the values for a single header. 91 | * 92 | * @param string $name 93 | * 94 | * @return string 95 | */ 96 | public function getHeaderLine($name) 97 | { 98 | return $this->hasHeader($name) ? implode(',', $this->headers[$name]) : ''; 99 | } 100 | 101 | /** 102 | * Retrieves all message header values. 103 | * 104 | * @return string[][] 105 | */ 106 | public function getHeaders() 107 | { 108 | return $this->headers; 109 | } 110 | 111 | /** 112 | * Retrieves the HTTP protocol version as a string. 113 | * 114 | * @return string 115 | */ 116 | public function getProtocolVersion() 117 | { 118 | return $this->version; 119 | } 120 | 121 | /** 122 | * Retrieves a message header value by the given case-insensitive name. 123 | * 124 | * @param string $name 125 | * 126 | * @return boolean 127 | */ 128 | public function hasHeader($name) 129 | { 130 | return isset($this->headers[$name]); 131 | } 132 | 133 | /** 134 | * Returns an instance with the specified header appended with the given value. 135 | * 136 | * @param string $name 137 | * @param string|string[] $value 138 | * 139 | * @return static 140 | * @throws \InvalidArgumentException 141 | */ 142 | public function withAddedHeader($name, $value) 143 | { 144 | // TODO: Add \InvalidArgumentException 145 | 146 | $static = clone $this; 147 | 148 | if (! is_array($value)) 149 | { 150 | $static->headers[$name][] = $value; 151 | 152 | return $static; 153 | } 154 | 155 | $items = $this->getHeader($name); 156 | 157 | $value = array_merge($items, $value); 158 | 159 | $static->headers[$name] = $value; 160 | 161 | return $static; 162 | } 163 | 164 | /** 165 | * Returns an instance with the specified message body. 166 | * 167 | * @param \Psr\Http\Message\StreamInterface $body 168 | * 169 | * @return static 170 | * @throws \InvalidArgumentException 171 | */ 172 | public function withBody(StreamInterface $body) 173 | { 174 | $static = clone $this; 175 | 176 | $static->body = $body; 177 | 178 | return $static; 179 | } 180 | 181 | /** 182 | * Returns an instance with the provided value replacing the specified header. 183 | * 184 | * @param string $name 185 | * @param string|string[] $value 186 | * 187 | * @return static 188 | * @throws \InvalidArgumentException 189 | */ 190 | public function withHeader($name, $value) 191 | { 192 | // TODO: Add \InvalidArgumentException 193 | 194 | $static = clone $this; 195 | 196 | $static->headers[$name] = (array) $value; 197 | 198 | return $static; 199 | } 200 | 201 | /** 202 | * Returns an instance with the specified HTTP protocol version. 203 | * 204 | * @param string $version 205 | * 206 | * @return static 207 | */ 208 | public function withProtocolVersion($version) 209 | { 210 | $static = clone $this; 211 | 212 | $static->version = $version; 213 | 214 | return $static; 215 | } 216 | 217 | /** 218 | * Returns an instance without the specified header. 219 | * 220 | * @param string $name 221 | * 222 | * @return static 223 | */ 224 | public function withoutHeader($name) 225 | { 226 | $static = clone $this; 227 | 228 | if ($this->hasHeader($name)) 229 | { 230 | unset($static->headers[$name]); 231 | } 232 | 233 | return $static; 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/Http/Request.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * For the full copyright and license information, please view the LICENSE 9 | * file that was distributed with this source code. 10 | */ 11 | 12 | namespace Rougin\Slytherin\Http; 13 | 14 | use Psr\Http\Message\RequestInterface; 15 | use Psr\Http\Message\StreamInterface; 16 | use Psr\Http\Message\UriInterface; 17 | 18 | /** 19 | * Request 20 | * 21 | * @package Slytherin 22 | * 23 | * @author Rougin Gutib 24 | */ 25 | class Request extends Message implements RequestInterface 26 | { 27 | /** 28 | * @var string 29 | */ 30 | protected $target = '/'; 31 | 32 | /** 33 | * @var string 34 | */ 35 | protected $method = 'GET'; 36 | 37 | /** 38 | * @var \Psr\Http\Message\UriInterface 39 | */ 40 | protected $uri; 41 | 42 | /** 43 | * Initializes the request instance. 44 | * 45 | * @param string $method 46 | * @param string $target 47 | * @param \Psr\Http\Message\UriInterface|null $uri 48 | * @param \Psr\Http\Message\StreamInterface|null $body 49 | * @param array $headers 50 | * @param string $version 51 | */ 52 | public function __construct($method = 'GET', $target = '/', UriInterface $uri = null, StreamInterface $body = null, array $headers = array(), $version = '1.1') 53 | { 54 | parent::__construct($body, $headers, $version); 55 | 56 | $this->method = $method; 57 | 58 | $this->target = $target; 59 | 60 | $this->uri = $uri === null ? new Uri : $uri; 61 | } 62 | 63 | /** 64 | * Retrieves the HTTP method of the request. 65 | * 66 | * @return string 67 | */ 68 | public function getMethod() 69 | { 70 | return $this->method; 71 | } 72 | 73 | /** 74 | * Retrieves the message's request target. 75 | * 76 | * @return string 77 | */ 78 | public function getRequestTarget() 79 | { 80 | return $this->target; 81 | } 82 | 83 | /** 84 | * Retrieves the URI instance. 85 | * 86 | * @return \Psr\Http\Message\UriInterface 87 | */ 88 | public function getUri() 89 | { 90 | return $this->uri; 91 | } 92 | 93 | /** 94 | * Returns an instance with the provided HTTP method. 95 | * 96 | * @param string $method 97 | * 98 | * @return static 99 | * @throws \InvalidArgumentException 100 | */ 101 | public function withMethod($method) 102 | { 103 | // TODO: Add \InvalidArgumentException 104 | 105 | $static = clone $this; 106 | 107 | $static->method = $method; 108 | 109 | return $static; 110 | } 111 | 112 | /** 113 | * Returns an instance with the specific request-target. 114 | * 115 | * @param string $target 116 | * 117 | * @return static 118 | */ 119 | public function withRequestTarget($target) 120 | { 121 | $static = clone $this; 122 | 123 | $static->target = $target; 124 | 125 | return $static; 126 | } 127 | 128 | /** 129 | * Returns an instance with the provided URI. 130 | * 131 | * @param \Psr\Http\Message\UriInterface $uri 132 | * @param boolean $preserve 133 | * 134 | * @return static 135 | */ 136 | public function withUri(UriInterface $uri, $preserve = false) 137 | { 138 | $static = clone $this; 139 | 140 | $static->uri = $uri; 141 | 142 | if (! $preserve && $host = $uri->getHost()) 143 | { 144 | $port = $host . ':' . $uri->getPort(); 145 | 146 | $host = $uri->getPort() ? $port : $host; 147 | 148 | $static->headers['Host'] = (array) $host; 149 | } 150 | 151 | return $static; 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/Http/Response.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * For the full copyright and license information, please view the LICENSE 9 | * file that was distributed with this source code. 10 | */ 11 | 12 | namespace Rougin\Slytherin\Http; 13 | 14 | use Psr\Http\Message\ResponseInterface; 15 | use Psr\Http\Message\StreamInterface; 16 | 17 | /** 18 | * Response 19 | * 20 | * @package Slytherin 21 | * 22 | * @author Kévin Dunglas 23 | * @author Rougin Gutib 24 | */ 25 | class Response extends Message implements ResponseInterface 26 | { 27 | /** 28 | * @var integer 29 | */ 30 | protected $code = 200; 31 | 32 | /** 33 | * @var array 34 | */ 35 | protected $codes = array( 36 | 100 => 'Continue', 37 | 101 => 'Switching Protocols', 38 | 102 => 'Processing', 39 | 200 => 'OK', 40 | 201 => 'Created', 41 | 202 => 'Accepted', 42 | 203 => 'Non Authoritative Information', 43 | 204 => 'No Content', 44 | 205 => 'Reset Content', 45 | 206 => 'Partial Content', 46 | 207 => 'Multi Status', 47 | 208 => 'Already Reported', 48 | 226 => 'Im Used', 49 | 300 => 'Multiple Choices', 50 | 301 => 'Moved Permanently', 51 | 302 => 'Found', 52 | 303 => 'See Other', 53 | 304 => 'Not Modified', 54 | 305 => 'Use Proxy', 55 | 306 => 'Reserved', 56 | 307 => 'Temporary Redirect', 57 | 308 => 'Permanent Redirect', 58 | 400 => 'Bad Request', 59 | 401 => 'Unauthorized', 60 | 402 => 'Payment Required', 61 | 403 => 'Forbidden', 62 | 404 => 'Not Found', 63 | 405 => 'Method Not Allowed', 64 | 406 => 'Not Acceptable', 65 | 407 => 'Proxy Authentication Required', 66 | 408 => 'Request Timeout', 67 | 409 => 'Conflict', 68 | 410 => 'Gone', 69 | 411 => 'Length Required', 70 | 412 => 'Precondition Failed', 71 | 413 => 'Payload Too Large', 72 | 414 => 'Uri Too Long', 73 | 415 => 'Unsupported Media Type', 74 | 416 => 'Range Not Satisfiable', 75 | 417 => 'Expectation Failed', 76 | 418 => 'Im A Teapot', 77 | 421 => 'Misdirected Request', 78 | 422 => 'Unprocessable Entity', 79 | 423 => 'Locked', 80 | 424 => 'Failed Dependency', 81 | 426 => 'Upgrade Required', 82 | 428 => 'Precondition Required', 83 | 429 => 'Too Many Requests', 84 | 431 => 'Request Header Fields Too Large', 85 | 451 => 'Unavailable For Legal Reasons', 86 | 500 => 'Internal Server Error', 87 | 501 => 'Not Implemented', 88 | 502 => 'Bad Gateway', 89 | 503 => 'Service Unavailable', 90 | 504 => 'Gateway Timeout', 91 | 505 => 'Version Not Supported', 92 | 506 => 'Variant Also Negotiates', 93 | 507 => 'Insufficient Storage', 94 | 508 => 'Loop Detected', 95 | 510 => 'Not Extended', 96 | 511 => 'Network Authentication Required', 97 | ); 98 | 99 | /** 100 | * @var string 101 | */ 102 | protected $reason = 'OK'; 103 | 104 | /** 105 | * Initializes the response instance. 106 | * 107 | * @param integer $code 108 | * @param \Psr\Http\Message\StreamInterface|null $body 109 | * @param array $headers 110 | * @param string $version 111 | */ 112 | public function __construct($code = 200, StreamInterface $body = null, array $headers = array(), $version = '1.1') 113 | { 114 | parent::__construct($body, $headers, $version); 115 | 116 | $this->code = $code; 117 | 118 | $this->reason = $this->codes[$code]; 119 | } 120 | 121 | /** 122 | * Returns the response reason phrase associated with the status code. 123 | * 124 | * @return string 125 | */ 126 | public function getReasonPhrase() 127 | { 128 | return $this->reason; 129 | } 130 | 131 | /** 132 | * Returns the response status code. 133 | * 134 | * @return integer 135 | */ 136 | public function getStatusCode() 137 | { 138 | return $this->code; 139 | } 140 | 141 | /** 142 | * Returns an instance with the specified status code and, optionally, reason phrase. 143 | * 144 | * @param integer $code 145 | * @param string $reason 146 | * 147 | * @return static 148 | * @throws \InvalidArgumentException 149 | */ 150 | public function withStatus($code, $reason = '') 151 | { 152 | // TODO: Add \InvalidArgumentException 153 | 154 | $static = clone $this; 155 | 156 | $static->code = $code; 157 | 158 | $static->reason = $reason ?: $static->codes[$code]; 159 | 160 | return $static; 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/Http/ServerRequest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * For the full copyright and license information, please view the LICENSE 9 | * file that was distributed with this source code. 10 | */ 11 | 12 | namespace Rougin\Slytherin\Http; 13 | 14 | use Psr\Http\Message\ServerRequestInterface; 15 | use Psr\Http\Message\StreamInterface; 16 | use Psr\Http\Message\UriInterface; 17 | 18 | /** 19 | * Server Request 20 | * 21 | * @package Slytherin 22 | * 23 | * @author Kévin Dunglas 24 | * @author Rougin Gutib 25 | */ 26 | class ServerRequest extends Request implements ServerRequestInterface 27 | { 28 | /** 29 | * @var array 30 | */ 31 | protected $attributes = array(); 32 | 33 | /** 34 | * @var array 35 | */ 36 | protected $cookies = array(); 37 | 38 | /** 39 | * @var array|object|null 40 | */ 41 | protected $data; 42 | 43 | /** 44 | * @var array 45 | */ 46 | protected $query = array(); 47 | 48 | /** 49 | * @var array 50 | */ 51 | protected $server = array(); 52 | 53 | /** 54 | * @var array 55 | */ 56 | protected $uploaded = array(); 57 | 58 | /** 59 | * Initializes the server request instance. 60 | * 61 | * @param array $server 62 | * @param array $cookies 63 | * @param array $query 64 | * @param array> $uploaded 65 | * @param array|object|null $data 66 | * @param array $attributes 67 | * @param \Psr\Http\Message\UriInterface|null $uri 68 | * @param \Psr\Http\Message\StreamInterface|null $body 69 | * @param array $headers 70 | * @param string $version 71 | */ 72 | public function __construct(array $server, array $cookies = array(), array $query = array(), array $uploaded = array(), $data = null, array $attributes = array(), UriInterface $uri = null, StreamInterface $body = null, array $headers = array(), $version = '1.1') 73 | { 74 | $uri = $uri === null ? Uri::instance($server) : $uri; 75 | 76 | $method = $server['REQUEST_METHOD']; 77 | 78 | $target = $server['REQUEST_URI']; 79 | 80 | parent::__construct($method, $target, $uri, $body, $headers, $version); 81 | 82 | $this->cookies = $cookies; 83 | 84 | $this->data = $data; 85 | 86 | $this->query = $query; 87 | 88 | $this->server = $server; 89 | 90 | $this->uploaded = UploadedFile::normalize($uploaded); 91 | 92 | $this->attributes = $attributes; 93 | 94 | // NOTE: To be removed in v1.0.0. Attributes should be empty on default. ----- 95 | if (! $attributes) 96 | { 97 | $this->attributes = array_merge($cookies, (array) $data, $query, $server); 98 | } 99 | // --------------------------------------------------------------------------- 100 | } 101 | 102 | /** 103 | * Retrieves a single derived request attribute. 104 | * 105 | * @param string $name 106 | * @param mixed $default 107 | * 108 | * @return mixed 109 | */ 110 | public function getAttribute($name, $default = null) 111 | { 112 | return isset($this->attributes[$name]) ? $this->attributes[$name] : $default; 113 | } 114 | 115 | /** 116 | * Retrieve attributes derived from the request. 117 | * 118 | * @return array 119 | */ 120 | public function getAttributes() 121 | { 122 | return $this->attributes; 123 | } 124 | 125 | /** 126 | * Retrieve cookies. 127 | * 128 | * @return array 129 | */ 130 | public function getCookieParams() 131 | { 132 | return $this->cookies; 133 | } 134 | 135 | /** 136 | * Retrieve any parameters provided in the request body. 137 | * 138 | * @return array|object|null 139 | */ 140 | public function getParsedBody() 141 | { 142 | return $this->data; 143 | } 144 | 145 | /** 146 | * Retrieve query string arguments. 147 | * 148 | * @return array 149 | */ 150 | public function getQueryParams() 151 | { 152 | return $this->query; 153 | } 154 | 155 | /** 156 | * Retrieve server parameters. 157 | * 158 | * @return array 159 | */ 160 | public function getServerParams() 161 | { 162 | return $this->server; 163 | } 164 | 165 | /** 166 | * Retrieve normalized file upload data. 167 | * 168 | * @return array 169 | */ 170 | public function getUploadedFiles() 171 | { 172 | return $this->uploaded; 173 | } 174 | 175 | /** 176 | * Returns an instance with the specified derived request attribute. 177 | * 178 | * @param string $name 179 | * @param string $value 180 | * 181 | * @return static 182 | */ 183 | public function withAttribute($name, $value) 184 | { 185 | $static = clone $this; 186 | 187 | $static->attributes[$name] = $value; 188 | 189 | return $static; 190 | } 191 | 192 | /** 193 | * Returns an instance with the specified cookies. 194 | * 195 | * @param array $cookies 196 | * 197 | * @return static 198 | */ 199 | public function withCookieParams(array $cookies) 200 | { 201 | $static = clone $this; 202 | 203 | $static->cookies = $cookies; 204 | 205 | return $static; 206 | } 207 | 208 | /** 209 | * Returns an instance with the specified body parameters. 210 | * 211 | * @param array|object|null $data 212 | * 213 | * @return static 214 | * @throws \InvalidArgumentException 215 | */ 216 | public function withParsedBody($data) 217 | { 218 | // TODO: Add \InvalidArgumentException 219 | 220 | $static = clone $this; 221 | 222 | $static->data = $data; 223 | 224 | return $static; 225 | } 226 | 227 | /** 228 | * Returns an instance with the specified query string arguments. 229 | * 230 | * @param array $query 231 | * 232 | * @return static 233 | */ 234 | public function withQueryParams(array $query) 235 | { 236 | $static = clone $this; 237 | 238 | $static->query = $query; 239 | 240 | return $static; 241 | } 242 | 243 | /** 244 | * Create a new instance with the specified uploaded files. 245 | * 246 | * @param array $uploaded 247 | * 248 | * @return static 249 | * @throws \InvalidArgumentException 250 | */ 251 | public function withUploadedFiles(array $uploaded) 252 | { 253 | // TODO: Add \InvalidArgumentException 254 | 255 | $static = clone $this; 256 | 257 | $static->uploaded = $uploaded; 258 | 259 | return $static; 260 | } 261 | 262 | /** 263 | * Returns an instance that removes the specified derived request attribute. 264 | * 265 | * @param string $name 266 | * 267 | * @return static 268 | */ 269 | public function withoutAttribute($name) 270 | { 271 | $static = clone $this; 272 | 273 | unset($static->attributes[$name]); 274 | 275 | return $static; 276 | } 277 | } 278 | -------------------------------------------------------------------------------- /src/Http/Stream.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * For the full copyright and license information, please view the LICENSE 9 | * file that was distributed with this source code. 10 | */ 11 | 12 | namespace Rougin\Slytherin\Http; 13 | 14 | use Psr\Http\Message\StreamInterface; 15 | 16 | /** 17 | * Stream 18 | * 19 | * @package Slytherin 20 | * 21 | * @author Kévin Dunglas 22 | * @author Jérémy 'Jejem' Desvages 23 | * @author Rougin Gutib 24 | */ 25 | class Stream implements StreamInterface 26 | { 27 | /** 28 | * @var array|null 29 | */ 30 | protected $meta = null; 31 | 32 | /** 33 | * @var string[] 34 | */ 35 | protected $readable = array('r', 'r+', 'w+', 'a+', 'x+', 'c+', 'w+b'); 36 | 37 | /** 38 | * @var integer|null 39 | */ 40 | protected $size = null; 41 | 42 | /** 43 | * @var resource|null 44 | */ 45 | protected $stream = null; 46 | 47 | /** 48 | * @var string[] 49 | */ 50 | protected $writable = array('r+', 'w', 'w+', 'a', 'a+', 'x', 'x+', 'c', 'c+', 'w+b'); 51 | 52 | /** 53 | * Initializes the stream instance. 54 | * 55 | * @param resource|null $stream 56 | */ 57 | public function __construct($stream = null) 58 | { 59 | $this->stream = $stream; 60 | } 61 | 62 | /** 63 | * Reads all data from the stream into a string, from the beginning to end. 64 | * 65 | * @return string 66 | */ 67 | public function __toString() 68 | { 69 | $this->rewind(); 70 | 71 | return $this->getContents(); 72 | } 73 | 74 | /** 75 | * Closes the stream and any underlying resources. 76 | * 77 | * @return void 78 | */ 79 | public function close() 80 | { 81 | is_null($this->stream) ?: fclose($this->stream); 82 | 83 | $this->detach(); 84 | } 85 | 86 | /** 87 | * Separates any underlying resources from the stream. 88 | * 89 | * @return resource|null 90 | */ 91 | public function detach() 92 | { 93 | $stream = $this->stream; 94 | 95 | $this->meta = null; 96 | 97 | $this->size = null; 98 | 99 | $this->stream = null; 100 | 101 | return $stream; 102 | } 103 | 104 | /** 105 | * Returns true if the stream is at the end of the stream. 106 | * 107 | * @return boolean 108 | */ 109 | public function eof() 110 | { 111 | return is_null($this->stream) ?: feof($this->stream); 112 | } 113 | 114 | /** 115 | * Returns the remaining contents in a string 116 | * 117 | * @return string 118 | * @throws \RuntimeException 119 | */ 120 | public function getContents() 121 | { 122 | $unreadable = ! $this->isReadable(); 123 | 124 | if (is_null($this->stream) || $unreadable) 125 | { 126 | $message = 'Could not get contents of stream'; 127 | 128 | throw new \RuntimeException($message); 129 | } 130 | 131 | return stream_get_contents($this->stream) ?: ''; 132 | } 133 | 134 | /** 135 | * Returns stream metadata as an associative array or retrieve a specific key. 136 | * 137 | * @param string $key 138 | * 139 | * @return array|mixed|null 140 | */ 141 | public function getMetadata($key = null) 142 | { 143 | $metadata = null; 144 | 145 | if (isset($this->stream)) 146 | { 147 | $this->meta = stream_get_meta_data($this->stream); 148 | } 149 | 150 | if (isset($this->meta[$key])) 151 | { 152 | $metadata = $this->meta[$key]; 153 | } 154 | 155 | return is_null($key) ? $this->meta : $metadata; 156 | } 157 | 158 | /** 159 | * Returns the size of the stream if known. 160 | * 161 | * @return integer|null 162 | */ 163 | public function getSize() 164 | { 165 | if ($this->stream === null) 166 | { 167 | return null; 168 | } 169 | 170 | if (is_null($this->size)) 171 | { 172 | /** @var array */ 173 | $stats = fstat($this->stream); 174 | 175 | $this->size = $stats['size']; 176 | } 177 | 178 | return $this->size; 179 | } 180 | 181 | /** 182 | * Returns whether or not the stream is readable. 183 | * 184 | * @return boolean 185 | */ 186 | public function isReadable() 187 | { 188 | return in_array($this->getMetadata('mode'), $this->readable); 189 | } 190 | 191 | /** 192 | * Returns whether or not the stream is seekable. 193 | * 194 | * @return boolean 195 | */ 196 | public function isSeekable() 197 | { 198 | return $this->getMetadata('seekable') === true; 199 | } 200 | 201 | /** 202 | * Returns whether or not the stream is writable. 203 | * 204 | * @return boolean 205 | */ 206 | public function isWritable() 207 | { 208 | return in_array($this->getMetadata('mode'), $this->writable); 209 | } 210 | 211 | /** 212 | * Reads data from the stream. 213 | * 214 | * @param int<1, max> $length 215 | * 216 | * @return string 217 | * @throws \RuntimeException 218 | */ 219 | public function read($length) 220 | { 221 | $data = null; 222 | 223 | if ($this->stream) 224 | { 225 | $data = @fread($this->stream, $length); 226 | } 227 | 228 | if (! $this->isReadable() || ! $data) 229 | { 230 | $message = 'Could not read from stream'; 231 | 232 | throw new \RuntimeException($message); 233 | } 234 | 235 | return $data; 236 | } 237 | 238 | /** 239 | * Seeks to the beginning of the stream. 240 | * 241 | * @return void 242 | * @throws \RuntimeException 243 | */ 244 | public function rewind() 245 | { 246 | $this->seek(0); 247 | } 248 | 249 | /** 250 | * Seeks to a position in the stream. 251 | * 252 | * @param integer $offset 253 | * @param integer $whence 254 | * 255 | * @return void 256 | * @throws \RuntimeException 257 | */ 258 | public function seek($offset, $whence = SEEK_SET) 259 | { 260 | $seek = -1; 261 | 262 | $this->stream && $seek = fseek($this->stream, $offset, $whence); 263 | 264 | if (! $this->isSeekable() || $seek === -1) 265 | { 266 | $message = 'Could not seek in stream'; 267 | 268 | throw new \RuntimeException($message); 269 | } 270 | } 271 | 272 | /** 273 | * Returns the current position of the file read/write pointer. 274 | * 275 | * @return integer 276 | * @throws \RuntimeException 277 | */ 278 | public function tell() 279 | { 280 | $position = false; 281 | 282 | $this->stream && $position = ftell($this->stream); 283 | 284 | if (is_null($this->stream) || $position === false) 285 | { 286 | $message = 'Could not get position of pointer in stream'; 287 | 288 | throw new \RuntimeException((string) $message); 289 | } 290 | 291 | return $position; 292 | } 293 | 294 | /** 295 | * Writes data to the stream. 296 | * 297 | * @param string $string 298 | * 299 | * @return integer 300 | * @throws \RuntimeException 301 | */ 302 | public function write($string) 303 | { 304 | if (! $this->isWritable()) 305 | { 306 | throw new \RuntimeException('Stream is not writable'); 307 | } 308 | 309 | /** @var resource */ 310 | $stream = $this->stream; 311 | 312 | $this->size = null; 313 | 314 | return fwrite($stream, $string) ?: 0; 315 | } 316 | } 317 | -------------------------------------------------------------------------------- /src/Http/UploadedFile.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * For the full copyright and license information, please view the LICENSE 9 | * file that was distributed with this source code. 10 | */ 11 | 12 | namespace Rougin\Slytherin\Http; 13 | 14 | use Psr\Http\Message\UploadedFileInterface; 15 | 16 | /** 17 | * Uploaded File 18 | * 19 | * @package Slytherin 20 | * 21 | * @author Kévin Dunglas 22 | * @author Rougin Gutib 23 | */ 24 | class UploadedFile implements UploadedFileInterface 25 | { 26 | /** 27 | * @var string 28 | */ 29 | protected $file; 30 | 31 | /** 32 | * @var integer|null 33 | */ 34 | protected $size; 35 | 36 | /** 37 | * @var integer 38 | */ 39 | protected $error; 40 | 41 | /** 42 | * @var string|null 43 | */ 44 | protected $name = null; 45 | 46 | /** 47 | * @var string|null 48 | */ 49 | protected $media = null; 50 | 51 | /** 52 | * Initializes the uploaded file instance. 53 | * 54 | * @param string $file 55 | * @param integer|null $size 56 | * @param integer $error 57 | * @param string|null $name 58 | * @param string|null $media 59 | */ 60 | public function __construct($file, $size = null, $error = UPLOAD_ERR_OK, $name = null, $media = null) 61 | { 62 | $this->error = $error; 63 | 64 | $this->file = $file; 65 | 66 | $this->media = $media; 67 | 68 | $this->name = $name; 69 | 70 | $this->size = $size; 71 | } 72 | 73 | /** 74 | * Retrieves the filename sent by the client. 75 | * 76 | * @return string|null 77 | */ 78 | public function getClientFilename() 79 | { 80 | return $this->name; 81 | } 82 | 83 | /** 84 | * Retrieves the media type sent by the client. 85 | * 86 | * @return string|null 87 | */ 88 | public function getClientMediaType() 89 | { 90 | return $this->media; 91 | } 92 | 93 | /** 94 | * Retrieves the error associated with the uploaded file. 95 | * 96 | * @return integer 97 | */ 98 | public function getError() 99 | { 100 | return $this->error; 101 | } 102 | 103 | /** 104 | * Retrieves the file size. 105 | * 106 | * @return integer|null 107 | */ 108 | public function getSize() 109 | { 110 | return $this->size; 111 | } 112 | 113 | /** 114 | * Retrieves a stream representing the uploaded file. 115 | * 116 | * @return \Psr\Http\Message\StreamInterface 117 | * @throws \RuntimeException 118 | */ 119 | public function getStream() 120 | { 121 | // TODO: Add \RuntimeException 122 | 123 | $stream = fopen($this->file, 'r+'); 124 | 125 | $stream = $stream === false ? null : $stream; 126 | 127 | return new Stream($stream); 128 | } 129 | 130 | /** 131 | * Move the uploaded file to a new location. 132 | * 133 | * @param string $target 134 | * 135 | * @return void 136 | * @throws \InvalidArgumentException 137 | * @throws \RuntimeException 138 | */ 139 | public function moveTo($target) 140 | { 141 | // TODO: Add \InvalidArgumentException 142 | // TODO: Add \RuntimeException 143 | 144 | rename($this->file, $target); 145 | } 146 | 147 | /** 148 | * Parses the $_FILES into multiple \File instances. 149 | * 150 | * @param array> $uploaded 151 | * 152 | * @return array 153 | */ 154 | public static function normalize(array $uploaded) 155 | { 156 | $diversed = self::diverse($uploaded); 157 | 158 | /** @var array */ 159 | $files = array(); 160 | 161 | foreach ($diversed as $name => $file) 162 | { 163 | $items = array(); 164 | 165 | foreach ($file['name'] as $key => $value) 166 | { 167 | $items[] = self::create($file, $key); 168 | } 169 | 170 | $files[$name] = (array) $items; 171 | } 172 | 173 | return (array) $files; 174 | } 175 | 176 | /** 177 | * Creates a new UploadedFile instance. 178 | * 179 | * @param array> $file 180 | * @param integer $key 181 | * 182 | * @return \Psr\Http\Message\UploadedFileInterface 183 | */ 184 | protected static function create(array $file, $key) 185 | { 186 | /** @var string */ 187 | $tmp = $file['tmp_name'][$key]; 188 | 189 | /** @var integer */ 190 | $size = $file['size'][$key]; 191 | 192 | /** @var integer */ 193 | $error = $file['error'][$key]; 194 | 195 | /** @var string */ 196 | $original = $file['name'][$key]; 197 | 198 | /** @var string */ 199 | $type = $file['type'][$key]; 200 | 201 | return new UploadedFile($tmp, $size, $error, $original, $type); 202 | } 203 | 204 | /** 205 | * Diverse the $_FILES into a consistent result. 206 | * 207 | * @param array> $uploaded 208 | * 209 | * @return array> 210 | */ 211 | protected static function diverse(array $uploaded) 212 | { 213 | $result = array(); 214 | 215 | foreach ($uploaded as $file => $item) 216 | { 217 | foreach ($item as $key => $value) 218 | { 219 | $result[$file][$key] = (array) $value; 220 | } 221 | } 222 | 223 | return $result; 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /src/Http/Uri.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * For the full copyright and license information, please view the LICENSE 9 | * file that was distributed with this source code. 10 | */ 11 | 12 | namespace Rougin\Slytherin\Http; 13 | 14 | use Psr\Http\Message\UriInterface; 15 | 16 | /** 17 | * URI 18 | * 19 | * @package Slytherin 20 | * 21 | * @author Kévin Dunglas 22 | * @author Rougin Gutib 23 | */ 24 | class Uri implements UriInterface 25 | { 26 | /** 27 | * @var string 28 | */ 29 | protected $fragment = ''; 30 | 31 | /** 32 | * @var string 33 | */ 34 | protected $host = ''; 35 | 36 | /** 37 | * @var string 38 | */ 39 | protected $pass = ''; 40 | 41 | /** 42 | * @var string 43 | */ 44 | protected $path = ''; 45 | 46 | /** 47 | * @var integer|null 48 | */ 49 | protected $port = null; 50 | 51 | /** 52 | * @var string 53 | */ 54 | protected $query = ''; 55 | 56 | /** 57 | * @var string 58 | */ 59 | protected $scheme = ''; 60 | 61 | /** 62 | * @var string 63 | */ 64 | protected $uri = ''; 65 | 66 | /** 67 | * @var string 68 | */ 69 | protected $user = ''; 70 | 71 | /** 72 | * Initializes the URI instance. 73 | * 74 | * @param string $uri 75 | */ 76 | public function __construct($uri = '') 77 | { 78 | $parts = parse_url($uri) ?: array(); 79 | 80 | foreach ($parts as $key => $value) 81 | { 82 | $key === 'user' && $this->user = $value; 83 | 84 | $this->$key = $value; 85 | } 86 | 87 | $this->uri = (string) $uri; 88 | } 89 | 90 | /** 91 | * Return the string representation as a URI reference. 92 | * 93 | * @return string 94 | */ 95 | public function __toString() 96 | { 97 | return $this->uri; 98 | } 99 | 100 | /** 101 | * Retrieves the authority component of the URI. 102 | * 103 | * @return string 104 | */ 105 | public function getAuthority() 106 | { 107 | $authority = $this->host; 108 | 109 | if ($this->host !== '' && $this->user !== null) 110 | { 111 | $authority = $this->user . '@' . $authority; 112 | 113 | $authority = $authority . ':' . $this->port; 114 | } 115 | 116 | return $authority; 117 | } 118 | 119 | /** 120 | * Retrieves the fragment component of the URI. 121 | * 122 | * @return string 123 | */ 124 | public function getFragment() 125 | { 126 | return $this->fragment; 127 | } 128 | 129 | /** 130 | * Retrieves the host component of the URI. 131 | * 132 | * @return string 133 | */ 134 | public function getHost() 135 | { 136 | return $this->host; 137 | } 138 | 139 | /** 140 | * Retrieves the path component of the URI. 141 | * 142 | * @return string 143 | */ 144 | public function getPath() 145 | { 146 | return $this->path; 147 | } 148 | 149 | /** 150 | * Retrieves the port component of the URI. 151 | * 152 | * @return integer|null 153 | */ 154 | public function getPort() 155 | { 156 | return $this->port; 157 | } 158 | 159 | /** 160 | * Retrieves the query string of the URI. 161 | * 162 | * @return string 163 | */ 164 | public function getQuery() 165 | { 166 | return $this->query; 167 | } 168 | 169 | /** 170 | * Retrieves the scheme component of the URI. 171 | * 172 | * @return string 173 | */ 174 | public function getScheme() 175 | { 176 | return $this->scheme; 177 | } 178 | 179 | /** 180 | * Retrieves the user information component of the URI. 181 | * 182 | * @return string 183 | */ 184 | public function getUserInfo() 185 | { 186 | return $this->user; 187 | } 188 | 189 | /** 190 | * Returns an instance with the specified URI fragment. 191 | * 192 | * @param string $fragment 193 | * 194 | * @return static 195 | */ 196 | public function withFragment($fragment) 197 | { 198 | $new = clone $this; 199 | 200 | $new->fragment = $fragment; 201 | 202 | return $new; 203 | } 204 | 205 | /** 206 | * Returns an instance with the specified host. 207 | * 208 | * @param string $host 209 | * 210 | * @return static 211 | * @throws \InvalidArgumentException 212 | */ 213 | public function withHost($host) 214 | { 215 | // TODO: Add \InvalidArgumentException 216 | 217 | $new = clone $this; 218 | 219 | $new->host = $host; 220 | 221 | return $new; 222 | } 223 | 224 | /** 225 | * Returns an instance with the specified path. 226 | * 227 | * @param string $path 228 | * 229 | * @return static 230 | * @throws \InvalidArgumentException 231 | */ 232 | public function withPath($path) 233 | { 234 | // TODO: Add \InvalidArgumentException 235 | 236 | $new = clone $this; 237 | 238 | $new->path = $path; 239 | 240 | return $new; 241 | } 242 | 243 | /** 244 | * Returns an instance with the specified port. 245 | * 246 | * @param integer|null $port 247 | * 248 | * @return static 249 | * @throws \InvalidArgumentException 250 | */ 251 | public function withPort($port) 252 | { 253 | // TODO: Add \InvalidArgumentException 254 | 255 | $new = clone $this; 256 | 257 | $new->port = $port; 258 | 259 | return $new; 260 | } 261 | 262 | /** 263 | * Returns an instance with the specified query string. 264 | * 265 | * @param string $query 266 | * 267 | * @return static 268 | * @throws \InvalidArgumentException 269 | */ 270 | public function withQuery($query) 271 | { 272 | // TODO: Add \InvalidArgumentException 273 | 274 | $new = clone $this; 275 | 276 | $new->query = $query; 277 | 278 | return $new; 279 | } 280 | 281 | /** 282 | * Returns an instance with the specified scheme. 283 | * 284 | * @param string $scheme 285 | * 286 | * @return static 287 | * @throws \InvalidArgumentException 288 | */ 289 | public function withScheme($scheme) 290 | { 291 | // TODO: Add \InvalidArgumentException 292 | 293 | $new = clone $this; 294 | 295 | $new->scheme = $scheme; 296 | 297 | return $new; 298 | } 299 | 300 | /** 301 | * Returns an instance with the specified user information. 302 | * 303 | * @param string $user 304 | * @param string|null $password 305 | * 306 | * @return static 307 | */ 308 | public function withUserInfo($user, $password = null) 309 | { 310 | $new = clone $this; 311 | 312 | $new->user = $user . ':' . $password; 313 | 314 | return $new; 315 | } 316 | 317 | /** 318 | * Generates a \Psr\Http\Message\UriInterface from server variables. 319 | * 320 | * @param array $server 321 | * 322 | * @return \Psr\Http\Message\UriInterface 323 | */ 324 | public static function instance(array $server) 325 | { 326 | $secure = isset($server['HTTPS']) ? 'on' : 'off'; 327 | 328 | $http = $secure === 'off' ? 'http' : 'https'; 329 | 330 | $url = $http . '://' . $server['SERVER_NAME']; 331 | 332 | $url .= (string) $server['SERVER_PORT']; 333 | 334 | return new Uri($url . $server['REQUEST_URI']); 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /src/Integration/Configuration.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Configuration 15 | { 16 | /** 17 | * @var array 18 | */ 19 | protected $data = array(); 20 | 21 | /** 22 | * @param array|string|null $data 23 | */ 24 | public function __construct($data = null) 25 | { 26 | if (is_array($data)) 27 | { 28 | $this->data = $data; 29 | } 30 | 31 | if (is_string($data)) 32 | { 33 | $this->data = $this->load($data); 34 | } 35 | } 36 | 37 | /** 38 | * Returns the value from the specified key. 39 | * 40 | * @param string $key 41 | * @param mixed|null $default 42 | * 43 | * @return mixed 44 | */ 45 | public function get($key, $default = null) 46 | { 47 | $keys = array_filter(explode('.', $key)); 48 | 49 | $data = $this->data; 50 | 51 | for ($i = 0; $i < count($keys); $i++) 52 | { 53 | /** @var string */ 54 | $index = $keys[(int) $i]; 55 | 56 | /** @phpstan-ignore-next-line */ 57 | $data = &$data[$index]; 58 | } 59 | 60 | return $data !== null ? $data : $default; 61 | } 62 | 63 | /** 64 | * Loads the configuration from a specified directory. 65 | * 66 | * @param string $directory 67 | * 68 | * @return array 69 | */ 70 | public function load($directory) 71 | { 72 | /** @var array */ 73 | $configurations = glob($directory . '/*.php'); 74 | 75 | foreach ($configurations as $item) 76 | { 77 | $items = require $item; 78 | 79 | $name = basename($item, '.php'); 80 | 81 | $name = array($name => $items); 82 | 83 | $this->data = array_merge($this->data, $name); 84 | } 85 | 86 | return $this->data; 87 | } 88 | 89 | /** 90 | * Sets the value to the specified key. 91 | * 92 | * @param string $key 93 | * @param mixed $value 94 | * @param boolean $fromFile 95 | * 96 | * @return self 97 | */ 98 | public function set($key, $value, $fromFile = false) 99 | { 100 | $keys = array_filter(explode('.', $key)); 101 | 102 | $value = $fromFile ? require $value : $value; 103 | 104 | $this->save($keys, $this->data, $value); 105 | 106 | return $this; 107 | } 108 | 109 | /** 110 | * Saves the specified key in the list of data. 111 | * 112 | * @param array &$keys 113 | * @param array &$data 114 | * @param mixed $value 115 | * 116 | * @return mixed 117 | */ 118 | protected function save(array &$keys, &$data, $value) 119 | { 120 | $key = array_shift($keys); 121 | 122 | if (empty($keys)) 123 | { 124 | $data[$key] = $value; 125 | 126 | return $data[$key]; 127 | } 128 | 129 | if (! isset($data[$key])) 130 | { 131 | $data[$key] = array(); 132 | } 133 | 134 | return $this->save($keys, $data[$key], $value); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/Integration/ConfigurationIntegration.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | class ConfigurationIntegration implements IntegrationInterface 18 | { 19 | /** 20 | * Defines the specified integration. 21 | * 22 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 23 | * @param \Rougin\Slytherin\Integration\Configuration $config 24 | * 25 | * @return \Rougin\Slytherin\Container\ContainerInterface 26 | */ 27 | public function define(ContainerInterface $container, Configuration $config) 28 | { 29 | $alias = 'Rougin\Slytherin\Configuration'; 30 | 31 | return $container->set($alias, $config)->set(System::CONFIG, $config); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Integration/IntegrationInterface.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | interface IntegrationInterface 17 | { 18 | /** 19 | * Defines the specified integration. 20 | * 21 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 22 | * @param \Rougin\Slytherin\Integration\Configuration $config 23 | * 24 | * @return \Rougin\Slytherin\Container\ContainerInterface 25 | */ 26 | public function define(ContainerInterface $container, Configuration $config); 27 | } 28 | -------------------------------------------------------------------------------- /src/IoC/Auryn.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Auryn extends AurynContainer 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/IoC/Auryn/Container.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Container extends AurynContainer 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/IoC/AurynContainer.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class AurynContainer extends Auryn\Container 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/IoC/BaseContainer.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class BaseContainer extends Container 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/IoC/Container.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Container extends Vanilla\Container 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/IoC/ContainerInterface.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | interface ContainerInterface extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/IoC/DependencyInjectorInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | interface DependencyInjectorInterface extends ContainerInterface 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/IoC/League/Container.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Container extends LeagueContainer 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/IoC/LeagueContainer.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class LeagueContainer extends League\Container 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/IoC/Vanilla/Container.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Container extends VanillaContainer 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/IoC/Vanilla/Exception/NotFoundException.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class NotFoundException extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Middleware/Callback.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | class Callback implements MiddlewareInterface 18 | { 19 | /** 20 | * @var callable 21 | */ 22 | protected $middleware; 23 | 24 | /** 25 | * @var \Psr\Http\Message\ResponseInterface|null 26 | */ 27 | protected $response = null; 28 | 29 | /** 30 | * Initializes the middleware instance. 31 | * 32 | * @param callable $middleware 33 | * @param \Psr\Http\Message\ResponseInterface|null $response 34 | */ 35 | public function __construct($middleware, ResponseInterface $response = null) 36 | { 37 | $this->middleware = $middleware; 38 | 39 | $this->response = $response; 40 | } 41 | 42 | /** 43 | * Processes an incoming server request and return a response. 44 | * 45 | * @param \Psr\Http\Message\ServerRequestInterface $request 46 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $handler 47 | * 48 | * @return \Psr\Http\Message\ResponseInterface 49 | */ 50 | public function process(ServerRequestInterface $request, HandlerInterface $handler) 51 | { 52 | $middleware = $this->middleware; 53 | 54 | if (is_string($middleware)) 55 | { 56 | /** @var callable */ 57 | $middleware = new $middleware; 58 | } 59 | 60 | if ($this->isSinglePass($middleware)) 61 | { 62 | return $middleware($request, $handler); 63 | } 64 | 65 | // Process the double pass middlewares --- 66 | $response = $this->response; 67 | 68 | $fn = function ($request) use ($handler) 69 | { 70 | return $handler->handle($request); 71 | }; 72 | // --------------------------------------- 73 | 74 | return $middleware($request, $response, $fn); 75 | } 76 | 77 | /** 78 | * Checks if the middleware is a single-pass or a double-pass implementation. 79 | * 80 | * @param mixed $item 81 | * 82 | * @return boolean 83 | */ 84 | protected function isSinglePass($item) 85 | { 86 | if ($item instanceof \Closure) 87 | { 88 | $object = new \ReflectionFunction($item); 89 | } 90 | else 91 | { 92 | /** @var object|string $item */ 93 | $object = new \ReflectionMethod($item, '__invoke'); 94 | } 95 | 96 | return count($object->getParameters()) === 2; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/Middleware/Delegate.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Delegate extends Handler 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Middleware/Dispatcher.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | class Dispatcher implements DispatcherInterface 18 | { 19 | /** 20 | * @var \Rougin\Slytherin\Middleware\MiddlewareInterface[] 21 | */ 22 | protected $stack = array(); 23 | 24 | /** 25 | * @var \Psr\Http\Message\ResponseInterface|null 26 | */ 27 | protected $response = null; 28 | 29 | /** 30 | * @param mixed[] $stack 31 | */ 32 | public function __construct($stack = array()) 33 | { 34 | if ($stack) 35 | { 36 | $this->setStack($stack); 37 | } 38 | } 39 | 40 | /** 41 | * Returns the list of added middlewares. 42 | * 43 | * @return \Rougin\Slytherin\Middleware\MiddlewareInterface[] 44 | */ 45 | public function getStack() 46 | { 47 | return $this->stack; 48 | } 49 | 50 | /** 51 | * Processes an incoming server request and return a response, optionally 52 | * delegating to the next middleware component to create the response. 53 | * 54 | * @param \Psr\Http\Message\ServerRequestInterface $request 55 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $handler 56 | * 57 | * @return \Psr\Http\Message\ResponseInterface 58 | */ 59 | public function process(ServerRequestInterface $request, HandlerInterface $handler) 60 | { 61 | $stack = (array) $this->getStack(); 62 | 63 | $handler = new Handler($stack, $handler); 64 | 65 | return $handler->handle($request); 66 | } 67 | 68 | /** 69 | * Adds a new middleware to the end of the stack. 70 | * 71 | * @param mixed $middleware 72 | * 73 | * @return self 74 | */ 75 | public function push($middleware) 76 | { 77 | if (! is_array($middleware)) 78 | { 79 | $item = $this->transform($middleware); 80 | 81 | array_push($this->stack, $item); 82 | 83 | return $this; 84 | } 85 | 86 | foreach ($middleware as $item) 87 | { 88 | $this->push($item); 89 | } 90 | 91 | return $this; 92 | } 93 | 94 | /** 95 | * Sets a new stack of middlewares. 96 | * 97 | * @param mixed[] $stack 98 | * 99 | * @return self 100 | */ 101 | public function setStack($stack) 102 | { 103 | $result = array(); 104 | 105 | foreach ($stack as $item) 106 | { 107 | $result[] = $this->transform($item); 108 | } 109 | 110 | $this->stack = $result; 111 | 112 | return $this; 113 | } 114 | 115 | /** 116 | * @deprecated since ~0.9, use "getStack" instead. 117 | * 118 | * Returns the list of added middlewares. 119 | * 120 | * @return \Rougin\Slytherin\Middleware\MiddlewareInterface[] 121 | */ 122 | public function stack() 123 | { 124 | return $this->getStack(); 125 | } 126 | 127 | /** 128 | * Transforms the middleware into a Slytherin counterpart. 129 | * 130 | * @param mixed $middleware 131 | * 132 | * @return \Rougin\Slytherin\Middleware\MiddlewareInterface 133 | */ 134 | protected function transform($middleware) 135 | { 136 | if ($middleware instanceof MiddlewareInterface) 137 | { 138 | return $middleware; 139 | } 140 | 141 | // Set empty response for double pass middlewares --- 142 | if (! $this->response) 143 | { 144 | $this->response = new Response; 145 | } 146 | // -------------------------------------------------- 147 | 148 | if ($this->isCallable($middleware)) 149 | { 150 | /** @var callable $middleware */ 151 | return new Callback($middleware, $this->response); 152 | } 153 | 154 | return new Wrapper($middleware); 155 | } 156 | 157 | /** 158 | * Checks if the middleware is a callable. 159 | * 160 | * @param mixed $item 161 | * 162 | * @return boolean 163 | */ 164 | protected function isCallable($item) 165 | { 166 | /** @var object|string $item */ 167 | $method = method_exists($item, '__invoke'); 168 | 169 | $callable = is_callable($item); 170 | 171 | $object = is_object($item); 172 | 173 | $closure = (! $object) || $item instanceof \Closure; 174 | 175 | return ($method || $callable) && $closure; 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/Middleware/DispatcherInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | interface DispatcherInterface extends MiddlewareInterface 15 | { 16 | /** 17 | * Returns the list of added middlewares. 18 | * 19 | * @return \Rougin\Slytherin\Middleware\MiddlewareInterface[] 20 | */ 21 | public function getStack(); 22 | 23 | /** 24 | * Adds a new middleware to the end of the stack. 25 | * 26 | * @param mixed $middleware 27 | * 28 | * @return self 29 | */ 30 | public function push($middleware); 31 | 32 | /** 33 | * Sets a new stack of middlewares. 34 | * 35 | * @param mixed[] $stack 36 | * 37 | * @return self 38 | */ 39 | public function setStack($stack); 40 | } 41 | -------------------------------------------------------------------------------- /src/Middleware/Doublepass.php: -------------------------------------------------------------------------------- 1 | 16 | * 17 | * @codeCoverageIgnore 18 | */ 19 | class Doublepass implements HandlerInterface 20 | { 21 | /** 22 | * @var callable 23 | */ 24 | protected $handler; 25 | 26 | /** 27 | * @var \Psr\Http\Message\ResponseInterface 28 | */ 29 | protected $response; 30 | 31 | /** 32 | * @param callable $handler 33 | * @param \Psr\Http\Message\ResponseInterface $response 34 | */ 35 | public function __construct($handler, ResponseInterface $response) 36 | { 37 | $this->handler = $handler; 38 | 39 | $this->response = $response; 40 | } 41 | 42 | /** 43 | * @param \Psr\Http\Message\ServerRequestInterface $request 44 | * 45 | * @return \Psr\Http\Message\ResponseInterface 46 | */ 47 | public function __invoke(ServerRequestInterface $request) 48 | { 49 | return $this->handle($request); 50 | } 51 | 52 | /** 53 | * @param \Psr\Http\Message\ServerRequestInterface $request 54 | * 55 | * @return \Psr\Http\Message\ResponseInterface 56 | */ 57 | public function handle(ServerRequestInterface $request) 58 | { 59 | return call_user_func($this->handler, $request, $this->response); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/Middleware/Handler.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Handler implements HandlerInterface 17 | { 18 | /** 19 | * @var \Rougin\Slytherin\Middleware\HandlerInterface 20 | */ 21 | protected $default; 22 | 23 | /** 24 | * @var integer 25 | */ 26 | protected $index = 0; 27 | 28 | /** 29 | * @var \Rougin\Slytherin\Middleware\MiddlewareInterface[] 30 | */ 31 | protected $stack; 32 | 33 | /** 34 | * @param \Rougin\Slytherin\Middleware\MiddlewareInterface[] $stack 35 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $default 36 | */ 37 | public function __construct(array $stack, HandlerInterface $default) 38 | { 39 | $this->default = $default; 40 | 41 | $this->stack = $stack; 42 | } 43 | 44 | /** 45 | * Dispatches the next available middleware and return the response. 46 | * 47 | * @param \Psr\Http\Message\ServerRequestInterface $request 48 | * 49 | * @return \Psr\Http\Message\ResponseInterface 50 | */ 51 | public function __invoke(ServerRequestInterface $request) 52 | { 53 | return $this->handle($request); 54 | } 55 | 56 | /** 57 | * Dispatches the next available middleware and return the response. 58 | * 59 | * @param \Psr\Http\Message\ServerRequestInterface $request 60 | * 61 | * @return \Psr\Http\Message\ResponseInterface 62 | */ 63 | public function handle(ServerRequestInterface $request) 64 | { 65 | if (! isset($this->stack[$this->index])) 66 | { 67 | return $this->default->handle($request); 68 | } 69 | 70 | $item = $this->stack[(int) $this->index]; 71 | 72 | $next = $this->next(); 73 | 74 | return $item->process($request, $next); 75 | } 76 | 77 | /** 78 | * Returns the next specified middleware. 79 | * 80 | * @return \Rougin\Slytherin\Middleware\HandlerInterface 81 | */ 82 | protected function next() 83 | { 84 | $next = clone $this; 85 | 86 | $next->index++; 87 | 88 | return $next; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/Middleware/HandlerInterface.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | interface HandlerInterface 17 | { 18 | /** 19 | * Dispatches the next available middleware and return the response. 20 | * 21 | * @param \Psr\Http\Message\ServerRequestInterface $request 22 | * 23 | * @return \Psr\Http\Message\ResponseInterface 24 | */ 25 | public function handle(ServerRequestInterface $request); 26 | } 27 | -------------------------------------------------------------------------------- /src/Middleware/Handlers/Handler030.php: -------------------------------------------------------------------------------- 1 | 18 | * 19 | * @codeCoverageIgnore 20 | */ 21 | class Handler030 implements DelegateInterface, HandlerInterface 22 | { 23 | /** 24 | * @var \Rougin\Slytherin\Middleware\HandlerInterface 25 | */ 26 | protected $handler; 27 | 28 | /** 29 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $handler 30 | */ 31 | public function __construct(HandlerInterface $handler) 32 | { 33 | $this->handler = $handler; 34 | } 35 | 36 | /** 37 | * @param \Psr\Http\Message\ServerRequestInterface $request 38 | * 39 | * @return \Psr\Http\Message\ResponseInterface 40 | */ 41 | public function __invoke(ServerRequestInterface $request) 42 | { 43 | return $this->process($request); 44 | } 45 | 46 | /** 47 | * @param \Psr\Http\Message\RequestInterface $request 48 | * 49 | * @return \Psr\Http\Message\ResponseInterface 50 | */ 51 | public function handle(RequestInterface $request) 52 | { 53 | return $this->handler->handle($request); 54 | } 55 | 56 | /** 57 | * @param \Psr\Http\Message\RequestInterface $request 58 | * 59 | * @return \Psr\Http\Message\ResponseInterface 60 | */ 61 | public function process(RequestInterface $request) 62 | { 63 | return $this->handle($request); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Middleware/Handlers/Handler041.php: -------------------------------------------------------------------------------- 1 | 17 | * 18 | * @codeCoverageIgnore 19 | */ 20 | class Handler041 implements DelegateInterface, HandlerInterface 21 | { 22 | /** 23 | * @var \Rougin\Slytherin\Middleware\HandlerInterface 24 | */ 25 | protected $handler; 26 | 27 | /** 28 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $handler 29 | */ 30 | public function __construct(HandlerInterface $handler) 31 | { 32 | $this->handler = $handler; 33 | } 34 | 35 | /** 36 | * @param \Psr\Http\Message\ServerRequestInterface $request 37 | * 38 | * @return \Psr\Http\Message\ResponseInterface 39 | */ 40 | public function __invoke(ServerRequestInterface $request) 41 | { 42 | return $this->process($request); 43 | } 44 | 45 | /** 46 | * @param \Psr\Http\Message\ServerRequestInterface $request 47 | * 48 | * @return \Psr\Http\Message\ResponseInterface 49 | */ 50 | public function handle(ServerRequestInterface $request) 51 | { 52 | return $this->handler->handle($request); 53 | } 54 | 55 | /** 56 | * @param \Psr\Http\Message\RequestInterface $request 57 | * 58 | * @return \Psr\Http\Message\ResponseInterface 59 | */ 60 | public function process(ServerRequestInterface $request) 61 | { 62 | return $this->handle($request); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/Middleware/Handlers/Handler050.php: -------------------------------------------------------------------------------- 1 | 17 | * 18 | * @codeCoverageIgnore 19 | */ 20 | class Handler050 implements RequestHandlerInterface, HandlerInterface 21 | { 22 | /** 23 | * @var \Rougin\Slytherin\Middleware\HandlerInterface 24 | */ 25 | protected $handler; 26 | 27 | /** 28 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $handler 29 | */ 30 | public function __construct(HandlerInterface $handler) 31 | { 32 | $this->handler = $handler; 33 | } 34 | 35 | /** 36 | * @param \Psr\Http\Message\ServerRequestInterface $request 37 | * 38 | * @return \Psr\Http\Message\ResponseInterface 39 | */ 40 | public function __invoke(ServerRequestInterface $request) 41 | { 42 | return $this->handle($request); 43 | } 44 | 45 | /** 46 | * @param \Psr\Http\Message\ServerRequestInterface $request 47 | * 48 | * @return \Psr\Http\Message\ResponseInterface 49 | */ 50 | public function handle(ServerRequestInterface $request) 51 | { 52 | return $this->handler->handle($request); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Middleware/Handlers/Handler100.php: -------------------------------------------------------------------------------- 1 | 18 | * 19 | * @codeCoverageIgnore 20 | */ 21 | class Handler100 implements RequestHandlerInterface, HandlerInterface 22 | { 23 | /** 24 | * @var \Rougin\Slytherin\Middleware\HandlerInterface 25 | */ 26 | protected $handler; 27 | 28 | /** 29 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $handler 30 | */ 31 | public function __construct(HandlerInterface $handler) 32 | { 33 | $this->handler = $handler; 34 | } 35 | 36 | /** 37 | * @param \Psr\Http\Message\ServerRequestInterface $request 38 | * 39 | * @return \Psr\Http\Message\ResponseInterface 40 | */ 41 | public function __invoke(ServerRequestInterface $request): ResponseInterface 42 | { 43 | return $this->handle($request); 44 | } 45 | 46 | /** 47 | * @param \Psr\Http\Message\ServerRequestInterface $request 48 | * 49 | * @return \Psr\Http\Message\ResponseInterface 50 | */ 51 | public function handle(ServerRequestInterface $request): ResponseInterface 52 | { 53 | return $this->handler->handle($request); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Middleware/Interop.php: -------------------------------------------------------------------------------- 1 | 19 | * 20 | * @codeCoverageIgnore 21 | */ 22 | class Interop implements HandlerInterface 23 | { 24 | const VERSION_0_3_0 = 'Interop\Http\Middleware\DelegateInterface'; 25 | 26 | const VERSION_0_4_1 = 'Interop\Http\ServerMiddleware\DelegateInterface'; 27 | 28 | const VERSION_0_5_0 = 'Interop\Http\Server\RequestHandlerInterface'; 29 | 30 | const VERSION_1_0_0 = 'Psr\Http\Server\RequestHandlerInterface'; 31 | 32 | /** 33 | * @var mixed 34 | */ 35 | protected $handler; 36 | 37 | /** 38 | * @param mixed $handler 39 | */ 40 | public function __construct($handler) 41 | { 42 | $this->handler = $handler; 43 | } 44 | 45 | /** 46 | * Dispatches the next available middleware and return the response. 47 | * 48 | * @param \Psr\Http\Message\ServerRequestInterface $request 49 | * 50 | * @return \Psr\Http\Message\ResponseInterface 51 | */ 52 | public function __invoke(ServerRequestInterface $request) 53 | { 54 | return $this->handle($request); 55 | } 56 | 57 | /** 58 | * Dispatches the next available middleware and return the response. 59 | * 60 | * @param \Psr\Http\Message\ServerRequestInterface $request 61 | * 62 | * @return \Psr\Http\Message\ResponseInterface 63 | */ 64 | public function handle(ServerRequestInterface $request) 65 | { 66 | $version = Version::get(); 67 | 68 | $method = 'handle'; 69 | 70 | if ($version === '0.3.0' || $version === '0.4.1') 71 | { 72 | $method = 'process'; 73 | } 74 | 75 | $class = array($this->handler, $method); 76 | 77 | return call_user_func($class, $request); 78 | } 79 | 80 | /** 81 | * Checks if one of the supported versions are installed. 82 | * 83 | * @return boolean 84 | */ 85 | public static function exists() 86 | { 87 | return interface_exists(self::VERSION_0_3_0) 88 | || interface_exists(self::VERSION_0_4_1) 89 | || interface_exists(self::VERSION_0_5_0); 90 | } 91 | 92 | /** 93 | * Converts the handler into the currently installed PSR-15 implementation. 94 | * 95 | * @param mixed $handler 96 | * @param string|null $version 97 | * 98 | * @return mixed 99 | */ 100 | public static function getHandler($handler, $version = null) 101 | { 102 | switch ($version) 103 | { 104 | case '0.3.0': 105 | return new Handler030($handler); 106 | 107 | case '0.4.1': 108 | return new Handler041($handler); 109 | 110 | case '0.5.0': 111 | return new Handler050($handler); 112 | 113 | case '1.0.0': 114 | return new Handler100($handler); 115 | } 116 | 117 | if (self::hasVersion($handler, self::VERSION_0_3_0)) 118 | { 119 | return new Handler030($handler); 120 | } 121 | 122 | if (self::hasVersion($handler, self::VERSION_0_4_1)) 123 | { 124 | return new Handler041($handler); 125 | } 126 | 127 | if (self::hasVersion($handler, self::VERSION_0_5_0)) 128 | { 129 | return new Handler050($handler); 130 | } 131 | 132 | if (self::hasVersion($handler, self::VERSION_1_0_0)) 133 | { 134 | return new Handler100($handler); 135 | } 136 | 137 | return $handler; 138 | } 139 | 140 | /** 141 | * Checks if the handler is installed in the supported PSR-15 version. 142 | * 143 | * @param mixed $handler 144 | * @param string $version 145 | * 146 | * @return boolean 147 | */ 148 | public static function hasVersion($handler, $class) 149 | { 150 | return interface_exists($class) || is_a($handler, $class); 151 | } 152 | 153 | /** 154 | * Checks if the official PSR-15 is currently installed. 155 | * 156 | * @return boolean 157 | */ 158 | public static function psrExists() 159 | { 160 | return interface_exists(self::VERSION_1_0_0); 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/Middleware/Middleware.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Middleware extends Dispatcher 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Middleware/MiddlewareIntegration.php: -------------------------------------------------------------------------------- 1 | 19 | */ 20 | class MiddlewareIntegration implements IntegrationInterface 21 | { 22 | /** 23 | * @var string|null 24 | */ 25 | protected $preferred = null; 26 | 27 | /** 28 | * Defines the specified integration. 29 | * 30 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 31 | * @param \Rougin\Slytherin\Integration\Configuration $config 32 | * 33 | * @return \Rougin\Slytherin\Container\ContainerInterface 34 | */ 35 | public function define(ContainerInterface $container, Configuration $config) 36 | { 37 | /** @var array */ 38 | $stack = $config->get('app.middlewares', array()); 39 | 40 | $dispatch = new Dispatcher($stack); 41 | 42 | $empty = $this->preferred === null; 43 | 44 | // Use "zend-stratigility" if installed and preferred ------ 45 | $hasZend = class_exists('Zend\Stratigility\MiddlewarePipe'); 46 | 47 | $wantZend = $this->preferred === 'stratigility'; 48 | 49 | if (($empty || $wantZend) && $hasZend) 50 | { 51 | $pipe = new MiddlewarePipe; 52 | 53 | $dispatch = new StratigilityDispatcher($pipe); 54 | } 55 | // --------------------------------------------------------- 56 | 57 | return $container->set(System::MIDDLEWARE, $dispatch); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/Middleware/MiddlewareInterface.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | interface MiddlewareInterface 17 | { 18 | /** 19 | * Processes an incoming server request and return a response, optionally 20 | * delegating to the next middleware component to create the response. 21 | * 22 | * @param \Psr\Http\Message\ServerRequestInterface $request 23 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $handler 24 | * 25 | * @return \Psr\Http\Message\ResponseInterface 26 | */ 27 | public function process(ServerRequestInterface $request, HandlerInterface $handler); 28 | } 29 | -------------------------------------------------------------------------------- /src/Middleware/Stratigility/Middleware.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Middleware extends StratigilityDispatcher 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Middleware/StratigilityDispatcher.php: -------------------------------------------------------------------------------- 1 | 18 | * 19 | * @link https://github.com/zendframework/zend-stratigility 20 | */ 21 | class StratigilityDispatcher extends Dispatcher 22 | { 23 | /** 24 | * @var \Zend\Stratigility\MiddlewarePipe 25 | */ 26 | protected $zend; 27 | 28 | /** 29 | * @param \Zend\Stratigility\MiddlewarePipe $pipe 30 | * @param mixed[] $stack 31 | */ 32 | public function __construct(MiddlewarePipe $pipe, $stack = array()) 33 | { 34 | parent::__construct($stack); 35 | 36 | $this->zend = $pipe; 37 | } 38 | 39 | /** 40 | * Checks if the current version has a wrapper factory. 41 | * 42 | * @return boolean 43 | */ 44 | public function hasFactory() 45 | { 46 | return class_exists('Zend\Stratigility\Middleware\CallableMiddlewareWrapperFactory'); 47 | } 48 | 49 | /** 50 | * Checks if the current version implements the official PSR-15. 51 | * 52 | * @return boolean 53 | */ 54 | public function hasPsr() 55 | { 56 | return class_exists('Zend\Stratigility\Middleware\CallableMiddlewareDecorator'); 57 | } 58 | 59 | /** 60 | * Processes an incoming server request and return a response, optionally 61 | * delegating to the next middleware component to create the response. 62 | * 63 | * @param \Psr\Http\Message\ServerRequestInterface $request 64 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $handler 65 | * 66 | * @return \Psr\Http\Message\ResponseInterface 67 | */ 68 | public function process(ServerRequestInterface $request, HandlerInterface $handler) 69 | { 70 | $response = new Response; 71 | 72 | $this->setFactory($response); 73 | 74 | foreach ($this->getStack() as $item) 75 | { 76 | $item = $this->setMiddleware($item); 77 | 78 | // @codeCoverageIgnoreStart 79 | if (! $this->hasFactory() && $this->hasPsr()) 80 | { 81 | $item = $this->setPsrMiddleware($item); 82 | } 83 | // @codeCoverageIgnoreEnd 84 | 85 | /** @phpstan-ignore-next-line */ 86 | $this->zend->pipe($item); 87 | } 88 | 89 | // Force version check to 1.0.0 if using v3.0 --- 90 | $version = $this->hasPsr() ? '1.0.0' : null; 91 | // ---------------------------------------------- 92 | 93 | $next = Interop::getHandler($handler, $version); 94 | 95 | $zend = $this->zend; 96 | 97 | // @codeCoverageIgnoreStart 98 | if ($this->hasPsr()) 99 | { 100 | /** @phpstan-ignore-next-line */ 101 | return $zend->process($request, $next); 102 | } 103 | 104 | /** @phpstan-ignore-next-line */ 105 | return $zend($request, $response, $next); 106 | // @codeCoverageIgnoreEnd 107 | } 108 | 109 | /** 110 | * Sets the factory if there is a middleware decorator. 111 | * 112 | * @param \Psr\Http\Message\ResponseInterface $response 113 | * 114 | * @return void 115 | * 116 | * @codeCoverageIgnore 117 | */ 118 | protected function setFactory(ResponseInterface $response) 119 | { 120 | if (! $this->hasFactory()) 121 | { 122 | return; 123 | } 124 | 125 | /** @var class-string */ 126 | $factory = 'Zend\Stratigility\Middleware\CallableMiddlewareWrapperFactory'; 127 | 128 | $class = new \ReflectionClass((string) $factory); 129 | 130 | $factory = $class->newInstance($response); 131 | 132 | /** @var callable */ 133 | $class = array($this->zend, 'setCallableMiddlewareDecorator'); 134 | 135 | call_user_func_array($class, array($factory)); 136 | } 137 | 138 | /** 139 | * Sets the Slytherin middleware into a single-pass or double-pass callable. 140 | * 141 | * @param \Rougin\Slytherin\Middleware\MiddlewareInterface $item 142 | * 143 | * @return callable 144 | * 145 | * @codeCoverageIgnore 146 | */ 147 | protected function setMiddleware(MiddlewareInterface $item) 148 | { 149 | if ($this->hasPsr()) 150 | { 151 | return function ($request, $handler) use ($item) 152 | { 153 | return $item->process($request, new Interop($handler)); 154 | }; 155 | } 156 | 157 | return function ($request, $response, $next) use ($item) 158 | { 159 | /** @var callable $next */ 160 | $handle = new Doublepass($next, $response); 161 | 162 | return $item->process($request, $handle); 163 | }; 164 | } 165 | 166 | /** 167 | * Sets the PSR-15 decorator to a middleware. 168 | * 169 | * @param callable $item 170 | * 171 | * @return object 172 | * 173 | * @codeCoverageIgnore 174 | */ 175 | protected function setPsrMiddleware($item) 176 | { 177 | /** @var class-string */ 178 | $psr = 'Zend\Stratigility\Middleware\CallableMiddlewareDecorator'; 179 | 180 | $class = new \ReflectionClass($psr); 181 | 182 | return $class->newInstance($item); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/Middleware/StratigilityMiddleware.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class StratigilityMiddleware extends Stratigility\Middleware 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Middleware/Vanilla/Delegate.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Delegate extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Middleware/Vanilla/Middleware.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Middleware extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Middleware/VanillaDelegate.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class VanillaDelegate extends Vanilla\Delegate 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Middleware/VanillaMiddleware.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class VanillaMiddleware extends Vanilla\Middleware 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Middleware/Version.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Version 15 | { 16 | const VERSION_0_3_0 = 'Interop\Http\Middleware\ServerMiddlewareInterface'; 17 | 18 | const VERSION_0_4_0 = 'Interop\Http\ServerMiddleware\MiddlewareInterface'; 19 | 20 | const VERSION_0_5_0 = 'Interop\Http\Server\MiddlewareInterface'; 21 | 22 | const VERSION_1_0_0 = 'Psr\Http\Server\MiddlewareInterface'; 23 | 24 | /** 25 | * Returns the current version installed. 26 | * 27 | * @return string|null 28 | * 29 | * @codeCoverageIgnore 30 | */ 31 | public static function get() 32 | { 33 | $hasPsr = interface_exists(self::VERSION_1_0_0); 34 | 35 | if (! $hasPsr && interface_exists(self::VERSION_0_3_0)) 36 | { 37 | return '0.3.0'; 38 | } 39 | 40 | if (! $hasPsr && interface_exists(self::VERSION_0_4_0)) 41 | { 42 | return '0.4.1'; 43 | } 44 | 45 | if (! $hasPsr && interface_exists(self::VERSION_0_5_0)) 46 | { 47 | return '0.5.0'; 48 | } 49 | 50 | return $hasPsr ? '1.0.0' : null; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Middleware/Wrapper.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Wrapper implements MiddlewareInterface 17 | { 18 | /** 19 | * @var mixed 20 | */ 21 | protected $middleware; 22 | 23 | /** 24 | * Initializes the middleware instance. 25 | * 26 | * @param mixed $middleware 27 | */ 28 | public function __construct($middleware) 29 | { 30 | $this->middleware = $middleware; 31 | } 32 | 33 | /** 34 | * Processes an incoming server request and return a response. 35 | * 36 | * @param \Psr\Http\Message\ServerRequestInterface $request 37 | * @param \Rougin\Slytherin\Middleware\HandlerInterface $handler 38 | * 39 | * @return \Psr\Http\Message\ResponseInterface 40 | */ 41 | public function process(ServerRequestInterface $request, HandlerInterface $handler) 42 | { 43 | $middleware = $this->middleware; 44 | 45 | if (is_string($middleware)) 46 | { 47 | $middleware = new $middleware; 48 | } 49 | 50 | $next = Interop::getHandler($handler); 51 | 52 | /** @phpstan-ignore-next-line */ 53 | return $middleware->process($request, $next); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Routing/Dispatcher.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Dispatcher implements DispatcherInterface 15 | { 16 | /** 17 | * @var string[] 18 | */ 19 | protected $allowed = array('DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT'); 20 | 21 | /** 22 | * @var \Rougin\Slytherin\Routing\RouterInterface 23 | */ 24 | protected $router; 25 | 26 | /** 27 | * Initializes the route dispatcher instance. 28 | * 29 | * @param \Rougin\Slytherin\Routing\RouterInterface|null $router 30 | */ 31 | public function __construct(RouterInterface $router = null) 32 | { 33 | if ($router) 34 | { 35 | $this->setRouter($router); 36 | } 37 | } 38 | 39 | /** 40 | * Dispatches against the provided HTTP method verb and URI. 41 | * 42 | * @param string $method 43 | * @param string $uri 44 | * 45 | * @return \Rougin\Slytherin\Routing\RouteInterface 46 | * @throws \BadMethodCallException 47 | */ 48 | public function dispatch($method, $uri) 49 | { 50 | $this->validMethod($method); 51 | 52 | $uri = $uri[0] !== '/' ? '/' . $uri : $uri; 53 | 54 | $route = $this->match($method, $uri); 55 | 56 | if (! $route) 57 | { 58 | $text = (string) 'Route "%s %s" not found'; 59 | 60 | $error = sprintf($text, $method, $uri); 61 | 62 | throw new \BadMethodCallException($error); 63 | } 64 | 65 | // Parses the matched parameters back to the route -------- 66 | $params = $route->getParams(); 67 | 68 | /** @var string[] */ 69 | $filtered = array_filter(array_keys($params), 'is_string'); 70 | 71 | /** @var string[] */ 72 | $flipped = (array) array_flip($filtered); 73 | 74 | /** @var string[] */ 75 | $values = array_intersect_key($params, $flipped); 76 | // -------------------------------------------------------- 77 | 78 | return $route->setParams($values); 79 | } 80 | 81 | /** 82 | * Sets the router and parse its available routes if needed. 83 | * 84 | * @param \Rougin\Slytherin\Routing\RouterInterface $router 85 | * 86 | * @return self 87 | * @throws \UnexpectedValueException 88 | */ 89 | public function setRouter(RouterInterface $router) 90 | { 91 | $this->router = $router; 92 | 93 | return $this; 94 | } 95 | 96 | /** 97 | * Checks if the specified method is a valid HTTP method. 98 | * 99 | * @param string $method 100 | * 101 | * @return boolean 102 | * @throws \BadMethodCallException 103 | */ 104 | protected function validMethod($method) 105 | { 106 | if (in_array($method, $this->allowed)) 107 | { 108 | return true; 109 | } 110 | 111 | $message = 'Used method is not allowed (' . $method . ')'; 112 | 113 | throw new \BadMethodCallException($message); 114 | } 115 | 116 | /** 117 | * Matches the route from the parsed URI. 118 | * 119 | * @param string $method 120 | * @param string $uri 121 | * 122 | * @return \Rougin\Slytherin\Routing\RouteInterface|null 123 | */ 124 | protected function match($method, $uri) 125 | { 126 | $routes = $this->router->routes(); 127 | 128 | $isOptions = $method === 'OPTIONS'; 129 | 130 | foreach ($routes as $route) 131 | { 132 | $regex = $route->getRegex(); 133 | 134 | $matched = preg_match($regex, $uri, $matches); 135 | 136 | $sameMethod = $route->getMethod() === $method; 137 | 138 | if ($matched && ($sameMethod || $isOptions)) 139 | { 140 | return $route->setParams($matches); 141 | } 142 | } 143 | 144 | return null; 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/Routing/DispatcherInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | interface DispatcherInterface 15 | { 16 | /** 17 | * Dispatches against the provided HTTP method verb and URI. 18 | * 19 | * @param string $method 20 | * @param string $uri 21 | * 22 | * @return \Rougin\Slytherin\Routing\RouteInterface 23 | * @throws \BadMethodCallException 24 | */ 25 | public function dispatch($method, $uri); 26 | 27 | /** 28 | * Sets the router and parse its available routes if needed. 29 | * 30 | * @param \Rougin\Slytherin\Routing\RouterInterface $router 31 | * 32 | * @return self 33 | * @throws \UnexpectedValueException 34 | */ 35 | public function setRouter(RouterInterface $router); 36 | } 37 | -------------------------------------------------------------------------------- /src/Routing/FastRoute/Dispatcher.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Dispatcher extends FastRouteDispatcher 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Routing/FastRoute/Router.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Router extends FastRouteRouter 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Routing/FastRouteDispatcher.php: -------------------------------------------------------------------------------- 1 | 13 | * 14 | * @link https://github.com/nikic/FastRoute 15 | */ 16 | class FastRouteDispatcher extends Dispatcher 17 | { 18 | /** 19 | * @var \FastRoute\Dispatcher 20 | */ 21 | protected $fastroute; 22 | 23 | /** 24 | * Dispatches against the provided HTTP method verb and URI. 25 | * 26 | * @param string $method 27 | * @param string $uri 28 | * 29 | * @return \Rougin\Slytherin\Routing\RouteInterface 30 | * @throws \BadMethodCallException 31 | */ 32 | public function dispatch($method, $uri) 33 | { 34 | $this->validMethod($method); 35 | 36 | /** @var array */ 37 | $result = $this->fastroute->dispatch($method, $uri); 38 | 39 | if ($result[0] === \FastRoute\Dispatcher::NOT_FOUND) 40 | { 41 | $text = (string) 'Route "%s %s" not found'; 42 | 43 | $error = sprintf($text, $method, $uri); 44 | 45 | throw new \BadMethodCallException($error); 46 | } 47 | 48 | /** @var \Rougin\Slytherin\Routing\RouteInterface */ 49 | $route = $result[1]; 50 | 51 | /** @var array */ 52 | $params = $result[2]; 53 | 54 | return $route->setParams($params); 55 | } 56 | 57 | /** 58 | * Sets the router and parse its available routes if needed. 59 | * 60 | * @param \Rougin\Slytherin\Routing\RouterInterface $router 61 | * 62 | * @return self 63 | * @throws \UnexpectedValueException 64 | */ 65 | public function setRouter(RouterInterface $router) 66 | { 67 | $routes = $router->routes(); 68 | 69 | $parsed = $router->parsed($routes); 70 | 71 | // Force to use third-party router if not being used --- 72 | if (! is_callable($parsed)) 73 | { 74 | $fastroute = new FastRouteRouter; 75 | 76 | $parsed = $fastroute->asParsed($routes); 77 | } 78 | // ----------------------------------------------------- 79 | 80 | $this->router = $router; 81 | 82 | $this->fastroute = \FastRoute\simpleDispatcher($parsed); 83 | 84 | return $this; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/Routing/FastRouteRouter.php: -------------------------------------------------------------------------------- 1 | 17 | * 18 | * @link https://github.com/nikic/FastRoute 19 | */ 20 | class FastRouteRouter extends Router 21 | { 22 | /** 23 | * @var \FastRoute\RouteCollector 24 | */ 25 | protected $collector; 26 | 27 | /** 28 | * Initializes the router instance. 29 | * 30 | * @param array $routes 31 | */ 32 | public function __construct(array $routes = array()) 33 | { 34 | parent::__construct($routes); 35 | 36 | $this->collector = new RouteCollector(new Std, new GroupCountBased); 37 | } 38 | 39 | /** 40 | * @param \Rougin\Slytherin\Routing\RouteInterface[] $routes 41 | * 42 | * @return callable 43 | */ 44 | public function asParsed(array $routes) 45 | { 46 | /** @var callable */ 47 | return $this->parsed($routes); 48 | } 49 | 50 | /** 51 | * Returns a listing of parsed routes. 52 | * 53 | * @param \Rougin\Slytherin\Routing\RouteInterface[] $routes 54 | * 55 | * @return mixed|null 56 | */ 57 | public function parsed(array $routes = array()) 58 | { 59 | $fn = function (RouteCollector $collector) use ($routes) 60 | { 61 | foreach ($routes as $route) 62 | { 63 | // Convert the ":name" pattern into "{name}" pattern ------------------ 64 | $uri = $route->getUri(); 65 | 66 | $matched = preg_match_all('/\:([a-zA-Z0-9\_\-]+)/i', $uri, $matches); 67 | 68 | if ($matched) 69 | { 70 | foreach ($matches[0] as $key => $item) 71 | { 72 | $uri = str_replace($item, '{' . $matches[1][$key] . '}', $uri); 73 | } 74 | } 75 | // -------------------------------------------------------------------- 76 | 77 | $collector->addRoute($route->getMethod(), $uri, $route); 78 | } 79 | }; 80 | 81 | return $fn; 82 | } 83 | 84 | /** 85 | * @param \FastRoute\RouteCollector $collector 86 | * 87 | * @return self 88 | */ 89 | public function setCollector(RouteCollector $collector) 90 | { 91 | $this->collector = $collector; 92 | 93 | return $this; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/Routing/Phroute/Dispatcher.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Dispatcher extends PhrouteDispatcher 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Routing/Phroute/Router.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Router extends PhrouteRouter 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Routing/PhrouteDispatcher.php: -------------------------------------------------------------------------------- 1 | 18 | * 19 | * @link https://github.com/mrjgreen/phroute 20 | */ 21 | class PhrouteDispatcher extends Dispatcher 22 | { 23 | /** 24 | * @var \Phroute\Phroute\RouteCollector 25 | */ 26 | protected $collector; 27 | 28 | /** 29 | * @var \Phroute\Phroute\Dispatcher 30 | */ 31 | protected $dispatcher; 32 | 33 | /** 34 | * @var \Phroute\Phroute\RouteDataArray 35 | */ 36 | protected $items; 37 | 38 | /** 39 | * @var \Phroute\Phroute\HandlerResolverInterface|null 40 | */ 41 | protected $resolver; 42 | 43 | /** 44 | * @param \Rougin\Slytherin\Routing\RouterInterface|null $router 45 | * @param \Phroute\Phroute\HandlerResolverInterface|null $resolver 46 | */ 47 | public function __construct(RouterInterface $router = null, HandlerResolverInterface $resolver = null) 48 | { 49 | parent::__construct($router); 50 | 51 | if (! $resolver) 52 | { 53 | $resolver = new PhrouteResolver; 54 | } 55 | 56 | $this->resolver = $resolver; 57 | } 58 | 59 | /** 60 | * Dispatches against the provided HTTP method verb and URI. 61 | * 62 | * @param string $method 63 | * @param string $uri 64 | * 65 | * @return \Rougin\Slytherin\Routing\RouteInterface 66 | * @throws \BadMethodCallException 67 | */ 68 | public function dispatch($method, $uri) 69 | { 70 | $this->validMethod($method); 71 | 72 | $phroute = new Phroute($this->items, $this->resolver); 73 | 74 | try 75 | { 76 | /** @var \Rougin\Slytherin\Routing\RouteInterface */ 77 | $route = $phroute->dispatch($method, $uri); 78 | 79 | // Combine values from resolver and the current parameters ------------- 80 | $regex = '/\{([a-zA-Z0-9\_\-]+)\}/i'; 81 | 82 | $matched = preg_match_all($regex, $route->getUri(), $matches); 83 | 84 | // If "{name}" pattern is not found, try the ":name" pattern instead --- 85 | if (! $matched) 86 | { 87 | $regex = '/\:([a-zA-Z0-9\_\-]+)/i'; 88 | 89 | $matched = preg_match_all($regex, $route->getUri(), $matches); 90 | } 91 | // --------------------------------------------------------------------- 92 | 93 | /** @var array */ 94 | $params = array_combine($matches[1], $route->getParams()); 95 | 96 | return $route->setParams($params); 97 | // --------------------------------------------------------------------- 98 | } 99 | catch (HttpRouteNotFoundException $e) 100 | { 101 | throw new \BadMethodCallException($e->getMessage()); 102 | } 103 | } 104 | 105 | /** 106 | * Sets the router and parse its available routes if needed. 107 | * 108 | * @param \Rougin\Slytherin\Routing\RouterInterface $router 109 | * 110 | * @return self 111 | * @throws \UnexpectedValueException 112 | */ 113 | public function setRouter(RouterInterface $router) 114 | { 115 | $routes = $router->routes(); 116 | 117 | $parsed = $router->parsed($routes); 118 | 119 | // Force to use third-party router if not being used --- 120 | if (! $parsed instanceof RouteDataArray) 121 | { 122 | $phroute = new PhrouteRouter; 123 | 124 | $parsed = $phroute->asParsed($routes); 125 | } 126 | // ----------------------------------------------------- 127 | 128 | $this->router = $router; 129 | 130 | $this->items = $parsed; 131 | 132 | return $this; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/Routing/PhrouteResolver.php: -------------------------------------------------------------------------------- 1 | 15 | * 16 | * @link https://github.com/mrjgreen/phroute 17 | */ 18 | class PhrouteResolver implements HandlerResolverInterface 19 | { 20 | /** 21 | * @param \Rougin\Slytherin\Routing\RouteInterface $handler 22 | * 23 | * @return array 24 | */ 25 | public function resolve($handler) 26 | { 27 | return array(new PhrouteWrapper($handler), 'setParams'); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Routing/PhrouteRouter.php: -------------------------------------------------------------------------------- 1 | 15 | * 16 | * @link https://github.com/mrjgreen/phroute 17 | */ 18 | class PhrouteRouter extends Router 19 | { 20 | /** 21 | * @var \Phroute\Phroute\RouteCollector 22 | */ 23 | protected $collector; 24 | 25 | /** 26 | * Initializes the router instance. 27 | * 28 | * @param array $routes 29 | */ 30 | public function __construct(array $routes = array()) 31 | { 32 | $this->collector = new RouteCollector; 33 | 34 | parent::__construct($routes); 35 | } 36 | 37 | /** 38 | * Adds a new raw route. 39 | * 40 | * @param string $method 41 | * @param string $uri 42 | * @param callable|string|string[] $handler 43 | * @param callable|mixed[]|string $middlewares 44 | * 45 | * @return self 46 | */ 47 | public function add($method, $uri, $handler, $middlewares = array()) 48 | { 49 | parent::add($method, $uri, $handler, $middlewares); 50 | 51 | // Returns the recently added route from parent --- 52 | $route = $this->routes[count($this->routes) - 1]; 53 | // ------------------------------------------------ 54 | 55 | $this->collector->addRoute($method, $route->getUri(), $route); 56 | 57 | return $this; 58 | } 59 | 60 | /** 61 | * @param \Rougin\Slytherin\Routing\RouteInterface[] $routes 62 | * 63 | * @return \Phroute\Phroute\RouteDataArray 64 | */ 65 | public function asParsed(array $routes) 66 | { 67 | foreach ($routes as $route) 68 | { 69 | // Convert the ":name" pattern into "{name}" pattern ------------------ 70 | $uri = $route->getUri(); 71 | 72 | $matched = preg_match_all('/\:([a-zA-Z0-9\_\-]+)/i', $uri, $matches); 73 | 74 | if ($matched) 75 | { 76 | foreach ($matches[0] as $key => $item) 77 | { 78 | $uri = str_replace($item, '{' . $matches[1][$key] . '}', $uri); 79 | } 80 | } 81 | // -------------------------------------------------------------------- 82 | 83 | $this->collector->addRoute($route->getMethod(), $uri, $route); 84 | } 85 | 86 | return $this->collector->getData(); 87 | } 88 | 89 | /** 90 | * Returns a listing of parsed routes. 91 | * 92 | * @param \Rougin\Slytherin\Routing\RouteInterface[] $routes 93 | * 94 | * @return mixed|null 95 | */ 96 | public function parsed(array $routes = array()) 97 | { 98 | return $this->collector->getData(); 99 | } 100 | 101 | /** 102 | * @param \Phroute\Phroute\RouteCollector $collector 103 | * 104 | * @return self 105 | */ 106 | public function setCollector(RouteCollector $collector) 107 | { 108 | $this->collector = $collector; 109 | 110 | return $this; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/Routing/PhrouteWrapper.php: -------------------------------------------------------------------------------- 1 | 13 | * 14 | * @link https://github.com/mrjgreen/phroute 15 | */ 16 | class PhrouteWrapper 17 | { 18 | /** @var \Rougin\Slytherin\Routing\RouteInterface */ 19 | protected $route; 20 | 21 | /** 22 | * @param \Rougin\Slytherin\Routing\RouteInterface $route 23 | */ 24 | public function __construct(RouteInterface $route) 25 | { 26 | $this->route = $route; 27 | } 28 | 29 | /** 30 | * @param string $method 31 | * @param mixed[] $params 32 | * 33 | * @return mixed 34 | */ 35 | public function __call($method, $params) 36 | { 37 | /** @var string[] $params */ 38 | return $this->route->setParams($params); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Routing/Route.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Route implements RouteInterface 15 | { 16 | /** 17 | * @var callable|string[] 18 | */ 19 | protected $handler; 20 | 21 | /** 22 | * @var string 23 | */ 24 | protected $method; 25 | 26 | /** 27 | * @var mixed[] 28 | */ 29 | protected $middlewares; 30 | 31 | /** 32 | * @var array 33 | */ 34 | protected $params = array(); 35 | 36 | /** 37 | * @var string 38 | */ 39 | protected $uri; 40 | 41 | /** 42 | * @param string $method 43 | * @param string $uri 44 | * @param callable|string|string[] $handler 45 | * @param callable|mixed[]|string $middlewares 46 | */ 47 | public function __construct($method, $uri, $handler, $middlewares = array()) 48 | { 49 | if (is_string($handler)) 50 | { 51 | /** @var string[] */ 52 | $handler = explode('@', $handler); 53 | } 54 | 55 | $this->handler = $handler; 56 | 57 | $this->method = $method; 58 | 59 | if (! is_array($middlewares)) 60 | { 61 | $middlewares = array($middlewares); 62 | } 63 | 64 | $this->middlewares = $middlewares; 65 | 66 | $this->uri = (string) $uri; 67 | } 68 | 69 | /** 70 | * Returns the handler. 71 | * 72 | * @return callable|string[] 73 | */ 74 | public function getHandler() 75 | { 76 | return $this->handler; 77 | } 78 | 79 | /** 80 | * Returns the HTTP method. 81 | * 82 | * @return string 83 | */ 84 | public function getMethod() 85 | { 86 | return $this->method; 87 | } 88 | 89 | /** 90 | * Returns the defined middlewares. 91 | * 92 | * @return mixed[] 93 | */ 94 | public function getMiddlewares() 95 | { 96 | return $this->middlewares; 97 | } 98 | 99 | /** 100 | * Returns the defined parameters. 101 | * 102 | * @return array 103 | */ 104 | public function getParams() 105 | { 106 | return $this->params; 107 | } 108 | 109 | /** 110 | * Returns a regular expression pattern from the given URI. 111 | * 112 | * @return string 113 | * 114 | * @link https://stackoverflow.com/q/30130913 115 | */ 116 | public function getRegex() 117 | { 118 | // Turn "(/)" into "/?" ------------------------------ 119 | /** @var string */ 120 | $uri = preg_replace('#\(/\)#', '/?', $this->getUri()); 121 | // --------------------------------------------------- 122 | 123 | // Create capture group for ":parameter", replaces ":parameter" --- 124 | $uri = $this->capture($uri, '/:(' . self::ALLOWED_REGEX . ')/'); 125 | // ---------------------------------------------------------------- 126 | 127 | // Create capture group for '{parameter}', replaces "{parameter}" --- 128 | $uri = $this->capture($uri, '/{(' . self::ALLOWED_REGEX . ')}/'); 129 | // ------------------------------------------------------------------ 130 | 131 | // Add start and end matching ------ 132 | return (string) '@^' . $uri . '$@D'; 133 | // --------------------------------- 134 | } 135 | 136 | /** 137 | * Return the URI of the route. 138 | * 139 | * @return string 140 | */ 141 | public function getUri() 142 | { 143 | return $this->uri; 144 | } 145 | 146 | /** 147 | * Sets the parameters to the route. 148 | * 149 | * @param array $params 150 | * 151 | * @return self 152 | */ 153 | public function setParams($params) 154 | { 155 | $this->params = $params; 156 | 157 | return $this; 158 | } 159 | 160 | /** 161 | * Capture the specified regular expressions. 162 | * 163 | * @param string $pattern 164 | * @param string $search 165 | * 166 | * @return string 167 | */ 168 | protected function capture($pattern, $search) 169 | { 170 | /** @var string */ 171 | return preg_replace($search, '(?<$1>' . self::ALLOWED_REGEX . ')', $pattern); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /src/Routing/RouteInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | interface RouteInterface 15 | { 16 | const ALLOWED_REGEX = '[a-zA-Z0-9\_\-]+'; 17 | 18 | /** 19 | * Returns the handler. 20 | * 21 | * @return callable|string[] 22 | */ 23 | public function getHandler(); 24 | 25 | /** 26 | * Returns the HTTP method. 27 | * 28 | * @return string 29 | */ 30 | public function getMethod(); 31 | 32 | /** 33 | * Returns the defined middlewares. 34 | * 35 | * @return mixed[] 36 | */ 37 | public function getMiddlewares(); 38 | 39 | /** 40 | * Returns the defined parameters. 41 | * 42 | * @return string[] 43 | */ 44 | public function getParams(); 45 | 46 | /** 47 | * Returns a regular expression pattern from the given URI. 48 | * 49 | * @return string 50 | */ 51 | public function getRegex(); 52 | 53 | /** 54 | * Return the URI of the route. 55 | * 56 | * @return string 57 | */ 58 | public function getUri(); 59 | 60 | /** 61 | * Sets the parameters to the route. 62 | * 63 | * @param string[] $params 64 | * 65 | * @return self 66 | */ 67 | public function setParams($params); 68 | } 69 | -------------------------------------------------------------------------------- /src/Routing/RouterInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | interface RouterInterface 15 | { 16 | /** 17 | * Adds a new raw route. 18 | * 19 | * @param string $method 20 | * @param string $uri 21 | * @param callable|string|string[] $handler 22 | * @param callable|mixed[]|string $middlewares 23 | * 24 | * @return self 25 | */ 26 | public function add($method, $uri, $handler, $middlewares = array()); 27 | 28 | /** 29 | * Merges a listing of parsed routes to current one. 30 | * 31 | * @param \Rougin\Slytherin\Routing\RouteInterface[] $routes 32 | * 33 | * @return self 34 | */ 35 | public function merge(array $routes); 36 | 37 | /** 38 | * Returns a listing of parsed routes. 39 | * 40 | * @param \Rougin\Slytherin\Routing\RouteInterface[] $routes 41 | * 42 | * @return mixed|null 43 | */ 44 | public function parsed(array $routes = array()); 45 | 46 | /** 47 | * Returns a listing of available routes. 48 | * 49 | * @return \Rougin\Slytherin\Routing\RouteInterface[] 50 | */ 51 | public function routes(); 52 | } 53 | -------------------------------------------------------------------------------- /src/Routing/RoutingIntegration.php: -------------------------------------------------------------------------------- 1 | 18 | */ 19 | class RoutingIntegration implements IntegrationInterface 20 | { 21 | /** 22 | * @var string|null 23 | */ 24 | protected $preferred = null; 25 | 26 | /** 27 | * Defines the specified integration. 28 | * 29 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 30 | * @param \Rougin\Slytherin\Integration\Configuration $config 31 | * 32 | * @return \Rougin\Slytherin\Container\ContainerInterface 33 | */ 34 | public function define(ContainerInterface $container, Configuration $config) 35 | { 36 | $dispatcher = new Dispatcher; 37 | 38 | $router = $config->get('app.router', new Router); 39 | 40 | if ($this->wants('fastroute')) 41 | { 42 | $dispatcher = new FastRouteDispatcher; 43 | } 44 | 45 | if ($this->wants('phroute')) 46 | { 47 | $dispatcher = new PhrouteDispatcher; 48 | } 49 | 50 | $container->set(System::DISPATCHER, $dispatcher); 51 | 52 | return $container->set(System::ROUTER, $router); 53 | } 54 | 55 | /** 56 | * Checks the preferred package to be used. 57 | * 58 | * @param string $type 59 | * 60 | * @return boolean 61 | */ 62 | protected function wants($type) 63 | { 64 | $empty = $this->preferred === null; 65 | 66 | $package = ''; 67 | 68 | if ($type === 'fastroute') 69 | { 70 | $package = 'FastRoute\RouteCollector'; 71 | } 72 | 73 | if ($type === 'phroute') 74 | { 75 | $package = 'Phroute\Phroute\Dispatcher'; 76 | } 77 | 78 | $preferred = $this->preferred === $type; 79 | 80 | $exists = class_exists($package); 81 | 82 | return ($empty || $preferred) && $exists; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/Routing/Vanilla/Dispatcher.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Dispatcher extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Routing/Vanilla/Router.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Router extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/System.php: -------------------------------------------------------------------------------- 1 | 19 | */ 20 | class System 21 | { 22 | const CONFIG = 'Rougin\Slytherin\Integration\Configuration'; 23 | 24 | const CONTAINER = 'Rougin\Slytherin\Container\ContainerInterface'; 25 | 26 | const DEBUGGER = 'Rougin\Slytherin\Debug\ErrorHandlerInterface'; 27 | 28 | const DISPATCHER = 'Rougin\Slytherin\Routing\DispatcherInterface'; 29 | 30 | const MIDDLEWARE = 'Rougin\Slytherin\Middleware\DispatcherInterface'; 31 | 32 | const REQUEST = 'Psr\Http\Message\ServerRequestInterface'; 33 | 34 | const RESPONSE = 'Psr\Http\Message\ResponseInterface'; 35 | 36 | const ROUTER = 'Rougin\Slytherin\Routing\RouterInterface'; 37 | 38 | const TEMPLATE = 'Rougin\Slytherin\Template\RendererInterface'; 39 | 40 | /** 41 | * @var \Rougin\Slytherin\Integration\Configuration 42 | */ 43 | protected $config; 44 | 45 | /** 46 | * @var \Rougin\Slytherin\Container\ContainerInterface 47 | */ 48 | protected $container; 49 | 50 | /** 51 | * Initializes the application instance. 52 | * 53 | * @param \Rougin\Slytherin\Container\ContainerInterface|null $container 54 | * @param \Rougin\Slytherin\Integration\Configuration|null $config 55 | */ 56 | public function __construct(ContainerInterface $container = null, Configuration $config = null) 57 | { 58 | if (! $config) 59 | { 60 | $config = new Configuration; 61 | } 62 | 63 | $this->config = $config; 64 | 65 | if (! $container) 66 | { 67 | $container = new Container; 68 | } 69 | 70 | $this->container = $container; 71 | } 72 | 73 | /** 74 | * Handles the ServerRequestInterface to convert it to a ResponseInterface. 75 | * 76 | * @param \Psr\Http\Message\ServerRequestInterface $request 77 | * 78 | * @return \Psr\Http\Message\ResponseInterface 79 | */ 80 | public function handle(ServerRequestInterface $request) 81 | { 82 | $uri = $request->getUri()->getPath(); 83 | 84 | $method = $request->getMethod(); 85 | 86 | /** @var \Rougin\Slytherin\Routing\DispatcherInterface */ 87 | $dispatcher = $this->container->get(self::DISPATCHER); 88 | 89 | if ($this->container->has(self::ROUTER)) 90 | { 91 | /** @var \Rougin\Slytherin\Routing\RouterInterface */ 92 | $router = $this->container->get(self::ROUTER); 93 | 94 | $dispatcher = $dispatcher->setRouter($router); 95 | } 96 | 97 | $route = $dispatcher->dispatch($method, $uri); 98 | 99 | $items = $route->getMiddlewares(); 100 | 101 | $handler = new Handler($route, $this->container); 102 | 103 | if (! $this->container->has(self::MIDDLEWARE)) 104 | { 105 | return $handler->handle($request); 106 | } 107 | 108 | /** @var \Rougin\Slytherin\Middleware\DispatcherInterface */ 109 | $middleware = $this->container->get(self::MIDDLEWARE); 110 | 111 | $stack = $middleware->getStack(); 112 | 113 | $middleware->setStack(array_merge($items, $stack)); 114 | 115 | return $middleware->process($request, $handler); 116 | } 117 | 118 | /** 119 | * Adds the specified integrations to the container. 120 | * 121 | * @param mixed|mixed[] $items 122 | * @param \Rougin\Slytherin\Integration\Configuration|null $config 123 | * 124 | * @return self 125 | */ 126 | public function integrate($items, Configuration $config = null) 127 | { 128 | if (! $config) 129 | { 130 | $config = $this->config; 131 | } 132 | 133 | if (! is_array($items)) 134 | { 135 | $items = array($items); 136 | } 137 | 138 | $container = $this->container; 139 | 140 | /** @var \Rougin\Slytherin\Integration\IntegrationInterface|string $item */ 141 | foreach ($items as $item) 142 | { 143 | if (is_string($item)) 144 | { 145 | /** @var \Rougin\Slytherin\Integration\IntegrationInterface */ 146 | $item = new $item; 147 | } 148 | 149 | $container = $item->define($container, $config); 150 | } 151 | 152 | $this->container = $container; 153 | 154 | return $this; 155 | } 156 | 157 | /** 158 | * Emits the headers from response and runs the application. 159 | * 160 | * @return void 161 | */ 162 | public function run() 163 | { 164 | if ($this->container->has(self::DEBUGGER)) 165 | { 166 | /** @var \Rougin\Slytherin\Debug\ErrorHandlerInterface */ 167 | $debugger = $this->container->get(self::DEBUGGER); 168 | 169 | $debugger->display(); 170 | } 171 | 172 | /** @var \Psr\Http\Message\ServerRequestInterface */ 173 | $request = $this->container->get(self::REQUEST); 174 | 175 | echo (string) $this->emit($request)->getBody(); 176 | } 177 | 178 | /** 179 | * Emits the headers based from the response. 180 | * 181 | * @param \Psr\Http\Message\ServerRequestInterface $request 182 | * 183 | * @return \Psr\Http\Message\ResponseInterface 184 | */ 185 | protected function emit(ServerRequestInterface $request) 186 | { 187 | $response = $this->handle($request); 188 | 189 | $code = (string) $response->getStatusCode(); 190 | 191 | $code .= ' ' . $response->getReasonPhrase(); 192 | 193 | $headers = (array) $response->getHeaders(); 194 | 195 | $version = $response->getProtocolVersion(); 196 | 197 | header('HTTP/' . $version . ' ' . $code); 198 | 199 | foreach ($headers as $name => $values) 200 | { 201 | $value = (string) implode(',', $values); 202 | 203 | header((string) $name . ': ' . $value); 204 | } 205 | 206 | return $response; 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /src/System/Handler.php: -------------------------------------------------------------------------------- 1 | 21 | */ 22 | class Handler implements HandlerInterface 23 | { 24 | /** 25 | * @var \Rougin\Slytherin\Container\ContainerInterface 26 | */ 27 | protected $container; 28 | 29 | /** 30 | * @var \Rougin\Slytherin\Routing\RouteInterface 31 | */ 32 | protected $route; 33 | 34 | /** 35 | * Initializes the system handler. 36 | * 37 | * @param \Rougin\Slytherin\Routing\RouteInterface $route 38 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 39 | */ 40 | public function __construct(RouteInterface $route, ContainerInterface $container) 41 | { 42 | $this->route = $route; 43 | 44 | $this->container = $container; 45 | } 46 | 47 | /** 48 | * Returns a callback for handling the application. 49 | * 50 | * @param \Psr\Http\Message\ServerRequestInterface $request 51 | * 52 | * @return \Psr\Http\Message\ResponseInterface 53 | */ 54 | public function handle(ServerRequestInterface $request) 55 | { 56 | // Attach the request again in the container to reflect from stack --- 57 | $this->container->set(System::REQUEST, $request); 58 | // ------------------------------------------------------------------- 59 | 60 | $container = new ReflectionContainer($this->container); 61 | 62 | $handler = $this->route->getHandler(); 63 | 64 | if (is_array($handler) && is_string($handler[0])) 65 | { 66 | $handler[0] = $container->get($handler[0]); 67 | 68 | /** @var object|string */ 69 | $objectOrMethod = $handler[0]; 70 | 71 | /** @var string */ 72 | $method = $handler[1]; 73 | 74 | $reflector = new \ReflectionMethod($objectOrMethod, $method); 75 | } 76 | else 77 | { 78 | /** @var \Closure|string */ 79 | $closure = $handler; 80 | 81 | $reflector = new \ReflectionFunction($closure); 82 | } 83 | 84 | /** @var callable */ 85 | $callable = $handler; 86 | 87 | $params = $this->setParams($reflector); 88 | 89 | $handler = call_user_func_array($callable, $params); 90 | 91 | return $this->setResponse($handler); 92 | } 93 | 94 | /** 95 | * Parses the reflection parameters against the result parameters. 96 | * 97 | * @param \ReflectionFunctionAbstract $reflector 98 | * 99 | * @return array 100 | */ 101 | protected function setParams(\ReflectionFunctionAbstract $reflector) 102 | { 103 | $container = new ReflectionContainer($this->container); 104 | 105 | $params = $this->route->getParams(); 106 | 107 | if (empty($params)) 108 | { 109 | return $container->getArguments($reflector, $params); 110 | } 111 | 112 | $items = $reflector->getParameters(); 113 | 114 | $values = $container->getArguments($reflector, $params); 115 | 116 | $result = array(); 117 | 118 | foreach (array_keys($items) as $key) 119 | { 120 | $exists = array_key_exists($key, $values); 121 | 122 | $result[] = $exists ? $values[$key] : $params[$key]; 123 | } 124 | 125 | return $result; 126 | } 127 | 128 | /** 129 | * Converts the result into a \Psr\Http\Message\ResponseInterface instance. 130 | * 131 | * @param mixed|\Psr\Http\Message\ResponseInterface $function 132 | * 133 | * @return \Psr\Http\Message\ResponseInterface 134 | */ 135 | protected function setResponse($function) 136 | { 137 | /** @var \Psr\Http\Message\ResponseInterface */ 138 | $response = $this->container->get(System::RESPONSE); 139 | 140 | if (is_string($function)) 141 | { 142 | $response->getBody()->write($function); 143 | } 144 | 145 | $instanceof = $function instanceof ResponseInterface; 146 | 147 | return $instanceof ? $function : $response; 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/System/Lastone.php: -------------------------------------------------------------------------------- 1 | 17 | */ 18 | class Lastone implements HandlerInterface 19 | { 20 | /** 21 | * @param \Psr\Http\Message\ServerRequestInterface $request 22 | * 23 | * @return \Psr\Http\Message\ResponseInterface 24 | */ 25 | public function handle(ServerRequestInterface $request) 26 | { 27 | return new Response; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/System/Routing.php: -------------------------------------------------------------------------------- 1 | 18 | * 19 | * @method add($method, $uri, $handler, $middlewares = array()) 20 | * @method delete($uri, $handler, $middlewares = array()) 21 | * @method get($uri, $handler, $middlewares = array()) 22 | * @method merge(array $routes) 23 | * @method parsed(array $routes = array()) 24 | * @method patch($uri, $handler, $middlewares = array()) 25 | * @method post($uri, $handler, $middlewares = array()) 26 | * @method prefix($prefix = '', $namespace = null) 27 | * @method put($uri, $handler, $middlewares = array()) 28 | * @method restful($uri, $class, $middlewares = array()) 29 | * @method routes() 30 | */ 31 | class Routing extends System 32 | { 33 | /** 34 | * @var \Rougin\Slytherin\Routing\RouterInterface|null 35 | */ 36 | protected $router = null; 37 | 38 | /** 39 | * Emits the headers from response and runs the application. 40 | * 41 | * @return void 42 | */ 43 | public function run() 44 | { 45 | if ($this->router === null) 46 | { 47 | parent::run(); 48 | 49 | return; 50 | } 51 | 52 | // Prepare the HttpIntegration ------------------- 53 | $this->config->set('app.http.cookies', $_COOKIE); 54 | 55 | $this->config->set('app.http.files', $_FILES); 56 | 57 | $this->config->set('app.http.get', (array) $_GET); 58 | 59 | $this->config->set('app.http.post', $_POST); 60 | 61 | $this->config->set('app.http.server', $_SERVER); 62 | 63 | $this->integrate(new HttpIntegration); 64 | // ----------------------------------------------- 65 | 66 | // Prepare the RoutingIntegration ------------------- 67 | $this->integrate(new RoutingIntegration); 68 | 69 | $this->container->set(System::ROUTER, $this->router); 70 | // -------------------------------------------------- 71 | 72 | parent::run(); 73 | } 74 | 75 | /** 76 | * Calls methods from the Router instance. 77 | * 78 | * @param string $method 79 | * @param mixed[] $params 80 | * 81 | * @return mixed 82 | */ 83 | public function __call($method, $params) 84 | { 85 | if (! $this->router) 86 | { 87 | $this->router = new Router; 88 | } 89 | 90 | /** @var callable $class */ 91 | $class = array($this->router, $method); 92 | 93 | return call_user_func_array($class, $params); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/Template/Renderer.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Renderer implements RendererInterface 15 | { 16 | /** 17 | * @var string[] 18 | */ 19 | protected $paths = array(); 20 | 21 | /** 22 | * Initializes the renderer instance. 23 | * 24 | * @param string|string[] $paths 25 | */ 26 | public function __construct($paths) 27 | { 28 | $this->paths = (array) $paths; 29 | } 30 | 31 | /** 32 | * Renders a file from a specified template. 33 | * 34 | * @param string $template 35 | * @param array $data 36 | * 37 | * @return string 38 | * @throws \InvalidArgumentException 39 | */ 40 | public function render($template, array $data = array()) 41 | { 42 | list($file, $name) = array(null, str_replace('.', '/', $template)); 43 | 44 | foreach ((array) $this->paths as $key => $path) 45 | { 46 | $files = (array) $this->files($path); 47 | 48 | $item = $this->check($files, $path, $key, "$name.php"); 49 | 50 | if ($item !== null) 51 | { 52 | $file = $item; 53 | } 54 | } 55 | 56 | if (! is_null($file)) 57 | { 58 | return $this->extract($file, $data); 59 | } 60 | 61 | $message = 'Template file "' . $name . '" not found.'; 62 | 63 | throw new \InvalidArgumentException((string) $message); 64 | } 65 | 66 | /** 67 | * Checks if the specified file exists. 68 | * 69 | * @param array $files 70 | * @param string $path 71 | * @param string $source 72 | * @param string $template 73 | * 74 | * @return string|null 75 | */ 76 | protected function check(array $files, $path, $source, $template) 77 | { 78 | $file = null; 79 | 80 | foreach ((array) $files as $key => $value) 81 | { 82 | $filepath = str_replace($path, $source, $value); 83 | 84 | $filepath = str_replace('\\', '/', (string) $filepath); 85 | 86 | /** @var string */ 87 | $filepath = preg_replace('/^\d\//i', '', $filepath); 88 | 89 | $exists = (string) $filepath === $template; 90 | 91 | $lowercase = strtolower($filepath) === $template; 92 | 93 | if ($exists || $lowercase) 94 | { 95 | $file = $value; 96 | } 97 | } 98 | 99 | return $file; 100 | } 101 | 102 | /** 103 | * Extracts the contents of the specified file. 104 | * 105 | * @param string $filepath 106 | * @param array $data 107 | * 108 | * @return string 109 | */ 110 | protected function extract($filepath, array $data) 111 | { 112 | extract($data); 113 | 114 | ob_start(); 115 | 116 | include $filepath; 117 | 118 | $contents = ob_get_contents(); 119 | 120 | ob_end_clean(); 121 | 122 | return $contents ?: ''; 123 | } 124 | 125 | /** 126 | * Returns an array of filepaths from a specified directory. 127 | * 128 | * @param string $path 129 | * 130 | * @return string[] 131 | */ 132 | protected function files($path) 133 | { 134 | $directory = new \RecursiveDirectoryIterator($path); 135 | 136 | $iterator = new \RecursiveIteratorIterator($directory); 137 | 138 | $regex = new \RegexIterator($iterator, '/^.+\.php$/i', 1); 139 | 140 | return (array) array_keys(iterator_to_array($regex)); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/Template/RendererIntegration.php: -------------------------------------------------------------------------------- 1 | 18 | */ 19 | class RendererIntegration implements IntegrationInterface 20 | { 21 | /** 22 | * @var string|null 23 | */ 24 | protected $preferred = null; 25 | 26 | /** 27 | * Defines the specified integration. 28 | * 29 | * @param \Rougin\Slytherin\Container\ContainerInterface $container 30 | * @param \Rougin\Slytherin\Integration\Configuration $config 31 | * 32 | * @return \Rougin\Slytherin\Container\ContainerInterface 33 | */ 34 | public function define(ContainerInterface $container, Configuration $config) 35 | { 36 | /** @var string|string[] */ 37 | $path = $config->get('app.views', ''); 38 | 39 | $renderer = new Renderer($path); 40 | 41 | $empty = $this->preferred === null; 42 | 43 | if (is_string($path)) 44 | { 45 | $path = array($path); 46 | } 47 | 48 | $twig = new TwigLoader; 49 | 50 | $wantTwig = $this->preferred === 'twig'; 51 | 52 | if (($empty || $wantTwig) && $twig->exists()) 53 | { 54 | $renderer = $twig->load($path); 55 | } 56 | 57 | $container->set(Application::TEMPLATE, $renderer); 58 | 59 | return $container; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/Template/RendererInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | interface RendererInterface 15 | { 16 | /** 17 | * Renders a template. 18 | * 19 | * @param string $template 20 | * @param array $data 21 | * 22 | * @return string 23 | */ 24 | public function render($template, array $data = array()); 25 | } 26 | -------------------------------------------------------------------------------- /src/Template/Twig.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class Twig extends Twig\Renderer 15 | { 16 | } 17 | -------------------------------------------------------------------------------- /src/Template/Twig/Renderer.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Renderer extends TwigRenderer 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Template/TwigLoader.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class TwigLoader 15 | { 16 | /** 17 | * Check if any version of Twig is installed. 18 | * 19 | * @return boolean 20 | */ 21 | public function exists() 22 | { 23 | return class_exists('Twig_Environment') || class_exists('Twig\Environment'); 24 | } 25 | 26 | /** 27 | * Loads the Twig instance. 28 | * 29 | * @param string|string[] $path 30 | * 31 | * @return \Twig\Environment 32 | */ 33 | public function load($path) 34 | { 35 | /** @var class-string */ 36 | $loader = 'Twig_Loader_Filesystem'; 37 | 38 | /** @var class-string */ 39 | $environment = 'Twig_Environment'; 40 | 41 | if (class_exists('Twig\Environment')) 42 | { 43 | $loader = 'Twig\Loader\FilesystemLoader'; 44 | 45 | $environment = 'Twig\Environment'; 46 | } 47 | 48 | $loader = new \ReflectionClass($loader); 49 | 50 | $loader = $loader->newInstance($path); 51 | 52 | $environment = new \ReflectionClass($environment); 53 | 54 | /** @var \Twig\Environment */ 55 | return $environment->newInstance($loader); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Template/TwigRenderer.php: -------------------------------------------------------------------------------- 1 | 14 | * 15 | * @link https://twig.sensiolabs.org 16 | */ 17 | class TwigRenderer implements RendererInterface 18 | { 19 | /** 20 | * @var \Twig\Environment 21 | */ 22 | protected $twig; 23 | 24 | /** 25 | * @param \Twig\Environment $twig 26 | * @param array $globals (NOTE: To be removed in v1.0.0). 27 | */ 28 | public function __construct($twig, array $globals = array()) 29 | { 30 | $this->twig = $twig; 31 | 32 | foreach ($globals as $key => $value) 33 | { 34 | $this->addGlobal($key, $value); 35 | } 36 | } 37 | 38 | /** 39 | * @param string $name 40 | * @param mixed $value 41 | * 42 | * @return self 43 | */ 44 | public function addGlobal($name, $value) 45 | { 46 | $this->twig->addGlobal($name, $value); 47 | 48 | return $this; 49 | } 50 | 51 | /** 52 | * Renders a template. 53 | * 54 | * @param string $template 55 | * @param array $data 56 | * @param string $extension 57 | * 58 | * @return string 59 | */ 60 | public function render($template, array $data = array(), $extension = 'html') 61 | { 62 | return $this->twig->render("$template.$extension", $data); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/Template/Vanilla/Renderer.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | class Renderer extends Slytherin 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/Template/VanillaRenderer.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | class VanillaRenderer extends Vanilla\Renderer 15 | { 16 | } 17 | --------------------------------------------------------------------------------