diff --git a/15-adding-content.md b/15-adding-content.md index c894d66..64562fa 100644 --- a/15-adding-content.md +++ b/15-adding-content.md @@ -1,4 +1,4 @@ -[<< previous](14-middleware.md) | [next >>](14-invoker.md) +[<< previous](14-middleware.md) | [next >>](16-data-repository.md) ### Adding Content @@ -250,4 +250,4 @@ add even more lines to that simple class, so lets move on to the next chapter wh classes following our holy SOLID principles :) -[<< previous](14-middleware.md) | [next >>](14-invoker.md) +[<< previous](14-middleware.md) | [next >>](16-data-repository.md) diff --git a/17-performance.md b/17-performance.md index d457bff..c83c7d5 100644 --- a/17-performance.md +++ b/17-performance.md @@ -1,6 +1,6 @@ -[<< previous](15-adding-content.md) | [next >>](17-performance.md) +[<< previous](16-data-repository.md) | [next >>](18-caching.md) -## Performance +## Autoloading performance Although our application is still very small and you should not really experience any performance issues right now, there are still some things we can already consider and take a look at. If I check the network tab in my browser it takes @@ -10,11 +10,34 @@ a template, some config files here and there and parse some markdown. So that sh The problem is, that we heavily rely on autoloading for all our class files, in the `src` folder. And there are also quite a lot of other files in composers `vendor` directory. To understand while this is becomming we should make -ourselves familiar with how autoloading in PHP works. +ourselves familiar with how [autoloading in php](https://www.php.net/manual/en/language.oop5.autoload.php) works. -[autoloading in php](https://www.php.net/manual/en/language.oop5.autoload.php) -[composer autoloader optimization](https://getcomposer.org/doc/articles/autoloader-optimization.md) +The basic idea is, that every class that php encounters has to be loaded from somewhere in the filesystem, we could +just require the files manually but that is tedious, unflexible and can often cause errors. -### Composer autoloading +The problem we are now facing is that the composer autoloader has some rules to determine from where in the filesystem +a class definition might be placed, then the autoloader tries to locate a file by the namespace and classname and if it +exists includes that file. -[<< previous](15-adding-content.md) | [next >>](17-performance.md) +If we only have a handfull of classes that does not take a lot of time, but as we are growing with our application this +easily takes longer than necesery, but fortunately composer has some options to speed up the class loading. + +Take a few minutes to read the documentation about [composer autoloader optimization](https://getcomposer.org/doc/articles/autoloader-optimization.md) + +You can try all 3 levels of optimizations, but we are going to stick with the first one for now, so lets create an +optimized classmap. + +`composer dump-autoload -o` + +After composer has finished you can start the devserver again with `composer serve` and take a look at the network tab +in your browsers devtools. + +In my case the response time falls down to under an average of 30ms with some spikes in between, but all in all it looks really good. +You can also try out the different optimization levels and see if you can spot any differences. + +Although the composer manual states not to use the optimtization in a dev environment I personally have not encountered +any errors with the first level of optimizations, so we can use that level here. If you add the line from the documentation +to your `composer.json` so that the autoloader gets optimized everytime we install new packages. + + +[<< previous](16-data-repository.md) | [next >>](18-caching.md) diff --git a/18-caching.md b/18-caching.md new file mode 100644 index 0000000..f06abe9 --- /dev/null +++ b/18-caching.md @@ -0,0 +1,252 @@ +[<< previous](17-performance.md) | [next >>](19-database.md) + +**DISClAIMER** I do not really have a lot of experience when it comes to caching, so this chapter is mostly some random +thoughts and ideas I wanted to explore when writing this tutorial, you should definitely take everything that is being +said here with caution and try to read up on some other sources. But that holds true for the whole tutorial anyway :) + +## Caching + +In the last chapter we greatly improved the perfomance for the lookup of all our classfiles, but currently we do not +have any real bottlenecks in our application like complex queries. + +But in a real application we are going to execute some really heavy and time intensive database queries that can take +quite a while to be completed. + +We can simulate that by adding a simple delay in our `FileSystemMarkdownPageRepo`. + +```php + return array_map(function (string $filename) { + usleep(rand(100, 400) * 1000); + $content = file_get_contents($filename); + if ($content === false) { + throw new InternalServerError('cannot read pages'); + } + $idAndTitle = str_replace([$this->dataPath, '.md'], ['', ''], $filename); + return new MarkdownPage( + (int) substr($idAndTitle, 0, 2), + substr($idAndTitle, 3), + $content + ); +}); +``` + +Here I added a function that pauses the scripts execution for a random time between 100 and 400ms for every markdownpage +in every call of the `all()` method. + +If you open any page or even the listAction in you browser you will see, that it takes quite a time to render that page. +Although this is a silly example we do not really need to query the database on every request, so lets add a way to cache +the database results between requests. + +The PHP-Community has already adressed the issue of having easy to use access to cache libraries, there is the +[PSR-6 Caching Interface](https://www.php-fig.org/psr/psr-6) which gives us easy access to many different implementations, +then there is also a much simpler [PSR-16 Simple Cache](https://www.php-fig.org/psr/psr-16) which makes the use even more +easy, and most Caching Libraries implement Both interfaces anyway. You would think that this is more than enough solutions +to satisfy all the Caching needs around, but the Symfony People decided that Caching should be even simpler and easier +to use and defined their own [Interface](https://symfony.com/doc/current/components/cache.html#cache-component-contracts) +which only needs two methods. You should definitely take a look at the linked documentation as it really blew my mind +when I first encountered it. + +The basic idea is that you provide a callback that computes the requested value. The Cache implementation then checks +if it already has the value stored somewhere and if it doesnt it just executes the callback and stores the value for +future calls. + +It is really simple and great to use. In a real world application you should definitely use that or a PSR-16 implementation +but for this tutorial I wanted to roll out my own solution, so here we go. + +As always we are going to define an interface first, I am going to call it EasyCache and place it in the `Service/Cache` +namespace. I will require only one method which is base on the Symfony Cache Contract, and hast a key, a callback, and +the duration that the item should be cached as arguments. + +```php +cache->get( + $key, + fn () => $this->repo->all(), + 300 + ); + } + + public function byName(string $name): MarkdownPage + { + $key = base64_encode(self::class . 'byName' . $name); + return $this->cache->get( + $key, + fn () => $this->repo->byName($name), + 300 + ); + } +} +``` + +This simple wrapper just requires an EasyCache implementation and a MarkdownPageRepo in the constructor and uses them +to cache all queries for 5 minutes. The beauty is that we are not dependent on any implementation here, so we can switch +out the Repository or the Cache at any point down the road if we want to. + +In order to use that we need to update our `config/dependencies.php` to add an alias for the EasyCache interface as well +as defining our CachedMarkdownPageRepo as implementation for the MarkdownPageRepo interface: + +```php +MarkdownPageRepo::class => fn (CachedMarkdownPageRepo $r) => $r, +EasyCache::class => fn (ApcuCache $c) => $c, +``` + +If we try to access our webpage now, we are getting an error, as PHP-DI has detected a circular dependency that cannot +be autowired. + +The Problem is that our CachedMarkdownPageRepo ist defined as the implementation for the MarkdownPageRepo, but it also +requires that exact interface as a dependency. To resolve this issue we need to manually tell the container how to build +the CachedMarkdownPageRepo by adding another line to the `config/dependencies.php` file: + +```php +CachedMarkdownPageRepo::class => fn (EasyCache $c, FileSystemMarkdownPageRepo $r) => new CachedMarkdownPageRepo($c, $r), +``` + +Here we explicitly require the FileSystemMarkdownPageRepo and us that to create the CachedMarkdownPageRepo object. + +When you now navigate to the pages list or to a specific page the first load should take a while (because of our added delay) +but the following request should be answered blazingly fast. + +Before moving on to the next chapter we can take the caching approach even further, in the middleware chapter I talked +about a simple CachingMiddleware that caches all the GET-Request for some seconds, as they should not change that often, +and we can bypass most of our application logic if we just complelety cache away the responses our application generates, +and return them quite early in our Middleware-Pipeline befor the router gets called, or the invoker calls the action, +which itself uses some other services to fetch all the needed data. + +We will introduce a new `Middleware` namespace to place our `Cache.php` middleware: +```php +getMethod() !== 'GET') { + return $handler->handle($request); + } + $keyHash = base64_encode($request->getUri()->getPath()); + $result = $this->cache->get( + $keyHash, + fn () => $this->serializer::toString($handler->handle($request)), + 300 + ); + return $this->serializer::fromString($result); + } +} +``` + +The code is quite straight forward, but you might be confused by the Responseserializer I have added here, we need this +because the response body is a stream object, which doesnt always gets serialized correctly, therefore I use a class from +the laminas project to to all the heavy lifting for us. + +We need to add the now middleware to the `config/middlewares.php` file. + +```php +>](19-database.md) diff --git a/Vagrantfile b/Vagrantfile index 56a4db4..7cdc936 100644 --- a/Vagrantfile +++ b/Vagrantfile @@ -3,9 +3,13 @@ Vagrant.configure("2") do |config| config.vm.box = "archlinux/archlinux" + config.vm.provider "virtualbox" do |v| + v.memory = 2048 + v.cpus = 4 + end config.vm.network "forwarded_port", guest: 1234, host: 1234 config.vm.network "forwarded_port", guest: 22, host: 2200, id: 'ssh' - config.vm.synced_folder "./app", "/home/vagrant/app" + config.vm.synced_folder "./app", "/home/vagrant/app/" config.ssh.username = 'vagrant' config.ssh.password = 'vagrant' config.vm.provision "shell", inline: <<-SHELL @@ -17,5 +21,7 @@ Vagrant.configure("2") do |config| echo -e 'zend_extension=xdebug\nxdebug.client_host=10.0.2.2\n' >> /etc/php/conf.d/tutorial.ini echo -e 'xdebug.client_port=9003\nxdebug.mode=debug\n' >> /etc/php/conf.d/tutorial.ini echo -e 'zend.assertions=1\n' >> /etc/php/conf.d/tutorial.ini + echo -e 'opcache.enable=1\nopcache.enable_cli=1\n' >> /etc/php/conf.d/tutorial.ini + echo -e 'acp.enable=1\napc.enable_cli=1\n' >> /etc/php/conf.d/tutorial.ini SHELL end diff --git a/app/composer.json b/app/composer.json index b5c7f1a..29695da 100644 --- a/app/composer.json +++ b/app/composer.json @@ -12,7 +12,9 @@ "middlewares/trailing-slash": "^2.0", "middlewares/whoops": "^2.0", "erusev/parsedown": "^1.7", - "league/commonmark": "^2.2" + "league/commonmark": "^2.2", + "ext-apcu": "*", + "ext-zend-opcache": "*" }, "autoload": { "psr-4": { @@ -36,6 +38,7 @@ "mnapoli/hard-mode": "^0.3.0" }, "config": { + "optimize-autoloader": true, "allow-plugins": { "phpstan/extension-installer": true, "dealerdirect/phpcodesniffer-composer-installer": true diff --git a/app/composer.lock b/app/composer.lock index a62d9c7..40cd7d3 100644 --- a/app/composer.lock +++ b/app/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "00acf07ae222f9117a84bce157b99837", + "content-hash": "9a29468fd456190a9fbcff98ed42d862", "packages": [ { "name": "dflydev/dot-access-data", @@ -2431,7 +2431,9 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": "^8.1" + "php": "^8.1", + "ext-apcu": "*", + "ext-zend-opcache": "*" }, "platform-dev": [], "plugin-api-version": "2.3.0" diff --git a/app/config/dependencies.php b/app/config/dependencies.php index 0040933..df815c6 100644 --- a/app/config/dependencies.php +++ b/app/config/dependencies.php @@ -11,8 +11,11 @@ use Lubian\NoFramework\Http\InvokerRoutedHandler; use Lubian\NoFramework\Http\Pipeline; use Lubian\NoFramework\Http\RoutedRequestHandler; use Lubian\NoFramework\Http\RouteMiddleware; +use Lubian\NoFramework\Repository\CachedMarkdownPageRepo; use Lubian\NoFramework\Repository\FileSystemMarkdownPageRepo; use Lubian\NoFramework\Repository\MarkdownPageRepo; +use Lubian\NoFramework\Service\Cache\ApcuCache; +use Lubian\NoFramework\Service\Cache\EasyCache; use Lubian\NoFramework\Service\Time\Now; use Lubian\NoFramework\Service\Time\SystemClockNow; use Lubian\NoFramework\Settings; @@ -26,8 +29,6 @@ use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; -use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Contracts\Cache\CacheInterface; use function FastRoute\simpleDispatcher; @@ -39,9 +40,11 @@ return [ MiddlewareInterface::class => fn (RouteMiddleware $r) => $r, RoutedRequestHandler::class => fn (InvokerRoutedHandler $h) => $h, RequestFactory::class => fn (DiactorosRequestFactory $rf) => $rf, - CacheInterface::class => fn (FilesystemAdapter $a) => $a, MarkdownParser::class => fn (ParsedownParser $p) => $p, - MarkdownPageRepo::class => fn (FileSystemMarkdownPageRepo $r) => $r, + MarkdownPageRepo::class => fn (CachedMarkdownPageRepo $r) => $r, + EasyCache::class => fn (ApcuCache $c) => $c, + CachedMarkdownPageRepo::class => fn (EasyCache $c, FileSystemMarkdownPageRepo $r) => new CachedMarkdownPageRepo($c, $r), + // Factories ResponseInterface::class => fn (ResponseFactory $rf) => $rf->createResponse(), diff --git a/app/config/middlewares.php b/app/config/middlewares.php index 71dd461..ab662be 100644 --- a/app/config/middlewares.php +++ b/app/config/middlewares.php @@ -1,11 +1,13 @@ >](14-invoker.md) +[<< previous](12-refactoring.md) | [next >>](15-adding-content.md) ### Middleware @@ -153,8 +153,6 @@ class ContainerPipeline implements Pipeline { /** * @param array $middlewares - * @param RequestHandlerInterface $tip - * @param ContainerInterface $container */ public function __construct( private array $middlewares, @@ -295,4 +293,11 @@ Lets try if you can make the kernel work with our created Pipeline implementatio pipeline a little bit, so that it can accept a class-string of a middleware and resolves that with the help of a dependency container, if you want you can do that as well. -[<< previous](12-refactoring.md) | [next >>](14-invoker.md) +**A quick note about docblocks:** You might have noticed, that I rarely add docblocks to my the code in the examples, and +when I do it seems kind of random. My philosophy is that I only add docblocks when there is no way to automatically get +the exact type from the code itself. For me docblocks only serve two purposes: help my IDE to understand what it choices +it has for code completion and to help the static analysis to better understand the code. There is a great blogpost +about the [cost and value of DocBlocks](https://localheinz.com/blog/2018/05/06/cost-and-value-of-docblocks/), although it +is written in 2018 at a time before PHP 7.4 was around everything written there is still valid today. + +[<< previous](12-refactoring.md) | [next >>](15-adding-content.md) diff --git a/app/data/pages/15-adding-content.md b/app/data/pages/15-adding-content.md new file mode 100644 index 0000000..64562fa --- /dev/null +++ b/app/data/pages/15-adding-content.md @@ -0,0 +1,253 @@ +[<< previous](14-middleware.md) | [next >>](16-data-repository.md) + +### Adding Content + +By now we did not really display anything but some examples to in our application and it is now time to make our app +display some content. For example we could our app be able to display the Markdown files used in this tutorial as +nicely rendered HTML Pages that can be viewed in the browser instead of the editor you are using. + +So lets start by copying the markdown files to our app directory. I have created a new folder 'data/pages' and placed all +the markdown files in there. + +Next we need a markdown parser, a pretty simple one is [Parsedown](https://parsedown.org/), if you want more features +you could also use the [Commonmark parser](https://commonmark.thephpleague.com/). I will choose Parsedown here, but you +can use whatever you like. + +After installing Parsedown lets write a Markdownparser interface and an implementation using parsedown. + +We only need one function that receives a string of Markdown and returns the HTML represantion (as a string as well). + + + +```php +parser->parse($markdown); + } +} +``` + +We could now use the ParsedownRender class directly in our actions by typehinting the classname as an argument to the +constructor or a method, but as we always want to rely on an interface instead of an implementation we need to define +the the ParsedownRenderer as the correct implementation for the MarkdownRenderer interface in the dependencies file: + +```php +... + \Lubian\NoFramework\Template\MarkdownParser::class => fn(\Lubian\NoFramework\Template\ParsedownParser $p) => $p, +... +``` + +You can test that in our "Other.php" action and try out if the Parser works and is able to render Markdown to HTML: + +```php +public function someFunctionName(ResponseInterface $response, MarkdownParser $parser): ResponseInterface +{ + $html = $parser->parse('This *works* **too!**'); + $response->getBody()->write($html); + return $response->withStatus(200); +} +``` + +But we want to display complete Pages written in Markdown, it would also be neat to be able to display a list of all +available pages. For that we need a few things: + +Firstly we need two new Templates, one for the list of the Pages, and the second one for displaying a single pages +content. Create a new folder in `templates/page` with to files: + +`templates/page/list.html` +```html + + + + + Pages + + + +
+ +
+ + +``` + +This template iterates over a provided array of pages, each element consists of the two properties: an id and a title, +those are simply displayed using an unordered list. + +`templates/page/show.html` +```html + + + + + {{title}} + + + + + + +
+ {{{content}}} +
+ + +``` + +The second templates displays a single rendered markdown page. As data it expects the title and the content as array. +I used an extra bracket for the content ```{{{content}}}``` so that the Mustache-Renderer does not escape the provided +html and thereby destroys the the parsed markdown. + +You might have spotted that I added [Pico.css](https://picocss.com/) which is just a very small css framework to make the +pages a little bit nicer to look at. It mostly provides some typography styles that work great with rendered Markdown, +but you can leave that out or use any other css framework you like. There is also some Javascript that adds syntax +highlighting to the code. + +After you have taken care of the templating side we can now create an new Action class with two methods to display use +our markdown files and the templates to create the pages. As we have two templates I propose to use Two methods in our +Action: +`src/Action/Page.php` +```php +function show(string $name): \Psr\Http\Message\ResponseInterface; +function list(): \Psr\Http\Message\ResponseInterface; +``` + +Lets define two routes. `/page` should display the overview of all pages, and if the add the name of chapter to the +route, `/page/adding-content` for example, the show action should be called with the name as a variable: + +`config/routes.php` +```php +$r->addRoute('GET', '/page', [Page::class, 'list']); +$r->addRoute('GET', '/page/{page}', [Page::class, 'show']); +``` + +Here is my Implementation. If have added a little regex replacement in the show method that replaces the links to the +next and previous chapter so that it works with our routing configuration. + +`src/Action/Page.php` +```php +getPages(), + fn (string $filename) => str_contains($filename, $page) + ) + )[0]; + $markdown = file_get_contents($page); + + // fix the next and previous buttons to work with our routing + $markdown = preg_replace('/\(\d\d-/m', '(', $markdown); + $markdown = str_replace('.md)', ')', $markdown); + + $page = str_replace([$this->pagesPath, '.md'], ['', ''], $page); + $data = [ + 'title' => substr($page, 3), + 'content' => $this->parser->parse($markdown), + ]; + $html = $this->renderer->render('page/show', $data); + $this->response->getBody()->write($html); + return $this->response; + } + + public function list(): ResponseInterface + { + $pages = array_map(function (string $page) { + $page = str_replace([$this->pagesPath, '.md'], ['', ''], $page); + return [ + 'id' => substr($page, 0, 2), + 'title' => substr($page, 3), + ]; + }, $this->getPages()); + $html = $this->renderer->render('page/list', ['pages' => $pages]); + $this->response->getBody()->write($html); + return $this->response; + } + + /** + * @return string[] + */ + private function getPages(): array + { + $files = glob($this->pagesPath . '*.md'); + if ($files === false) { + throw new InternalServerError('cannot read pages'); + } + return $files; + } +} +``` + +You can now navigate your Browser to [localhost:1234/page][http://localhost:1234/page] and try out if everything works. + +Of course this code is far from looking good. We heavily rely on the pages being files in the filesystem, and the action +should never be aware of the filesystem in the first place, also we have a lot of string replacements and other repetetive +code in the file. And phpstan is gonna scream at us a lot, but if we rewrite the code to satisfy all the checks we would +add even more lines to that simple class, so lets move on to the next chapter where we move all the logic to seperate +classes following our holy SOLID principles :) + + +[<< previous](14-middleware.md) | [next >>](16-data-repository.md) diff --git a/app/data/pages/16-data-repository.md b/app/data/pages/16-data-repository.md new file mode 100644 index 0000000..d9a3218 --- /dev/null +++ b/app/data/pages/16-data-repository.md @@ -0,0 +1,265 @@ +[<< previous](15-adding-content.md) | [next >>](17-performance.md) + +## Data Repository + +At the end of the last chapter I mentioned being unhappy with our Pages action, because there is to much stuff happening +there. We are firstly receiving some Arguments, then we are using those to query the filesytem for the given page, +loading the specific file from the filesystem, rendering the markdown, passing the markdown to the template renderer, +adding the resulting html to the response and then returning the response. + +In order to make our pageaction independent from the filesystem and move the code that is responsible for reading the +files +to a better place I want to introduce +the [Repository Pattern](https://designpatternsphp.readthedocs.io/en/latest/More/Repository/README.html). + +I want to start by creating a class that represents the Data that is included in a page so that. For now I can spot +three +distrinct attributes. + +* the ID (or chapternumber) +* the title (or name) +* the content + +Currently all those properties are always available, but we might later be able to create new pages and store them, but +at that point in time we are not yet aware of the new available ID, so we should leave that property nullable. This +allows +us to create an object without an id and let the code that actually saves the object to a persistant store define a +valid +id on saving. + +Lets create an new Namespace called `Model` and put a `MarkdownPage.php` class in there: + +```php +dataPath . '*.md'); + if ($files === false) { + throw new InternalServerError('cannot read pages'); + } + return array_map(function (string $filename) { + $content = file_get_contents($filename); + if ($content === false) { + throw new InternalServerError('cannot read pages'); + } + $idAndTitle = str_replace([$this->dataPath, '.md'], ['', ''], $filename); + return new MarkdownPage( + (int) substr($idAndTitle, 0, 2), + substr($idAndTitle, 3), + $content + ); + }, $files); + } + + public function byName(string $name): MarkdownPage + { + $pages = array_values( + array_filter( + $this->all(), + fn (MarkdownPage $p) => $p->title === $name, + ) + ); + + if (count($pages) !== 1) { + throw new NotFound; + } + + return $pages[0]; + } +} +``` + +With that in place we need to add the required `$pagesPath` to our settings class and add specify that in our +configuration. + +`src/Settings.php` + +```php +final class Settings +{ + public function __construct( + public readonly string $environment, + public readonly string $dependenciesFile, + public readonly string $middlewaresFile, + public readonly string $templateDir, + public readonly string $templateExtension, + public readonly string $pagesPath, + ) { + } +} +``` + +`config/settings.php` + +```php +return new Settings( + environment: 'prod', + dependenciesFile: __DIR__ . '/dependencies.php', + middlewaresFile: __DIR__ . '/middlewares.php', + templateDir: __DIR__ . '/../templates', + templateExtension: '.html', + pagesPath: __DIR__ . '/../data/pages/', +); +``` + +Of course we need to define the correct implementation for the container to choose when we are requesting the Repository +interface: +`conf/dependencies.php` + +```php +MarkdownPageRepo::class => fn (FileSystemMarkdownPageRepo $r) => $r, +FileSystemMarkdownPageRepo::class => fn (Settings $s) => new FileSystemMarkdownPageRepo($s->pagesPath), +``` + +Now you can request the MarkdownPageRepo Interface in your page action and use the defined functions to get the +MarkdownPage +Objects. My `src/Action/Page.php` looks like this now: + +```php +repo->byName($page); + + // fix the next and previous buttons to work with our routing + $content = preg_replace('/\(\d\d-/m', '(', $page->content); + assert(is_string($content)); + $content = str_replace('.md)', ')', $content); + + $data = [ + 'title' => $page->title, + 'content' => $this->parser->parse($content), + ]; + + $html = $this->renderer->render('page/show', $data); + $this->response->getBody()->write($html); + return $this->response; + } + + public function list(): ResponseInterface + { + $pages = array_map(function (MarkdownPage $page) { + return [ + 'id' => $page->id, + 'title' => $page->content, + ]; + }, $this->repo->all()); + + $html = $this->renderer->render('page/list', ['pages' => $pages]); + $this->response->getBody()->write($html); + return $this->response; + } +} +``` + +Check the page in your browser if everything still works, don't forget to run phpstan and the others fixers before +committing your changes and moving on to the next chapter. + +[<< previous](15-adding-content.md) | [next >>](17-performance.md) diff --git a/app/data/pages/17-performance.md b/app/data/pages/17-performance.md new file mode 100644 index 0000000..c83c7d5 --- /dev/null +++ b/app/data/pages/17-performance.md @@ -0,0 +1,43 @@ +[<< previous](16-data-repository.md) | [next >>](18-caching.md) + +## Autoloading performance + +Although our application is still very small and you should not really experience any performance issues right now, +there are still some things we can already consider and take a look at. If I check the network tab in my browser it takes +about 90-400ms to show a simple rendered markdownpage, with is sort of ok but in my opinion way to long as we are not +really doing anything and do not connect to any external services. Mostly we are just reading around 16 markdown files, +a template, some config files here and there and parse some markdown. So that should not really take that long. + +The problem is, that we heavily rely on autoloading for all our class files, in the `src` folder. And there are also +quite a lot of other files in composers `vendor` directory. To understand while this is becomming we should make +ourselves familiar with how [autoloading in php](https://www.php.net/manual/en/language.oop5.autoload.php) works. + +The basic idea is, that every class that php encounters has to be loaded from somewhere in the filesystem, we could +just require the files manually but that is tedious, unflexible and can often cause errors. + +The problem we are now facing is that the composer autoloader has some rules to determine from where in the filesystem +a class definition might be placed, then the autoloader tries to locate a file by the namespace and classname and if it +exists includes that file. + +If we only have a handfull of classes that does not take a lot of time, but as we are growing with our application this +easily takes longer than necesery, but fortunately composer has some options to speed up the class loading. + +Take a few minutes to read the documentation about [composer autoloader optimization](https://getcomposer.org/doc/articles/autoloader-optimization.md) + +You can try all 3 levels of optimizations, but we are going to stick with the first one for now, so lets create an +optimized classmap. + +`composer dump-autoload -o` + +After composer has finished you can start the devserver again with `composer serve` and take a look at the network tab +in your browsers devtools. + +In my case the response time falls down to under an average of 30ms with some spikes in between, but all in all it looks really good. +You can also try out the different optimization levels and see if you can spot any differences. + +Although the composer manual states not to use the optimtization in a dev environment I personally have not encountered +any errors with the first level of optimizations, so we can use that level here. If you add the line from the documentation +to your `composer.json` so that the autoloader gets optimized everytime we install new packages. + + +[<< previous](16-data-repository.md) | [next >>](18-caching.md) diff --git a/app/data/pages/18-caching.md b/app/data/pages/18-caching.md new file mode 100644 index 0000000..42e9cb1 --- /dev/null +++ b/app/data/pages/18-caching.md @@ -0,0 +1,252 @@ +[<< previous](17-performance.md) | [next >>](19-database.md) + +**DISClAIMER** I do not really have a lot of experience when it comes to caching, so this chapter is mostly some random +thoughts and ideas I wanted to explore when writing this tutorial, you should definitely take everything that is being +said here with caution and try to read up on some other sources. But that holds true for the whole tutorial anyway :) + +## Caching + +In the last chapter we greatly improved the perfomance for the lookup of all our classfiles, but currently we do not +have any real bottlenecks in our application like complex queries. + +But in a real application we are going to execute some really heavy and time intensive database queries that can take +quite a while to be completed. + +We can simulate that by adding a simple delay in our `FileSystemMarkdownPageRepo`. + +```php + return array_map(function (string $filename) { + usleep(rand(100, 400) * 1000); + $content = file_get_contents($filename); + if ($content === false) { + throw new InternalServerError('cannot read pages'); + } + $idAndTitle = str_replace([$this->dataPath, '.md'], ['', ''], $filename); + return new MarkdownPage( + (int) substr($idAndTitle, 0, 2), + substr($idAndTitle, 3), + $content + ); +}); +``` + +Here I added a function that pauses the scripts execution for a random time between 100 and 400ms for every markdownpage +in every call of the `all()` method. + +If you open any page or even the listAction in you browser you will see, that it takes quite a time to render that page. +Although this is a silly example we do not really need to query the database on every request, so lets add a way to cache +the database results between requests. + +The PHP-Community has already adressed the issue of having easy to use access to cache libraries, there is the +[PSR-6 Caching Interface](https://www.php-fig.org/psr/psr-6) which gives us easy access to many different implementations, +then there is also a much simpler [PSR-16 Simple Cache](https://www.php-fig.org/psr/psr-16) which makes the use even more +easy, and most Caching Libraries implement Both interfaces anyway. You would think that this is more than enough solutions +to satisfy all the Caching needs around, but the Symfony People decided that Caching should be even simpler and easier +to use and defined their own [Interface](https://symfony.com/doc/current/components/cache.html#cache-component-contracts) +which only needs two methods. You should definitely take a look at the linked documentation as it really blew my mind +when I first encountered it. + +The basic idea is that you provide a callback that computes the requested value. The Cache implementation then checks +if it already has the value stored somewhere and if it doesnt it just executes the callback and stores the value for +future calls. + +It is really simple and great to use. In a real world application you should definitely use that or a PSR-16 implementation +but for this tutorial I wanted to roll out my own solution, so here we go. + +As always we are going to define an interface first, I am going to call it EasyCache and place it in the `Service/Cache` +namespace. I will require only one method which is base on the Symfony Cache Contract, and hast a key, a callback, and +the duration that the item should be cached as arguments. + +```php +cache->get( + $key, + fn () => $this->repo->all(), + 300 + ); + } + + public function byName(string $name): MarkdownPage + { + $key = base64_encode(self::class . 'byName' . $name); + return $this->cache->get( + $key, + fn () => $this->repo->byName($name), + 300 + ); + } +} +``` + +This simple wrapper just requires an EasyCache implementation and a MarkdownPageRepo in the constructor and uses them +to cache all queries for 5 minutes. The beauty is that we are not dependent on any implementation here, so we can switch +out the Repository or the Cache at any point down the road if we want to. + +In order to use that we need to update our `config/dependencies.php` to add an alias for the EasyCache interface as well +as defining our CachedMarkdownPageRepo as implementation for the MarkdownPageRepo interface: + +```php +MarkdownPageRepo::class => fn (CachedMarkdownPageRepo $r) => $r, +EasyCache::class => fn (ApcuCache $c) => $c, +``` + +If we try to access our webpage now, we are getting an error, as PHP-DI has detected a circular dependency that cannot +be autowired. + +The Problem is that our CachedMarkdownPageRepo ist defined as the implementation for the MarkdownPageRepo, but it also +requires that exact interface as a dependency. To resolve this issue we need to manually tell the container how to build +the CachedMarkdownPageRepo by adding another line to the `config/dependencies.php` file: + +```php +CachedMarkdownPageRepo::class => fn (EasyCache $c, FileSystemMarkdownPageRepo $r) => new CachedMarkdownPageRepo($c, $r), +``` + +Here we explicitly require the FileSystemMarkdownPageRepo and us that to create the CachedMarkdownPageRepo object. + +When you now navigate to the pages list or to a specific page the first load should take a while (because of our added delay) +but the following request should be answered blazingly fast. + +Before moving on to the next chapter we can take the caching approach even further, in the middleware chapter I talked +about a simple CachingMiddleware that caches all the GET-Request for some seconds, as they should not change that often, +and we can bypass most of our application logic if we just complelety cache away the responses our application generates, +and return them quite early in our Middleware-Pipeline befor the router gets called, or the invoker calls the action, +which itself uses some other services to fetch all the needed data. + +We will introduce a new `Middleware` namespace to place our `Cache.php` middleware: +```php +getMethod() !== 'GET') { + return $handler->handle($request); + } + $keyHash = base64_encode($request->getUri()->getPath()); + $result = $this->cache->get( + $keyHash, + fn () => Serializer::toString($handler->handle($request)), + 300 + ); + return Serializer::fromString($result); + } +} +``` + +The code is quite straight forward, but you might be confused by the Responseserializer I have added here, we need this +because the response body is a stream object, which doesnt always gets serialized correctly, therefore I use a class from +the laminas project to to all the heavy lifting for us. + +We need to add the now middleware to the `config/middlewares.php` file. + +```php +>](19-database.md) diff --git a/app/public/index.php b/app/public/index.php index d93da3a..32f5eb3 100644 --- a/app/public/index.php +++ b/app/public/index.php @@ -2,4 +2,4 @@ declare(strict_types=1); -require __DIR__ . '/../src/Bootstrap.php'; \ No newline at end of file +require __DIR__ . '/../src/Bootstrap.php'; diff --git a/app/src/Action/Page.php b/app/src/Action/Page.php index 4af45f0..96696e4 100644 --- a/app/src/Action/Page.php +++ b/app/src/Action/Page.php @@ -49,7 +49,7 @@ class Page $pages = array_map(function (MarkdownPage $page) { return [ 'id' => $page->id, - 'title' => $page->content, + 'title' => $page->title, ]; }, $this->repo->all()); diff --git a/app/src/Factory/DoctrineEm.php b/app/src/Factory/DoctrineEm.php deleted file mode 100644 index b0be39b..0000000 --- a/app/src/Factory/DoctrineEm.php +++ /dev/null @@ -1,32 +0,0 @@ -settings->doctrine['devMode']); - - $config->setMetadataDriverImpl( - new AttributeDriver( - $this->settings->doctrine['metadataDirs'] - ) - ); - - return EntityManager::create( - $this->settings->connection, - $config, - ); - } -} diff --git a/app/src/Middleware/Cache.php b/app/src/Middleware/Cache.php new file mode 100644 index 0000000..8460761 --- /dev/null +++ b/app/src/Middleware/Cache.php @@ -0,0 +1,38 @@ +getMethod() !== 'GET') { + return $handler->handle($request); + } + $keyHash = base64_encode($request->getUri()->getPath()); + $result = $this->cache->get( + $keyHash, + fn () => $this->serializer::toString($handler->handle($request)), + 300 + ); + assert(is_string($result)); + return $this->serializer::fromString($result); + } +} diff --git a/app/src/Repository/CachedMarkdownPageRepo.php b/app/src/Repository/CachedMarkdownPageRepo.php new file mode 100644 index 0000000..a4d9180 --- /dev/null +++ b/app/src/Repository/CachedMarkdownPageRepo.php @@ -0,0 +1,49 @@ +cache->get( + $key, + fn () => $this->repo->all(), + 300 + ); + assert(is_array($result)); + foreach ($result as $page) { + assert($page instanceof MarkdownPage); + } + return $result; + } + + public function byName(string $name): MarkdownPage + { + $key = base64_encode(self::class . 'byName' . $name); + $result = $this->cache->get( + $key, + fn () => $this->repo->byName($name), + 300 + ); + assert($result instanceof MarkdownPage); + return $result; + } +} diff --git a/app/src/Service/Cache/ApcuCache.php b/app/src/Service/Cache/ApcuCache.php new file mode 100644 index 0000000..4835098 --- /dev/null +++ b/app/src/Service/Cache/ApcuCache.php @@ -0,0 +1,21 @@ +setRiskyAllowed(true) + ->setRules([ + '@PSR12:risky' => true, + '@PSR12' => true, + '@PHP80Migration' => true, + '@PHP80Migration:risky' => true, + '@PHP81Migration' => true, + 'array_indentation' => true, + 'include' => true, + 'blank_line_after_opening_tag' => false, + 'native_constant_invocation' => true, + 'new_with_braces' => false, + 'native_function_invocation' => [ + 'include' => ['@all'] + ], + 'no_unused_imports' => true, + 'global_namespace_import' => [ + 'import_classes' => true, + 'import_constants' => true, + 'import_functions' => true, + ], + 'ordered_interfaces' => true, + ]) + ->setFinder( + PhpCsFixer\Finder::create() + ->in([ + __DIR__ . '/src', + __DIR__ . '/config' + ]) + ); \ No newline at end of file diff --git a/implementation/18-caching/.phpcs.xml.dist b/implementation/18-caching/.phpcs.xml.dist new file mode 100644 index 0000000..3b433f6 --- /dev/null +++ b/implementation/18-caching/.phpcs.xml.dist @@ -0,0 +1,9 @@ + + + + + src + config + + + \ No newline at end of file diff --git a/implementation/18-caching/cli-config.php b/implementation/18-caching/cli-config.php new file mode 100644 index 0000000..fbc6598 --- /dev/null +++ b/implementation/18-caching/cli-config.php @@ -0,0 +1,13 @@ +getContainer(); + +return ConsoleRunner::createHelperSet($container->get(EntityManagerInterface::class)); diff --git a/implementation/18-caching/composer.json b/implementation/18-caching/composer.json new file mode 100644 index 0000000..29695da --- /dev/null +++ b/implementation/18-caching/composer.json @@ -0,0 +1,57 @@ +{ + "name": "lubian/no-framework", + "require": { + "php": "^8.1", + "filp/whoops": "^2.14", + "laminas/laminas-diactoros": "^2.8", + "nikic/fast-route": "^1.3", + "psr/http-server-handler": "^1.0", + "php-di/php-di": "^6.3", + "mustache/mustache": "^2.14", + "psr/http-server-middleware": "^1.0", + "middlewares/trailing-slash": "^2.0", + "middlewares/whoops": "^2.0", + "erusev/parsedown": "^1.7", + "league/commonmark": "^2.2", + "ext-apcu": "*", + "ext-zend-opcache": "*" + }, + "autoload": { + "psr-4": { + "Lubian\\NoFramework\\": "src/" + } + }, + "authors": [ + { + "name": "lubian", + "email": "test@example.com" + } + ], + "require-dev": { + "phpstan/phpstan": "^1.5", + "php-cs-fixer/shim": "^3.8", + "symfony/var-dumper": "^6.0", + "squizlabs/php_codesniffer": "^3.6", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan-strict-rules": "^1.1", + "thecodingmachine/phpstan-strict-rules": "^1.0", + "mnapoli/hard-mode": "^0.3.0" + }, + "config": { + "optimize-autoloader": true, + "allow-plugins": { + "phpstan/extension-installer": true, + "dealerdirect/phpcodesniffer-composer-installer": true + } + }, + "scripts": { + "serve": [ + "Composer\\Config::disableProcessTimeout", + "php -S 0.0.0.0:1234 -t public" + ], + "phpstan": "./vendor/bin/phpstan analyze", + "baseline": "./vendor/bin/phpstan analyze --generate-baseline", + "check": "./vendor/bin/phpcs", + "fix": "./vendor/bin/php-cs-fixer fix && ./vendor/bin/phpcbf" + } +} diff --git a/implementation/18-caching/composer.lock b/implementation/18-caching/composer.lock new file mode 100644 index 0000000..40cd7d3 --- /dev/null +++ b/implementation/18-caching/composer.lock @@ -0,0 +1,2440 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "9a29468fd456190a9fbcff98ed42d862", + "packages": [ + { + "name": "dflydev/dot-access-data", + "version": "v3.0.1", + "source": { + "type": "git", + "url": "https://github.com/dflydev/dflydev-dot-access-data.git", + "reference": "0992cc19268b259a39e86f296da5f0677841f42c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dflydev/dflydev-dot-access-data/zipball/0992cc19268b259a39e86f296da5f0677841f42c", + "reference": "0992cc19268b259a39e86f296da5f0677841f42c", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.42", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.3", + "scrutinizer/ocular": "1.6.0", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^3.14" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Dflydev\\DotAccessData\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Dragonfly Development Inc.", + "email": "info@dflydev.com", + "homepage": "http://dflydev.com" + }, + { + "name": "Beau Simensen", + "email": "beau@dflydev.com", + "homepage": "http://beausimensen.com" + }, + { + "name": "Carlos Frutos", + "email": "carlos@kiwing.it", + "homepage": "https://github.com/cfrutos" + }, + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com" + } + ], + "description": "Given a deep data structure, access data by dot notation.", + "homepage": "https://github.com/dflydev/dflydev-dot-access-data", + "keywords": [ + "access", + "data", + "dot", + "notation" + ], + "support": { + "issues": "https://github.com/dflydev/dflydev-dot-access-data/issues", + "source": "https://github.com/dflydev/dflydev-dot-access-data/tree/v3.0.1" + }, + "time": "2021-08-13T13:06:58+00:00" + }, + { + "name": "erusev/parsedown", + "version": "1.7.4", + "source": { + "type": "git", + "url": "https://github.com/erusev/parsedown.git", + "reference": "cb17b6477dfff935958ba01325f2e8a2bfa6dab3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/erusev/parsedown/zipball/cb17b6477dfff935958ba01325f2e8a2bfa6dab3", + "reference": "cb17b6477dfff935958ba01325f2e8a2bfa6dab3", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35" + }, + "type": "library", + "autoload": { + "psr-0": { + "Parsedown": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "description": "Parser for Markdown.", + "homepage": "http://parsedown.org", + "keywords": [ + "markdown", + "parser" + ], + "support": { + "issues": "https://github.com/erusev/parsedown/issues", + "source": "https://github.com/erusev/parsedown/tree/1.7.x" + }, + "time": "2019-12-30T22:54:17+00:00" + }, + { + "name": "filp/whoops", + "version": "2.14.5", + "source": { + "type": "git", + "url": "https://github.com/filp/whoops.git", + "reference": "a63e5e8f26ebbebf8ed3c5c691637325512eb0dc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/filp/whoops/zipball/a63e5e8f26ebbebf8ed3c5c691637325512eb0dc", + "reference": "a63e5e8f26ebbebf8ed3c5c691637325512eb0dc", + "shasum": "" + }, + "require": { + "php": "^5.5.9 || ^7.0 || ^8.0", + "psr/log": "^1.0.1 || ^2.0 || ^3.0" + }, + "require-dev": { + "mockery/mockery": "^0.9 || ^1.0", + "phpunit/phpunit": "^4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.3", + "symfony/var-dumper": "^2.6 || ^3.0 || ^4.0 || ^5.0" + }, + "suggest": { + "symfony/var-dumper": "Pretty print complex values better with var-dumper available", + "whoops/soap": "Formats errors as SOAP responses" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.7-dev" + } + }, + "autoload": { + "psr-4": { + "Whoops\\": "src/Whoops/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Filipe Dobreira", + "homepage": "https://github.com/filp", + "role": "Developer" + } + ], + "description": "php error handling for cool kids", + "homepage": "https://filp.github.io/whoops/", + "keywords": [ + "error", + "exception", + "handling", + "library", + "throwable", + "whoops" + ], + "support": { + "issues": "https://github.com/filp/whoops/issues", + "source": "https://github.com/filp/whoops/tree/2.14.5" + }, + "funding": [ + { + "url": "https://github.com/denis-sokolov", + "type": "github" + } + ], + "time": "2022-01-07T12:00:00+00:00" + }, + { + "name": "laminas/laminas-diactoros", + "version": "2.9.0", + "source": { + "type": "git", + "url": "https://github.com/laminas/laminas-diactoros.git", + "reference": "954e2dcfb1607681be44599faac10fc63bb6925a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laminas/laminas-diactoros/zipball/954e2dcfb1607681be44599faac10fc63bb6925a", + "reference": "954e2dcfb1607681be44599faac10fc63bb6925a", + "shasum": "" + }, + "require": { + "php": "^7.3 || ~8.0.0 || ~8.1.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0" + }, + "conflict": { + "phpspec/prophecy": "<1.9.0", + "zendframework/zend-diactoros": "*" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "ext-curl": "*", + "ext-dom": "*", + "ext-gd": "*", + "ext-libxml": "*", + "http-interop/http-factory-tests": "^0.8.0", + "laminas/laminas-coding-standard": "~1.0.0", + "php-http/psr7-integration-tests": "^1.1", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.1", + "psalm/plugin-phpunit": "^0.14.0", + "vimeo/psalm": "^4.3" + }, + "type": "library", + "extra": { + "laminas": { + "config-provider": "Laminas\\Diactoros\\ConfigProvider", + "module": "Laminas\\Diactoros" + } + }, + "autoload": { + "files": [ + "src/functions/create_uploaded_file.php", + "src/functions/marshal_headers_from_sapi.php", + "src/functions/marshal_method_from_sapi.php", + "src/functions/marshal_protocol_version_from_sapi.php", + "src/functions/marshal_uri_from_sapi.php", + "src/functions/normalize_server.php", + "src/functions/normalize_uploaded_files.php", + "src/functions/parse_cookie_header.php", + "src/functions/create_uploaded_file.legacy.php", + "src/functions/marshal_headers_from_sapi.legacy.php", + "src/functions/marshal_method_from_sapi.legacy.php", + "src/functions/marshal_protocol_version_from_sapi.legacy.php", + "src/functions/marshal_uri_from_sapi.legacy.php", + "src/functions/normalize_server.legacy.php", + "src/functions/normalize_uploaded_files.legacy.php", + "src/functions/parse_cookie_header.legacy.php" + ], + "psr-4": { + "Laminas\\Diactoros\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "PSR HTTP Message implementations", + "homepage": "https://laminas.dev", + "keywords": [ + "http", + "laminas", + "psr", + "psr-17", + "psr-7" + ], + "support": { + "chat": "https://laminas.dev/chat", + "docs": "https://docs.laminas.dev/laminas-diactoros/", + "forum": "https://discourse.laminas.dev", + "issues": "https://github.com/laminas/laminas-diactoros/issues", + "rss": "https://github.com/laminas/laminas-diactoros/releases.atom", + "source": "https://github.com/laminas/laminas-diactoros" + }, + "funding": [ + { + "url": "https://funding.communitybridge.org/projects/laminas-project", + "type": "community_bridge" + } + ], + "time": "2022-03-29T20:12:16+00:00" + }, + { + "name": "league/commonmark", + "version": "2.2.3", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/commonmark.git", + "reference": "47b015bc4e50fd4438c1ffef6139a1fb65d2ab71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/47b015bc4e50fd4438c1ffef6139a1fb65d2ab71", + "reference": "47b015bc4e50fd4438c1ffef6139a1fb65d2ab71", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "league/config": "^1.1.1", + "php": "^7.4 || ^8.0", + "psr/event-dispatcher": "^1.0", + "symfony/deprecation-contracts": "^2.1 || ^3.0", + "symfony/polyfill-php80": "^1.15" + }, + "require-dev": { + "cebe/markdown": "^1.0", + "commonmark/cmark": "0.30.0", + "commonmark/commonmark.js": "0.30.0", + "composer/package-versions-deprecated": "^1.8", + "erusev/parsedown": "^1.0", + "ext-json": "*", + "github/gfm": "0.29.0", + "michelf/php-markdown": "^1.4", + "phpstan/phpstan": "^0.12.88 || ^1.0.0", + "phpunit/phpunit": "^9.5.5", + "scrutinizer/ocular": "^1.8.1", + "symfony/finder": "^5.3", + "symfony/yaml": "^2.3 | ^3.0 | ^4.0 | ^5.0 | ^6.0", + "unleashedtech/php-coding-standard": "^3.1", + "vimeo/psalm": "^4.7.3" + }, + "suggest": { + "symfony/yaml": "v2.3+ required if using the Front Matter extension" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.3-dev" + } + }, + "autoload": { + "psr-4": { + "League\\CommonMark\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "description": "Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and GitHub-Flavored Markdown (GFM)", + "homepage": "https://commonmark.thephpleague.com", + "keywords": [ + "commonmark", + "flavored", + "gfm", + "github", + "github-flavored", + "markdown", + "md", + "parser" + ], + "support": { + "docs": "https://commonmark.thephpleague.com/", + "forum": "https://github.com/thephpleague/commonmark/discussions", + "issues": "https://github.com/thephpleague/commonmark/issues", + "rss": "https://github.com/thephpleague/commonmark/releases.atom", + "source": "https://github.com/thephpleague/commonmark" + }, + "funding": [ + { + "url": "https://www.colinodell.com/sponsor", + "type": "custom" + }, + { + "url": "https://www.paypal.me/colinpodell/10.00", + "type": "custom" + }, + { + "url": "https://github.com/colinodell", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/league/commonmark", + "type": "tidelift" + } + ], + "time": "2022-02-26T21:24:45+00:00" + }, + { + "name": "league/config", + "version": "v1.1.1", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/config.git", + "reference": "a9d39eeeb6cc49d10a6e6c36f22c4c1f4a767f3e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/config/zipball/a9d39eeeb6cc49d10a6e6c36f22c4c1f4a767f3e", + "reference": "a9d39eeeb6cc49d10a6e6c36f22c4c1f4a767f3e", + "shasum": "" + }, + "require": { + "dflydev/dot-access-data": "^3.0.1", + "nette/schema": "^1.2", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.90", + "phpunit/phpunit": "^9.5.5", + "scrutinizer/ocular": "^1.8.1", + "unleashedtech/php-coding-standard": "^3.1", + "vimeo/psalm": "^4.7.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.2-dev" + } + }, + "autoload": { + "psr-4": { + "League\\Config\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Colin O'Dell", + "email": "colinodell@gmail.com", + "homepage": "https://www.colinodell.com", + "role": "Lead Developer" + } + ], + "description": "Define configuration arrays with strict schemas and access values with dot notation", + "homepage": "https://config.thephpleague.com", + "keywords": [ + "array", + "config", + "configuration", + "dot", + "dot-access", + "nested", + "schema" + ], + "support": { + "docs": "https://config.thephpleague.com/", + "issues": "https://github.com/thephpleague/config/issues", + "rss": "https://github.com/thephpleague/config/releases.atom", + "source": "https://github.com/thephpleague/config" + }, + "funding": [ + { + "url": "https://www.colinodell.com/sponsor", + "type": "custom" + }, + { + "url": "https://www.paypal.me/colinpodell/10.00", + "type": "custom" + }, + { + "url": "https://github.com/colinodell", + "type": "github" + } + ], + "time": "2021-08-14T12:15:32+00:00" + }, + { + "name": "middlewares/trailing-slash", + "version": "v2.0.1", + "source": { + "type": "git", + "url": "https://github.com/middlewares/trailing-slash.git", + "reference": "1bedcedbc89be78595c5a7a86776fe5ed003e819" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/middlewares/trailing-slash/zipball/1bedcedbc89be78595c5a7a86776fe5ed003e819", + "reference": "1bedcedbc89be78595c5a7a86776fe5ed003e819", + "shasum": "" + }, + "require": { + "middlewares/utils": "^3.0", + "php": "^7.2 || ^8.0", + "psr/http-server-middleware": "^1.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.0", + "laminas/laminas-diactoros": "^2.2", + "oscarotero/php-cs-fixer-config": "^1.0", + "phpstan/phpstan": "^0.12", + "phpunit/phpunit": "^8|^9", + "squizlabs/php_codesniffer": "^3.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Middlewares\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Middleware to normalize the trailing slash of the uri path", + "homepage": "https://github.com/middlewares/trailing-slash", + "keywords": [ + "http", + "middleware", + "normalize", + "path", + "psr-15", + "psr-7", + "slash" + ], + "support": { + "issues": "https://github.com/middlewares/trailing-slash/issues", + "source": "https://github.com/middlewares/trailing-slash/tree/v2.0.1" + }, + "time": "2020-12-02T00:06:55+00:00" + }, + { + "name": "middlewares/utils", + "version": "v3.3.0", + "source": { + "type": "git", + "url": "https://github.com/middlewares/utils.git", + "reference": "670b135ce0dbd040eadb025a9388f9bd617cc010" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/middlewares/utils/zipball/670b135ce0dbd040eadb025a9388f9bd617cc010", + "reference": "670b135ce0dbd040eadb025a9388f9bd617cc010", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0", + "psr/container": "^1.0 || ^2.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0", + "psr/http-server-middleware": "^1.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^v2.16", + "guzzlehttp/psr7": "^2.0", + "laminas/laminas-diactoros": "^2.4", + "nyholm/psr7": "^1.0", + "oscarotero/php-cs-fixer-config": "^1.0", + "phpstan/phpstan": "^0.12", + "phpunit/phpunit": "^8|^9", + "slim/psr7": "^1.4", + "squizlabs/php_codesniffer": "^3.5", + "sunrise/http-message": "^1.0", + "sunrise/http-server-request": "^1.0", + "sunrise/stream": "^1.0.15", + "sunrise/uri": "^1.0.15" + }, + "type": "library", + "autoload": { + "psr-4": { + "Middlewares\\Utils\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Common utils for PSR-15 middleware packages", + "homepage": "https://github.com/middlewares/utils", + "keywords": [ + "PSR-11", + "http", + "middleware", + "psr-15", + "psr-17", + "psr-7" + ], + "support": { + "issues": "https://github.com/middlewares/utils/issues", + "source": "https://github.com/middlewares/utils/tree/v3.3.0" + }, + "time": "2021-07-04T17:56:23+00:00" + }, + { + "name": "middlewares/whoops", + "version": "v2.0.2", + "source": { + "type": "git", + "url": "https://github.com/middlewares/whoops.git", + "reference": "bf0141230ac26814e16f416a75a9596206aefa5f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/middlewares/whoops/zipball/bf0141230ac26814e16f416a75a9596206aefa5f", + "reference": "bf0141230ac26814e16f416a75a9596206aefa5f", + "shasum": "" + }, + "require": { + "filp/whoops": "^2.5", + "middlewares/utils": "^3.0", + "php": "^7.2 || ^8.0", + "psr/container": "^1.0 || ^2.0", + "psr/http-server-middleware": "^1.0" + }, + "require-dev": { + "eloquent/phony-phpunit": "^5.0 || ^7.0", + "friendsofphp/php-cs-fixer": "^2.0", + "laminas/laminas-diactoros": "^2.2", + "oscarotero/php-cs-fixer-config": "^1.0", + "phpstan/phpstan": "^0.12", + "phpunit/phpunit": "^8|^9", + "squizlabs/php_codesniffer": "^3.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Middlewares\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Middleware to use Whoops as error handler", + "homepage": "https://github.com/middlewares/whoops", + "keywords": [ + "error", + "http", + "middleware", + "psr-15", + "psr-7", + "server", + "whoops" + ], + "support": { + "issues": "https://github.com/middlewares/whoops/issues", + "source": "https://github.com/middlewares/whoops/tree/v2.0.2" + }, + "time": "2022-01-27T20:31:30+00:00" + }, + { + "name": "mustache/mustache", + "version": "v2.14.1", + "source": { + "type": "git", + "url": "https://github.com/bobthecow/mustache.php.git", + "reference": "579ffa5c96e1d292c060b3dd62811ff01ad8c24e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/bobthecow/mustache.php/zipball/579ffa5c96e1d292c060b3dd62811ff01ad8c24e", + "reference": "579ffa5c96e1d292c060b3dd62811ff01ad8c24e", + "shasum": "" + }, + "require": { + "php": ">=5.2.4" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "~1.11", + "phpunit/phpunit": "~3.7|~4.0|~5.0" + }, + "type": "library", + "autoload": { + "psr-0": { + "Mustache": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Justin Hileman", + "email": "justin@justinhileman.info", + "homepage": "http://justinhileman.com" + } + ], + "description": "A Mustache implementation in PHP.", + "homepage": "https://github.com/bobthecow/mustache.php", + "keywords": [ + "mustache", + "templating" + ], + "support": { + "issues": "https://github.com/bobthecow/mustache.php/issues", + "source": "https://github.com/bobthecow/mustache.php/tree/v2.14.1" + }, + "time": "2022-01-21T06:08:36+00:00" + }, + { + "name": "nette/schema", + "version": "v1.2.2", + "source": { + "type": "git", + "url": "https://github.com/nette/schema.git", + "reference": "9a39cef03a5b34c7de64f551538cbba05c2be5df" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/schema/zipball/9a39cef03a5b34c7de64f551538cbba05c2be5df", + "reference": "9a39cef03a5b34c7de64f551538cbba05c2be5df", + "shasum": "" + }, + "require": { + "nette/utils": "^2.5.7 || ^3.1.5 || ^4.0", + "php": ">=7.1 <8.2" + }, + "require-dev": { + "nette/tester": "^2.3 || ^2.4", + "phpstan/phpstan-nette": "^0.12", + "tracy/tracy": "^2.7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "📐 Nette Schema: validating data structures against a given Schema.", + "homepage": "https://nette.org", + "keywords": [ + "config", + "nette" + ], + "support": { + "issues": "https://github.com/nette/schema/issues", + "source": "https://github.com/nette/schema/tree/v1.2.2" + }, + "time": "2021-10-15T11:40:02+00:00" + }, + { + "name": "nette/utils", + "version": "v3.2.7", + "source": { + "type": "git", + "url": "https://github.com/nette/utils.git", + "reference": "0af4e3de4df9f1543534beab255ccf459e7a2c99" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nette/utils/zipball/0af4e3de4df9f1543534beab255ccf459e7a2c99", + "reference": "0af4e3de4df9f1543534beab255ccf459e7a2c99", + "shasum": "" + }, + "require": { + "php": ">=7.2 <8.2" + }, + "conflict": { + "nette/di": "<3.0.6" + }, + "require-dev": { + "nette/tester": "~2.0", + "phpstan/phpstan": "^1.0", + "tracy/tracy": "^2.3" + }, + "suggest": { + "ext-gd": "to use Image", + "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()", + "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()", + "ext-json": "to use Nette\\Utils\\Json", + "ext-mbstring": "to use Strings::lower() etc...", + "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()", + "ext-xml": "to use Strings::length() etc. when mbstring is not available" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https://davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https://nette.org/contributors" + } + ], + "description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.", + "homepage": "https://nette.org", + "keywords": [ + "array", + "core", + "datetime", + "images", + "json", + "nette", + "paginator", + "password", + "slugify", + "string", + "unicode", + "utf-8", + "utility", + "validation" + ], + "support": { + "issues": "https://github.com/nette/utils/issues", + "source": "https://github.com/nette/utils/tree/v3.2.7" + }, + "time": "2022-01-24T11:29:14+00:00" + }, + { + "name": "nikic/fast-route", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/FastRoute.git", + "reference": "181d480e08d9476e61381e04a71b34dc0432e812" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/FastRoute/zipball/181d480e08d9476e61381e04a71b34dc0432e812", + "reference": "181d480e08d9476e61381e04a71b34dc0432e812", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35|~5.7" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "FastRoute\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "description": "Fast request router for PHP", + "keywords": [ + "router", + "routing" + ], + "support": { + "issues": "https://github.com/nikic/FastRoute/issues", + "source": "https://github.com/nikic/FastRoute/tree/master" + }, + "time": "2018-02-13T20:26:39+00:00" + }, + { + "name": "opis/closure", + "version": "3.6.3", + "source": { + "type": "git", + "url": "https://github.com/opis/closure.git", + "reference": "3d81e4309d2a927abbe66df935f4bb60082805ad" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opis/closure/zipball/3d81e4309d2a927abbe66df935f4bb60082805ad", + "reference": "3d81e4309d2a927abbe66df935f4bb60082805ad", + "shasum": "" + }, + "require": { + "php": "^5.4 || ^7.0 || ^8.0" + }, + "require-dev": { + "jeremeamia/superclosure": "^2.0", + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.6.x-dev" + } + }, + "autoload": { + "files": [ + "functions.php" + ], + "psr-4": { + "Opis\\Closure\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Marius Sarca", + "email": "marius.sarca@gmail.com" + }, + { + "name": "Sorin Sarca", + "email": "sarca_sorin@hotmail.com" + } + ], + "description": "A library that can be used to serialize closures (anonymous functions) and arbitrary objects.", + "homepage": "https://opis.io/closure", + "keywords": [ + "anonymous functions", + "closure", + "function", + "serializable", + "serialization", + "serialize" + ], + "support": { + "issues": "https://github.com/opis/closure/issues", + "source": "https://github.com/opis/closure/tree/3.6.3" + }, + "time": "2022-01-27T09:35:39+00:00" + }, + { + "name": "php-di/invoker", + "version": "2.3.3", + "source": { + "type": "git", + "url": "https://github.com/PHP-DI/Invoker.git", + "reference": "cd6d9f267d1a3474bdddf1be1da079f01b942786" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-DI/Invoker/zipball/cd6d9f267d1a3474bdddf1be1da079f01b942786", + "reference": "cd6d9f267d1a3474bdddf1be1da079f01b942786", + "shasum": "" + }, + "require": { + "php": ">=7.3", + "psr/container": "^1.0|^2.0" + }, + "require-dev": { + "athletic/athletic": "~0.1.8", + "mnapoli/hard-mode": "~0.3.0", + "phpunit/phpunit": "^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Invoker\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Generic and extensible callable invoker", + "homepage": "https://github.com/PHP-DI/Invoker", + "keywords": [ + "callable", + "dependency", + "dependency-injection", + "injection", + "invoke", + "invoker" + ], + "support": { + "issues": "https://github.com/PHP-DI/Invoker/issues", + "source": "https://github.com/PHP-DI/Invoker/tree/2.3.3" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + } + ], + "time": "2021-12-13T09:22:56+00:00" + }, + { + "name": "php-di/php-di", + "version": "6.3.5", + "source": { + "type": "git", + "url": "https://github.com/PHP-DI/PHP-DI.git", + "reference": "b8126d066ce144765300ee0ab040c1ed6c9ef588" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-DI/PHP-DI/zipball/b8126d066ce144765300ee0ab040c1ed6c9ef588", + "reference": "b8126d066ce144765300ee0ab040c1ed6c9ef588", + "shasum": "" + }, + "require": { + "opis/closure": "^3.5.5", + "php": ">=7.2.0", + "php-di/invoker": "^2.0", + "php-di/phpdoc-reader": "^2.0.1", + "psr/container": "^1.0" + }, + "provide": { + "psr/container-implementation": "^1.0" + }, + "require-dev": { + "doctrine/annotations": "~1.2", + "friendsofphp/php-cs-fixer": "^2.4", + "mnapoli/phpunit-easymock": "^1.2", + "ocramius/proxy-manager": "^2.0.2", + "phpstan/phpstan": "^0.12", + "phpunit/phpunit": "^8.5|^9.0" + }, + "suggest": { + "doctrine/annotations": "Install it if you want to use annotations (version ~1.2)", + "ocramius/proxy-manager": "Install it if you want to use lazy injection (version ~2.0)" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "DI\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "The dependency injection container for humans", + "homepage": "https://php-di.org/", + "keywords": [ + "PSR-11", + "container", + "container-interop", + "dependency injection", + "di", + "ioc", + "psr11" + ], + "support": { + "issues": "https://github.com/PHP-DI/PHP-DI/issues", + "source": "https://github.com/PHP-DI/PHP-DI/tree/6.3.5" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/php-di/php-di", + "type": "tidelift" + } + ], + "time": "2021-09-02T09:49:58+00:00" + }, + { + "name": "php-di/phpdoc-reader", + "version": "2.2.1", + "source": { + "type": "git", + "url": "https://github.com/PHP-DI/PhpDocReader.git", + "reference": "66daff34cbd2627740ffec9469ffbac9f8c8185c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-DI/PhpDocReader/zipball/66daff34cbd2627740ffec9469ffbac9f8c8185c", + "reference": "66daff34cbd2627740ffec9469ffbac9f8c8185c", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "require-dev": { + "mnapoli/hard-mode": "~0.3.0", + "phpunit/phpunit": "^8.5|^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "PhpDocReader\\": "src/PhpDocReader" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PhpDocReader parses @var and @param values in PHP docblocks (supports namespaced class names with the same resolution rules as PHP)", + "keywords": [ + "phpdoc", + "reflection" + ], + "support": { + "issues": "https://github.com/PHP-DI/PhpDocReader/issues", + "source": "https://github.com/PHP-DI/PhpDocReader/tree/2.2.1" + }, + "time": "2020-10-12T12:39:22+00:00" + }, + { + "name": "psr/container", + "version": "1.1.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/513e0666f7216c7459170d56df27dfcefe1689ea", + "reference": "513e0666f7216c7459170d56df27dfcefe1689ea", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/1.1.2" + }, + "time": "2021-11-05T16:50:12+00:00" + }, + { + "name": "psr/event-dispatcher", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Standard interfaces for event handling.", + "keywords": [ + "events", + "psr", + "psr-14" + ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, + "time": "2019-01-08T18:20:26+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/master" + }, + "time": "2019-04-30T12:38:16+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/master" + }, + "time": "2016-08-06T14:39:51+00:00" + }, + { + "name": "psr/http-server-handler", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-server-handler.git", + "reference": "aff2f80e33b7f026ec96bb42f63242dc50ffcae7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-server-handler/zipball/aff2f80e33b7f026ec96bb42f63242dc50ffcae7", + "reference": "aff2f80e33b7f026ec96bb42f63242dc50ffcae7", + "shasum": "" + }, + "require": { + "php": ">=7.0", + "psr/http-message": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP server-side request handler", + "keywords": [ + "handler", + "http", + "http-interop", + "psr", + "psr-15", + "psr-7", + "request", + "response", + "server" + ], + "support": { + "issues": "https://github.com/php-fig/http-server-handler/issues", + "source": "https://github.com/php-fig/http-server-handler/tree/master" + }, + "time": "2018-10-30T16:46:14+00:00" + }, + { + "name": "psr/http-server-middleware", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-server-middleware.git", + "reference": "2296f45510945530b9dceb8bcedb5cb84d40c5f5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-server-middleware/zipball/2296f45510945530b9dceb8bcedb5cb84d40c5f5", + "reference": "2296f45510945530b9dceb8bcedb5cb84d40c5f5", + "shasum": "" + }, + "require": { + "php": ">=7.0", + "psr/http-message": "^1.0", + "psr/http-server-handler": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP server-side middleware", + "keywords": [ + "http", + "http-interop", + "middleware", + "psr", + "psr-15", + "psr-7", + "request", + "response" + ], + "support": { + "issues": "https://github.com/php-fig/http-server-middleware/issues", + "source": "https://github.com/php-fig/http-server-middleware/tree/master" + }, + "time": "2018-10-30T17:12:04+00:00" + }, + { + "name": "psr/log", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/fe5ea303b0887d5caefd3d431c3e61ad47037001", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.0" + }, + "time": "2021-07-14T16:46:02+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.0.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/26954b3d62a6c5fd0ea8a2a00c0353a14978d05c", + "reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c", + "shasum": "" + }, + "require": { + "php": ">=8.0.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.0.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-01-02T09:55:41+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.25.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "4407588e0d3f1f52efb65fbe92babe41f37fe50c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/4407588e0d3f1f52efb65fbe92babe41f37fe50c", + "reference": "4407588e0d3f1f52efb65fbe92babe41f37fe50c", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.25.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-03-04T08:16:47+00:00" + } + ], + "packages-dev": [ + { + "name": "dealerdirect/phpcodesniffer-composer-installer", + "version": "v0.7.2", + "source": { + "type": "git", + "url": "https://github.com/Dealerdirect/phpcodesniffer-composer-installer.git", + "reference": "1c968e542d8843d7cd71de3c5c9c3ff3ad71a1db" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Dealerdirect/phpcodesniffer-composer-installer/zipball/1c968e542d8843d7cd71de3c5c9c3ff3ad71a1db", + "reference": "1c968e542d8843d7cd71de3c5c9c3ff3ad71a1db", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.0 || ^2.0", + "php": ">=5.3", + "squizlabs/php_codesniffer": "^2.0 || ^3.1.0 || ^4.0" + }, + "require-dev": { + "composer/composer": "*", + "php-parallel-lint/php-parallel-lint": "^1.3.1", + "phpcompatibility/php-compatibility": "^9.0" + }, + "type": "composer-plugin", + "extra": { + "class": "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin" + }, + "autoload": { + "psr-4": { + "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Franck Nijhof", + "email": "franck.nijhof@dealerdirect.com", + "homepage": "http://www.frenck.nl", + "role": "Developer / IT Manager" + }, + { + "name": "Contributors", + "homepage": "https://github.com/Dealerdirect/phpcodesniffer-composer-installer/graphs/contributors" + } + ], + "description": "PHP_CodeSniffer Standards Composer Installer Plugin", + "homepage": "http://www.dealerdirect.com", + "keywords": [ + "PHPCodeSniffer", + "PHP_CodeSniffer", + "code quality", + "codesniffer", + "composer", + "installer", + "phpcbf", + "phpcs", + "plugin", + "qa", + "quality", + "standard", + "standards", + "style guide", + "stylecheck", + "tests" + ], + "support": { + "issues": "https://github.com/dealerdirect/phpcodesniffer-composer-installer/issues", + "source": "https://github.com/dealerdirect/phpcodesniffer-composer-installer" + }, + "time": "2022-02-04T12:51:07+00:00" + }, + { + "name": "doctrine/coding-standard", + "version": "8.2.1", + "source": { + "type": "git", + "url": "https://github.com/doctrine/coding-standard.git", + "reference": "f595b060799c1a0d76ead16981804eaa0bbcd8d6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/coding-standard/zipball/f595b060799c1a0d76ead16981804eaa0bbcd8d6", + "reference": "f595b060799c1a0d76ead16981804eaa0bbcd8d6", + "shasum": "" + }, + "require": { + "dealerdirect/phpcodesniffer-composer-installer": "^0.6.2 || ^0.7", + "php": "^7.1 || ^8.0", + "slevomat/coding-standard": "^6.4.1", + "squizlabs/php_codesniffer": "^3.5.8" + }, + "type": "phpcodesniffer-standard", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Steve Müller", + "email": "st.mueller@dzh-online.de" + } + ], + "description": "The Doctrine Coding Standard is a set of PHPCS rules applied to all Doctrine projects.", + "homepage": "https://www.doctrine-project.org/projects/coding-standard.html", + "keywords": [ + "checks", + "code", + "coding", + "cs", + "doctrine", + "rules", + "sniffer", + "sniffs", + "standard", + "style" + ], + "support": { + "issues": "https://github.com/doctrine/coding-standard/issues", + "source": "https://github.com/doctrine/coding-standard/tree/8.2.1" + }, + "time": "2021-04-03T10:54:55+00:00" + }, + { + "name": "mnapoli/hard-mode", + "version": "0.3.0", + "source": { + "type": "git", + "url": "https://github.com/mnapoli/hard-mode.git", + "reference": "9fe24485a079ae8a568113a2d582270cd0265fa2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/mnapoli/hard-mode/zipball/9fe24485a079ae8a568113a2d582270cd0265fa2", + "reference": "9fe24485a079ae8a568113a2d582270cd0265fa2", + "shasum": "" + }, + "require": { + "doctrine/coding-standard": "^8.0" + }, + "type": "phpcodesniffer-standard", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Hard mode for PHP", + "support": { + "issues": "https://github.com/mnapoli/hard-mode/issues", + "source": "https://github.com/mnapoli/hard-mode/tree/0.3.0" + }, + "time": "2020-10-12T07:54:37+00:00" + }, + { + "name": "php-cs-fixer/shim", + "version": "v3.8.0", + "source": { + "type": "git", + "url": "https://github.com/PHP-CS-Fixer/shim.git", + "reference": "d0085a8083140e5203b1ce43add92f894b247e44" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-CS-Fixer/shim/zipball/d0085a8083140e5203b1ce43add92f894b247e44", + "reference": "d0085a8083140e5203b1ce43add92f894b247e44", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-tokenizer": "*", + "php": "^7.4 || ^8.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "support": { + "source": "https://github.com/PHP-CS-Fixer/shim/tree/v3.8.0" + }, + "time": "2022-03-18T17:23:40+00:00" + }, + { + "name": "phpstan/extension-installer", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/phpstan/extension-installer.git", + "reference": "66c7adc9dfa38b6b5838a9fb728b68a7d8348051" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/extension-installer/zipball/66c7adc9dfa38b6b5838a9fb728b68a7d8348051", + "reference": "66c7adc9dfa38b6b5838a9fb728b68a7d8348051", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.1 || ^2.0", + "php": "^7.1 || ^8.0", + "phpstan/phpstan": ">=0.11.6" + }, + "require-dev": { + "composer/composer": "^1.8", + "phing/phing": "^2.16.3", + "php-parallel-lint/php-parallel-lint": "^1.2.0", + "phpstan/phpstan-strict-rules": "^0.11 || ^0.12" + }, + "type": "composer-plugin", + "extra": { + "class": "PHPStan\\ExtensionInstaller\\Plugin" + }, + "autoload": { + "psr-4": { + "PHPStan\\ExtensionInstaller\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Composer plugin for automatic installation of PHPStan extensions", + "support": { + "issues": "https://github.com/phpstan/extension-installer/issues", + "source": "https://github.com/phpstan/extension-installer/tree/1.1.0" + }, + "time": "2020-12-13T13:06:13+00:00" + }, + { + "name": "phpstan/phpdoc-parser", + "version": "0.4.9", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpdoc-parser.git", + "reference": "98a088b17966bdf6ee25c8a4b634df313d8aa531" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/98a088b17966bdf6ee25c8a4b634df313d8aa531", + "reference": "98a088b17966bdf6ee25c8a4b634df313d8aa531", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "consistence/coding-standard": "^3.5", + "ergebnis/composer-normalize": "^2.0.2", + "jakub-onderka/php-parallel-lint": "^0.9.2", + "phing/phing": "^2.16.0", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12.26", + "phpstan/phpstan-strict-rules": "^0.12", + "phpunit/phpunit": "^6.3", + "slevomat/coding-standard": "^4.7.2", + "symfony/process": "^4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.4-dev" + } + }, + "autoload": { + "psr-4": { + "PHPStan\\PhpDocParser\\": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPDoc parser with support for nullable, intersection and generic types", + "support": { + "issues": "https://github.com/phpstan/phpdoc-parser/issues", + "source": "https://github.com/phpstan/phpdoc-parser/tree/master" + }, + "time": "2020-08-03T20:32:43+00:00" + }, + { + "name": "phpstan/phpstan", + "version": "1.5.4", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan.git", + "reference": "bbf68cae24f6dc023c607ea0f87da55dd9d55c2b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/bbf68cae24f6dc023c607ea0f87da55dd9d55c2b", + "reference": "bbf68cae24f6dc023c607ea0f87da55dd9d55c2b", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "support": { + "issues": "https://github.com/phpstan/phpstan/issues", + "source": "https://github.com/phpstan/phpstan/tree/1.5.4" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + }, + { + "url": "https://www.patreon.com/phpstan", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpstan/phpstan", + "type": "tidelift" + } + ], + "time": "2022-04-03T12:39:00+00:00" + }, + { + "name": "phpstan/phpstan-strict-rules", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan-strict-rules.git", + "reference": "e12d55f74a8cca18c6e684c6450767e055ba7717" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan-strict-rules/zipball/e12d55f74a8cca18c6e684c6450767e055ba7717", + "reference": "e12d55f74a8cca18c6e684c6450767e055ba7717", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0", + "phpstan/phpstan": "^1.2.0" + }, + "require-dev": { + "nikic/php-parser": "^4.13.0", + "php-parallel-lint/php-parallel-lint": "^1.2", + "phpstan/phpstan-phpunit": "^1.0", + "phpunit/phpunit": "^9.5" + }, + "type": "phpstan-extension", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + }, + "phpstan": { + "includes": [ + "rules.neon" + ] + } + }, + "autoload": { + "psr-4": { + "PHPStan\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Extra strict and opinionated rules for PHPStan", + "support": { + "issues": "https://github.com/phpstan/phpstan-strict-rules/issues", + "source": "https://github.com/phpstan/phpstan-strict-rules/tree/1.1.0" + }, + "time": "2021-11-18T09:30:29+00:00" + }, + { + "name": "slevomat/coding-standard", + "version": "6.4.1", + "source": { + "type": "git", + "url": "https://github.com/slevomat/coding-standard.git", + "reference": "696dcca217d0c9da2c40d02731526c1e25b65346" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slevomat/coding-standard/zipball/696dcca217d0c9da2c40d02731526c1e25b65346", + "reference": "696dcca217d0c9da2c40d02731526c1e25b65346", + "shasum": "" + }, + "require": { + "dealerdirect/phpcodesniffer-composer-installer": "^0.6.2 || ^0.7", + "php": "^7.1 || ^8.0", + "phpstan/phpdoc-parser": "0.4.5 - 0.4.9", + "squizlabs/php_codesniffer": "^3.5.6" + }, + "require-dev": { + "phing/phing": "2.16.3", + "php-parallel-lint/php-parallel-lint": "1.2.0", + "phpstan/phpstan": "0.12.48", + "phpstan/phpstan-deprecation-rules": "0.12.5", + "phpstan/phpstan-phpunit": "0.12.16", + "phpstan/phpstan-strict-rules": "0.12.5", + "phpunit/phpunit": "7.5.20|8.5.5|9.4.0" + }, + "type": "phpcodesniffer-standard", + "extra": { + "branch-alias": { + "dev-master": "6.x-dev" + } + }, + "autoload": { + "psr-4": { + "SlevomatCodingStandard\\": "SlevomatCodingStandard" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Slevomat Coding Standard for PHP_CodeSniffer complements Consistence Coding Standard by providing sniffs with additional checks.", + "support": { + "issues": "https://github.com/slevomat/coding-standard/issues", + "source": "https://github.com/slevomat/coding-standard/tree/6.4.1" + }, + "funding": [ + { + "url": "https://github.com/kukulich", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/slevomat/coding-standard", + "type": "tidelift" + } + ], + "time": "2020-10-05T12:39:37+00:00" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "3.6.2", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "5e4e71592f69da17871dba6e80dd51bce74a351a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/5e4e71592f69da17871dba6e80dd51bce74a351a", + "reference": "5e4e71592f69da17871dba6e80dd51bce74a351a", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "bin": [ + "bin/phpcs", + "bin/phpcbf" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/squizlabs/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards" + ], + "support": { + "issues": "https://github.com/squizlabs/PHP_CodeSniffer/issues", + "source": "https://github.com/squizlabs/PHP_CodeSniffer", + "wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki" + }, + "time": "2021-12-12T21:44:58+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.25.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "0abb51d2f102e00a4eefcf46ba7fec406d245825" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/0abb51d2f102e00a4eefcf46ba7fec406d245825", + "reference": "0abb51d2f102e00a4eefcf46ba7fec406d245825", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.25.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2021-11-30T18:21:41+00:00" + }, + { + "name": "symfony/var-dumper", + "version": "v6.0.6", + "source": { + "type": "git", + "url": "https://github.com/symfony/var-dumper.git", + "reference": "38358405ae948963c50a3aae3dfea598223ba15e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/38358405ae948963c50a3aae3dfea598223ba15e", + "reference": "38358405ae948963c50a3aae3dfea598223ba15e", + "shasum": "" + }, + "require": { + "php": ">=8.0.2", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "phpunit/phpunit": "<5.4.3", + "symfony/console": "<5.4" + }, + "require-dev": { + "ext-iconv": "*", + "symfony/console": "^5.4|^6.0", + "symfony/process": "^5.4|^6.0", + "symfony/uid": "^5.4|^6.0", + "twig/twig": "^2.13|^3.0.4" + }, + "suggest": { + "ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).", + "ext-intl": "To show region name in time zone dump", + "symfony/console": "To use the ServerDumpCommand and/or the bin/var-dump-server script" + }, + "bin": [ + "Resources/bin/var-dump-server" + ], + "type": "library", + "autoload": { + "files": [ + "Resources/functions/dump.php" + ], + "psr-4": { + "Symfony\\Component\\VarDumper\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides mechanisms for walking through any arbitrary PHP variable", + "homepage": "https://symfony.com", + "keywords": [ + "debug", + "dump" + ], + "support": { + "source": "https://github.com/symfony/var-dumper/tree/v6.0.6" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-03-02T12:58:14+00:00" + }, + { + "name": "thecodingmachine/phpstan-strict-rules", + "version": "v1.0.0", + "source": { + "type": "git", + "url": "https://github.com/thecodingmachine/phpstan-strict-rules.git", + "reference": "2ba8fa8b328c45f3b149c05def5bf96793c594b6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thecodingmachine/phpstan-strict-rules/zipball/2ba8fa8b328c45f3b149c05def5bf96793c594b6", + "reference": "2ba8fa8b328c45f3b149c05def5bf96793c594b6", + "shasum": "" + }, + "require": { + "php": "^7.1|^8.0", + "phpstan/phpstan": "^1.0" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^7.1" + }, + "type": "phpstan-extension", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + }, + "phpstan": { + "includes": [ + "phpstan-strict-rules.neon" + ] + } + }, + "autoload": { + "psr-4": { + "TheCodingMachine\\PHPStan\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "David Négrier", + "email": "d.negrier@thecodingmachine.com" + } + ], + "description": "A set of additional rules for PHPStan based on best practices followed at TheCodingMachine", + "support": { + "issues": "https://github.com/thecodingmachine/phpstan-strict-rules/issues", + "source": "https://github.com/thecodingmachine/phpstan-strict-rules/tree/v1.0.0" + }, + "time": "2021-11-08T09:10:49+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": "^8.1", + "ext-apcu": "*", + "ext-zend-opcache": "*" + }, + "platform-dev": [], + "plugin-api-version": "2.3.0" +} diff --git a/implementation/18-caching/config/dependencies.php b/implementation/18-caching/config/dependencies.php new file mode 100644 index 0000000..df815c6 --- /dev/null +++ b/implementation/18-caching/config/dependencies.php @@ -0,0 +1,58 @@ + fn (SystemClockNow $n) => $n, + ResponseFactoryInterface::class => fn (ResponseFactory $rf) => $rf, + Emitter::class => fn (BasicEmitter $e) => $e, + MiddlewareInterface::class => fn (RouteMiddleware $r) => $r, + RoutedRequestHandler::class => fn (InvokerRoutedHandler $h) => $h, + RequestFactory::class => fn (DiactorosRequestFactory $rf) => $rf, + MarkdownParser::class => fn (ParsedownParser $p) => $p, + MarkdownPageRepo::class => fn (CachedMarkdownPageRepo $r) => $r, + EasyCache::class => fn (ApcuCache $c) => $c, + CachedMarkdownPageRepo::class => fn (EasyCache $c, FileSystemMarkdownPageRepo $r) => new CachedMarkdownPageRepo($c, $r), + + + // Factories + ResponseInterface::class => fn (ResponseFactory $rf) => $rf->createResponse(), + ServerRequestInterface::class => fn (RequestFactory $rf) => $rf->fromGlobals(), + Renderer::class => fn (Mustache_Engine $e) => new MustacheRenderer($e), + MLF::class => fn (Settings $s) => new MLF($s->templateDir, ['extension' => $s->templateExtension]), + ME::class => fn (MLF $mfl) => new ME(['loader' => $mfl]), + Dispatcher::class => fn () => simpleDispatcher(require __DIR__ . '/routes.php'), + Pipeline::class => fn (PipelineProvider $p) => $p->getPipeline(), + FileSystemMarkdownPageRepo::class => fn (Settings $s) => new FileSystemMarkdownPageRepo($s->pagesPath), +]; diff --git a/implementation/18-caching/config/middlewares.php b/implementation/18-caching/config/middlewares.php new file mode 100644 index 0000000..ab662be --- /dev/null +++ b/implementation/18-caching/config/middlewares.php @@ -0,0 +1,13 @@ +addRoute('GET', '/hello[/{name}]', Hello::class); + $r->addRoute('GET', '/page', [Page::class, 'list']); + $r->addRoute('GET', '/page/{page}', [Page::class, 'show']); + $r->addRoute('GET', '/another-route', [Other::class, 'someFunctionName']); + $r->addRoute('GET', '/', fn (Response $r) => $r->withStatus(302)->withHeader('Location', '/hello')); +}; diff --git a/implementation/18-caching/config/settings.php b/implementation/18-caching/config/settings.php new file mode 100644 index 0000000..c654565 --- /dev/null +++ b/implementation/18-caching/config/settings.php @@ -0,0 +1,12 @@ +>](02-composer.md) + +### Front Controller + +A [front controller](http://en.wikipedia.org/wiki/Front_Controller_pattern) is a single point of entry for your application. + +To start, create an empty directory for your project. You also need an entry point where all requests will go to. This means you will have to create an `index.php` file. + +A common way to do this is to just put the `index.php` in the root folder of the projects. This is also how some frameworks do it. Let me explain why you should not do this. + +The `index.php` is the starting point, so it has to be inside the web server directory. This means that the web server has access to all subdirectories. If you set things up properly, you can still prevent it from accessing your subfolders where your application files are. + +But sometimes things don't go according to plan. And if something goes wrong and your files are set up as above, your whole application source code could be exposed to visitors. I won't have to explain why this is not a good thing. + +So instead of doing that, create a folder in your project folder called `public`. This is a good time to create an `src` folder for your application, also in the project root folder. + +Inside the `public` folder you can now create your `index.php`. Remember that you don't want to expose anything here, so put just the following code in there: + +```php +>](02-composer.md) diff --git a/implementation/18-caching/data/pages/02-composer.md b/implementation/18-caching/data/pages/02-composer.md new file mode 100644 index 0000000..a25a4a8 --- /dev/null +++ b/implementation/18-caching/data/pages/02-composer.md @@ -0,0 +1,75 @@ +[<< previous](01-front-controller.md) | [next >>](03-error-handler.md) + +### Composer + +[Composer](https://getcomposer.org/) is a dependency manager for PHP. + +Just because you are not using a framework does not mean you will have to reinvent the wheel every time you want to do +something. With Composer, you can install third-party libraries for your application. + +If you don't have Composer installed already, head over to the website and install it. You can find Composer packages +for your project on [Packagist](https://packagist.org/). + +Create a new file in your project root folder called `composer.json`. This is the Composer configuration file that will +be used to configure your project and its dependencies. It must be valid JSON or Composer will fail. + +Add the following content to the file: + +```json +{ + "name": "lubian/no-framework", + "require": { + "php": "^8.1" + }, + "autoload": { + "psr-4": { + "Lubian\\NoFramework\\": "src/" + } + }, + "authors": [ + { + "name": "lubiana", + "email": "lubiana@hannover.ccc.de" + } + ] +} +``` + +In the autoload part you can see that I am using the `Lubian\NoFramework` namespace for the project. You can use +whatever fits your project there, but from now on I will always use the `Lubian\NoFramework` namespace in my examples. +Just replace it with your namespace in your own code. + +I have also defined, that all my code and classes in the 'Lubian\NoFramework' namespace lives under the './src' folder. + +As the Bootstrap.php file is placed in that directory we should +add the namespace to the File as well. Here is my current Bootstrap.php +as a reference: + +```php +>](03-error-handler.md) diff --git a/implementation/18-caching/data/pages/03-error-handler.md b/implementation/18-caching/data/pages/03-error-handler.md new file mode 100644 index 0000000..60465d0 --- /dev/null +++ b/implementation/18-caching/data/pages/03-error-handler.md @@ -0,0 +1,79 @@ +[<< previous](02-composer.md) | [next >>](04-development-helpers.md) + +### Error Handler + +An error handler allows you to customize what happens if your code results in an error. + +A nice error page with a lot of information for debugging goes a long way during development. So the first package +for your application will take care of that. + +I like [filp/whoops](https://github.com/filp/whoops), so I will show how you can install that package for your project. +If you prefer another package, feel free to install that one. This is the beauty of programming without a framework, +you have total control over your project. + +An alternative package would be: [PHP-Error](https://github.com/JosephLenton/PHP-Error) + +To install a new package, open up your `composer.json` and add the package to the require part. It should now look +like this: + +```php +"require": { + "php": ">=8.1.0", + "filp/whoops": "^2.14" +}, +``` + +Now run `composer update` in your console and it will be installed. + +Another way to install packages is to simply type "composer require filp/whoops" into your terminal at the project root, +i that case composer automatically installs the package and updates your composer.json-file. + +But you can't use it yet. PHP won't know where to find the files for the classes. For this you will need an autoloader, +ideally a [PSR-4](http://www.php-fig.org/psr/psr-4/) autoloader. Composer already takes care of this for you, so you +only have to add a `require __DIR__ . '/../vendor/autoload.php';` to your `Bootstrap.php`. + +**Important:** Never show any errors in your production environment. A stack trace or even just a simple error message +can help someone to gain access to your system. Always show a user friendly error page instead and send an email to +yourself, write to a log or something similar. So only you can see the errors in the production environment. + +For development that does not make sense though -- you want a nice error page. The solution is to have an environment +switch in your code. We use the getenv() function here to check the environment and define the 'dev' env as standard in +case no environment has been set. + +Then after the error handler registration, throw an `Exception` to test if everything is working correctly. +Your `Bootstrap.php` should now look similar to this: + +```php +pushHandler(new PrettyPageHandler); +} else { + $whoops->pushHandler(function (\Throwable $e) { + error_log("Error: " . $e->getMessage(), $e->getCode()); + echo 'An Error happened'; + }); +} +$whoops->register(); + +throw new \Exception("Ooooopsie"); + +``` + +You should now see a error page with the line highlighted where you throw the exception. If not, go back and debug until +you get it working. Now would also be a good time for another commit. + + +[<< previous](02-composer.md) | [next >>](04-development-helpers.md) diff --git a/implementation/18-caching/data/pages/04-development-helpers.md b/implementation/18-caching/data/pages/04-development-helpers.md new file mode 100644 index 0000000..74f913c --- /dev/null +++ b/implementation/18-caching/data/pages/04-development-helpers.md @@ -0,0 +1,260 @@ +[<< previous](03-error-handler.md) | [next >>](05-http.md) + +### Development Helpers + +I have added some more helpers to my composer.json that help me with development. As these are scripts and programms +used only for development they should not be used in a production environment. Composer has a specific sections in its +file called "dev-dependencies", everything that is required in this section does not get installen in production. + +Let's install our dev-helpers and i will explain them one by one: +`composer require --dev phpstan/phpstan php-cs-fixer/shim symfony/var-dumper squizlabs/php_codesniffer` + +#### Static Code Analysis with phpstan + +Phpstan is a great little tool, that tries to understand your code and checks if you are making any grave mistakes or +create bad defined interfaces and structures. It also helps in finding logic-errors, dead code, access to array elements +that are not (or not always) available, if-statements that always are true and a lot of other stuff. + +A very simple example would be a small functions that takes a DateTime-Object and prints it in a human readable format. + +```php +/** + * @param \DateTime $date + * @return void + */ +function printDate($date) { + $date->format('Y-m-d H:i:s'); +} + +printDate('now'); +``` +if we run phpstan with the command `./vendor/bin/phpstan analyse --level 9 ./src/` + +It firstly tells us that calling "format" on a DateTime-Object without outputting or returning the function result has +no use, and secondly, that we are calling the function with a string instead of a datetime object. + +```shell +1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100% + + ------ --------------------------------------------------------------------------------------------- +Line Bootstrap.php + ------ --------------------------------------------------------------------------------------------- +30 Call to method DateTime::format() on a separate line has no effect. +33 Parameter #1 $date of function Lubian\NoFramework\printDate expects DateTime, string given. + ------ --------------------------------------------------------------------------------------------- +``` + +The second error is something that "declare strict-types" already catches for us, but the first error is something that +we usually would not discover easily without speccially looking for this errortype. + +We can add a simple configfile called phpstan.neon to our project so that we do not have to specify the errorlevel and +path everytime we want to check our code for errors: + +```yaml +parameters: + level: max + paths: + - src +``` +now we can just call `./vendor/bin/phpstan analyze` and have the same setting for every developer working in our project + +With this settings we have already a great setup to catch some errors before we execute the code, but it still allows us +some silly things, therefore we want to add install some packages that enforce rules that are a little bit more strict. + +```shell +composer require --dev phpstan/extension-installer +composer require --dev phpstan/phpstan-strict-rules thecodingmachine/phpstan-strict-rules +``` + +During the first install you need to allow the extension installer to actually install the extension. The second command +installs some more strict rulesets and activates them in phpstan. + +If we now rerun phpstan it already tells us about some errors we have made: + +``` + ------ ----------------------------------------------------------------------------------------------- +Line Bootstrap.php + ------ ----------------------------------------------------------------------------------------------- +10 Short ternary operator is not allowed. Use null coalesce operator if applicable or consider + using long ternary. +25 Do not throw the \Exception base class. Instead, extend the \Exception base class. More info: + http://bit.ly/subtypeexception +26 Unreachable statement - code above always terminates. + ------ ----------------------------------------------------------------------------------------------- +``` + +The last two Errors are caused by the Exception we have used to test the ErrorHandler in the last chapter if we remove +that we should be able to fix that. The first error is something we could fix, but I dont want to focus on that specific +problem right now. Phpstan gives us the option to ignore some errors and handle them later. If for example we are working +on an old legacy codebase and wanted to add static analysis to it but cant because we would get 1 Million error messages +everytime we use phpstan, we could add all those errors to a list and tell phpstan to only bother us about new errors we +are adding to our code. + +In order to use that we have to add an empty file 'phpstan-baseline.neon' to our project, include that in the +phpstan.neon file and run phpstan with the +'--generate-baseline' option: + +```yaml +includes: + - phpstan-baseline.neon + +parameters: + level: 9 + paths: + - src +``` +```shell +[vagrant@archlinux app]$ ./vendor/bin/phpstan analyze --generate-baseline +Note: Using configuration file /home/vagrant/app/phpstan.neon. + 1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100% + + + + [OK] Baseline generated with 1 error. + + +``` + +you can read more about the possible parameters and usage options in the [documentation](https://phpstan.org/user-guide/getting-started) + +#### PHP-CS-Fixer + +Another great tool is the php-cs-fixer, which just applies a specific style to your code. + +when you run `./vendor/bin/php-cs-fixer fix ./` it applies the psr-12 code style to every php file in you current +directory. + +You can read more about its usage and possible rulesets in the [documentation](https://github.com/FriendsOfPHP/PHP-CS-Fixer#documentation) + +personally i like to have a more opiniated version with some rules added to the psr-12 standard and have therefore setup +a configuration file that i use in all my projects .php-cs-fixer.php: + +```php +setRiskyAllowed(true) + ->setRules([ + '@PSR12:risky' => true, + '@PSR12' => true, + '@PHP80Migration' => true, + '@PHP80Migration:risky' => true, + '@PHP81Migration' => true, + 'array_indentation' => true, + 'include' => true, + 'blank_line_after_opening_tag' => false, + 'native_constant_invocation' => true, + 'new_with_braces' => false, + 'native_function_invocation' => [ + 'include' => ['@all'] + ], + 'no_unused_imports' => true, + 'global_namespace_import' => [ + 'import_classes' => true, + 'import_constants' => true, + 'import_functions' => true, + ], + 'ordered_interfaces' => true, + ]) + ->setFinder( + PhpCsFixer\Finder::create() + ->in([ + __DIR__ . '/src', + ]) + ); +``` + +#### PHP Codesniffer + +The PHPCodesniffer is sort of a combination of the previous tools, it checks for a defined codingstyle and some extra +rules that are not just stylechanges but instead enforces extra rules in if-statements, exception handling etc. + +it provides the phpcs command to check for violations and the phpcbf command to actually fix most of the violations. + +Without configuration the tool tries to apply the PSR12 standard just like the php-cs-fixer, but as you might have +guessed we are adding some extra rules. + +Lets install the ruleset with composer +```shell +composer require --dev mnapoli/hard-mode +``` + +and add a configuration file to actually use it '.phpcs.xml.dist' +```xml + + + + + src + + + +``` + +running `./vendor/bin/phpcs` now checks our src directory for violations and gives us a detailed list about the findings. + +``` +[vagrant@archlinux app]$ ./vendor/bin/phpcs + +FILE: src/Bootstrap.php +---------------------------------------------------------------------------------------------------- +FOUND 4 ERRORS AFFECTING 4 LINES +---------------------------------------------------------------------------------------------------- + 7 | ERROR | [x] Use statements should be sorted alphabetically. The first wrong one is Throwable. + 8 | ERROR | [x] Expected 1 lines between different types of use statement, found 0. + 11 | ERROR | [x] Expected 1 lines between different types of use statement, found 0. + 24 | ERROR | [x] String "ERROR: " does not require double quotes; use single quotes instead +---------------------------------------------------------------------------------------------------- +PHPCBF CAN FIX THE 4 MARKED SNIFF VIOLATIONS AUTOMATICALLY +---------------------------------------------------------------------------------------------------- + +Time: 639ms; Memory: 10MB +``` + +You can then use `./vendor/bin/phpcbf` to try to fix them + + +#### Symfony Var-Dumper + +another great tool for some quick debugging without xdebug is the symfony var-dumper. This just gives us some small +functions. + +dump(); is basically like phps var_dump() but has a better looking output that helps when looking into bigger objects +or arrays. + +dd() on the other hand is a function that dumps its parameters and then exits the php-script. + +you could just write dd($whoops) somewhere in your bootstrap.php to check how the output looks. + +#### Composer scripts + +now we have a few commands that are available on the command line. i personally do not like to type complex commands +with lots of parameters by hand all the time, so i added a few lines to my composer.json: + +```json +"scripts": { + "serve": "php -S 0.0.0.0:1234 -t public", + "phpstan": "./vendor/bin/phpstan analyze", + "baseline": "./vendor/bin/phpstan analyze --generate-baseline", + "check": "./vendor/bin/phpcs", + "fix": "./vendor/bin/php-cs-fixer fix && ./vendor/bin/phpcbf" +}, +``` + +that way i can just type "composer" followed by the command name in the root of my project. if i want to start the +php devserver i can just type "composer serve" and dont have to type in the hostname, port and targetdirectory all the +time. + +You could also configure PhpStorm to automatically run these commands in the background and highlight the violations +directly in the file you are currently editing. I personally am not a fan of this approach because it often disrupts my +flow when programming and always forces me to be absolutely strict even if I am only trying out an idea for debugging. + +My workflow is to just write my code the way i currently feel and that execute the phpstan and the fix scripts before +commiting and pushing the code. + +[<< previous](03-error-handler.md) | [next >>](05-http.md) diff --git a/implementation/18-caching/data/pages/05-http.md b/implementation/18-caching/data/pages/05-http.md new file mode 100644 index 0000000..6166214 --- /dev/null +++ b/implementation/18-caching/data/pages/05-http.md @@ -0,0 +1,124 @@ +[<< previous](04-development-helpers.md) | [next >>](06-router.md) + +### HTTP + +PHP already has a few things built in to make working with HTTP easier. For example there are the +[superglobals](http://php.net/manual/en/language.variables.superglobals.php) that contain the request information. + +These are good if you just want to get a small script up and running, something that won't be hard to maintain. However, +if you want to write clean, maintainable, [SOLID](http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29) code, +then you will want a class with a nice object-oriented interface that you can use in your application instead. + +Fortunately for us there has been a standard developed in the PHP-Community that is adopted by several Frameworks. The +standard is called [PSR-7](https://www.php-fig.org/psr/psr-7/) and has several interfaces defined that a lot of php +projects implement. This makes it easier for us to use modules developed for other frameworks in our projects. + +As this is a widely adopted standard there are already several implementations available for us to use. I will choose +the laminas/laminas-diactoros package as i am an old time fan of the laminas (previously zend) project. + +Some alternatives are [slim-psr7](https://github.com/slimphp/Slim-Psr7), [Guzzle](https://github.com/guzzle/psr7) and a +[lot more](https://packagist.org/providers/psr/http-message-implementation) are available for you to choose from. + +Symfony ships its own Request and Response objects that do not implement the psr-7 interfaces. Therefore i will not use +that in this tutorial, but if you understand how the psr-7 interfaces work you should have no problem in understanding +the [symfony http-foundation](https://symfony.com/doc/current/components/http_foundation.html#request). + + +to install the laminas psr-packages just type `composer require laminas/laminas-diactoros` into your console and hit +enter + +Now you can add the following below your error handler code in your `Bootstrap.php` (and don't forget to remove the exception): + +```php +$request = Laminas\Diactoros\ServerRequestFactory::fromGlobals(); +$response = new \Laminas\Diactoros\Response; +$response->getBody()->write('Hello World! '); +$response->getBody()->write('The Uri is: ' . $request->getUri()->getPath()); +``` + +This sets up the `Request` and `Response` objects that you can use in your other classes to get request data and send a response back to the browser. + +In order to actually add content to the response you have to access the Body-Streamobject of the Response and use the +write()-Method on that object. + + +To actually send something back, you will also need to add the following snippet at the end of your `Bootstrap.php` file: + +```php +echo $response->getBody(); +``` + +This will send the response data to the browser. If you don't do this, nothing happens as the `Response` object only +stores data. + +You can play around with the other methods of the Request object and take a look at its content with the dd() function. + +```php +dd($response) +``` + +Something you have to keep in mind is that the Response and Request objects are Immutable which means that they cannot +be changed after creation. Whenever you want to modify a property you have to call one of the "with" functions, which +creates a copy of the request object with the changed property and returns that clone: + +```php +$response = $response->withStatus(200); +$response = $response->withAddedHeader('Content-type', 'application/json'); +``` + +If you have ever struggled with Mutationproblems in an DateTime-Object you might understand why the standard has been +defined this way. + +But if you have been keeping attention you might argue that the following line should not work if the request object is +immutable. + +```php +$response->getBody()->write('Hello World!'); +``` + +The response-body implements a stream interface which is immutable for some reasons that are described in the +[meta-document](https://www.php-fig.org/psr/psr-7/meta/#why-are-streams-mutable). For me the important thing is to be +aware of the problems that can occur with mutable objects. Here is a small [Blogpost](http://andrew.carterlunn.co.uk/programming/2016/05/22/psr-7-is-not-immutable.html) that gives some context. Beware that the Middleware-Example in +the post is based on a deprecated middleware standard. But more on middlewares will be discussed in later chapters. +I for one am happy about that fact, as it saves me from writing at least 3 lines of code whenever i want to add content +to a response object. + +```php +$body = $response->getBody(); +$body->write('Hello World!'); +$response = $response->withBody($body); +``` + +Right now we are just outputting the Response-Body without any headers or http-status. So we need to expand our +output-logic a little bit more. Replace the line that echos the response-body with the following: + +```php +foreach ($response->getHeaders() as $name => $values) { + $first = strtolower($name) !== 'set-cookie'; + foreach ($values as $value) { + $header = sprintf('%s: %s', $name, $value); + header($header, $first); + $first = false; + } +} + +$statusLine = sprintf( + 'HTTP/%s %s %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() +); +header($statusLine, true, $response->getStatusCode()); + +echo $response->getBody(); +``` + +This code is still fairly simple and there is a lot more stuff that can be considered when emitting a response to a +webbrowser, if you want a more complete solution you can take a look at the [httpsoft/http-emitter](https://github.com/httpsoft/http-emitter/blob/master/src/SapiEmitter.php) package on github. + +Remember that the object is only storing data, so if you set multiple status codes before you send the response, only the last one will be applied. + +Be sure to run composer phpstan, composer fix and composer check before moving on to the next chapter + + +[<< previous](04-development-helpers.md) | [next >>](06-router.md) diff --git a/implementation/18-caching/data/pages/06-router.md b/implementation/18-caching/data/pages/06-router.md new file mode 100644 index 0000000..6c39ae5 --- /dev/null +++ b/implementation/18-caching/data/pages/06-router.md @@ -0,0 +1,101 @@ +[<< previous](05-http.md) | [next >>](07-dispatching-to-a-class.md) + +### Router + +A router dispatches to different handlers depending on rules that you have set up. + +With your current setup it does not matter what URL is used to access the application, it will always result in the same +response. So let's fix that now. + +I will use [nikic/fast-route](https://github.com/nikic/FastRoute) in this tutorial. But as always, you can pick your own +favorite package. + +Alternative packages: [symfony/Routing](https://github.com/symfony/Routing), [Aura.Router](https://github.com/auraphp/Aura.Router), [fuelphp/routing](https://github.com/fuelphp/routing), [Klein](https://github.com/chriso/klein.php) + +By now you know how to install Composer packages, so I will leave that to you. + +Now add this code block to your `Bootstrap.php` file where you added the 'hello world' message in the last chapter. + +```php +$dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) { + $r->addRoute('GET', '/hello[/{name}]', function (\Psr\Http\Message\ServerRequestInterface $request) { + $name = $request->getAttribute('name', 'Stranger'); + $response = (new \Laminas\Diactoros\Response)->withStatus(200); + $response->getBody()->write('Hello ' . $name . '!'); + return $response; + }); + $r->addRoute('GET', '/another-route', function (\Psr\Http\Message\ServerRequestInterface $request) { + $response = (new \Laminas\Diactoros\Response)->withStatus(200); + $response->getBody()->write('This works too!'); + return $response; + }); +}); + +$routeInfo = $dispatcher->dispatch( + $request->getMethod(), + $request->getUri()->getPath(), +); + +switch ($routeInfo[0]) { + case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED: + $response = (new \Laminas\Diactoros\Response)->withStatus(405); + $response->getBody()->write('Method not allowed'); + $response = $response->withStatus(405); + break; + case \FastRoute\Dispatcher::FOUND: + $handler = $routeInfo[1]; + foreach ($routeInfo[2] as $attributeName => $attributeValue) { + $request = $request->withAttribute($attributeName, $attributeValue); + } + /** @var \Psr\Http\Message\ResponseInterface $response */ + $response = call_user_func($handler, $request); + break; + case \FastRoute\Dispatcher::NOT_FOUND: + default: + $response = (new \Laminas\Diactoros\Response)->withStatus(404); + $response->getBody()->write('Not Found!'); + break; +} +``` + +In the first part of the code, you are registering the available routes for your application. In the second part, the +dispatcher gets called and the appropriate part of the switch statement will be executed. If a route was found, +we collect any variable parameters of the route, store them in the request parameterbag and call the handler callable. +If the route dispatcher returns a wrong value in the first entry of the routeMatch array we handle it the same as a 404. + +This setup might work for really small applications, but once you start adding a few routes your bootstrap file will +quickly get cluttered. So let's move them out into a separate file. + +Create a new directory in you projectroot named 'config' and add a 'routes.php' file with the following content; + +```php +addRoute('GET', '/hello[/{name}]', function (\Psr\Http\Message\ServerRequestInterface $request) { + $name = $request->getAttribute('name', 'Stranger'); + $response = (new \Laminas\Diactoros\Response)->withStatus(200); + $response->getBody()->write('Hello ' . $name . '!'); + return $response; + }); + $r->addRoute('GET', '/another-route', function (\Psr\Http\Message\ServerRequestInterface $request) { + $response = (new Laminas\Diactoros\Response)->withStatus(200); + $response->getBody()->write('This works too!'); + return $response; + }); +}; +``` + +Now let's rewrite the route dispatcher part to use the `Routes.php` file. + +```php +$routeDefinitionCallback = require __DIR__ . '/../config/routes.php'; +$dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback); +``` + +This is already an improvement, but now all the handler code is in the `routes.php` file. This is not optimal, so let's fix that in the next part. + +Of course we now need to add the 'config' folder to the configuration files of our +devhelpers so that they can scan that directory as well. + +[<< previous](05-http.md) | [next >>](07-dispatching-to-a-class.md) diff --git a/implementation/18-caching/data/pages/07-dispatching-to-a-class.md b/implementation/18-caching/data/pages/07-dispatching-to-a-class.md new file mode 100644 index 0000000..0c961a4 --- /dev/null +++ b/implementation/18-caching/data/pages/07-dispatching-to-a-class.md @@ -0,0 +1,137 @@ +[<< previous](06-router.md) | [next >>](08-inversion-of-control.md) + +### Dispatching to a Class + +In this tutorial we won't implement [MVC (Model-View-Controller)](http://martinfowler.com/eaaCatalog/modelViewController.html). +MVC can't be implemented properly in PHP anyway, at least not in the way it was originally conceived. If you want to +learn more about this, read [A Beginner's Guide To MVC](http://blog.ircmaxell.com/2014/11/a-beginners-guide-to-mvc-for-web.html) +and the followup posts. + +So forget about MVC and instead let's worry about [separation of concerns](http://en.wikipedia.org/wiki/Separation_of_concerns). + +We will need a descriptive name for the classes that handle the requests. For this tutorial I will use `Handler`, other +common names are 'Controllers' or 'Actions'. + +Create a new folder inside the `src/` folder with the name `Handler`.In this folder we will place all our action classes. +In there, create a `Hello.php` file. + +```php +getAttribute('name', 'Stranger'); + $response = (new \Laminas\Diactoros\Response)->withStatus(200); + $response->getBody()->write('Hello ' . $name . '!'); + return $response; + } +} +``` + +You can see that we implement the [RequestHandlerInterface](https://github.com/php-fig/http-server-handler/blob/master/src/RequestHandlerInterface.php) +that has a 'handle'-Method with requires a Requestobject as its parameter and returns a Responseobject. For now this is +fine, but we may have to change our approach later. In anyway it is good to know about this interface as we will implement +it in some other parts of our application as well. In order to use that Interface we have to require it with composer: +'composer require psr/http-server-handler'. + +The autoloader will only work if the namespace of a class matches the file path and the file name equals the class name. +At the beginning I defined `Lubian\NoFramework` as the root namespace of the application so this is referring to the `src/` folder. + +Now let's change the hello world route so that it calls your new class method instead of the closure. Change your `routes.php` to this: + +```php +return function(\FastRoute\RouteCollector $r) { + $r->addRoute('GET', '/hello[/{name}]', \Lubian\NoFramework\Action\Hello::class); + $r->addRoute('GET', '/another-route', \Lubian\NoFramework\Action\Another::class); +}; +``` + +Instead of a callable we are now passing the fully namespaced class identifier to the route-definition. I also declared +the class 'Another' as the target for the second route, you can create it by copying the Hello.php file and changing +the response to the one we defined for the second route. + +To make this work, you will also have to do a small refactor to the routing part of the `Bootstrap.php`: + +```php +case \FastRoute\Dispatcher::FOUND: + $handler = new $routeInfo[1]; + if (! $handler instanceof \Psr\Http\Server\RequestHandlerInterface) { + throw new \Exception('Invalid Requesthandler'); + } + foreach ($routeInfo[2] as $attributeName => $attributeValue) { + $request = $request->withAttribute($attributeName, $attributeValue); + } + $response = $handler->handle($request); + assert($response instanceof \Psr\Http\Message\ResponseInterface) + break; +``` + +So instead of just calling a method you are now instantiating an object and then calling the method on it. + +Now if you visit `http://localhost:1234/` everything should work. If not, go back and debug. + +And of course don't forget to commit your changes. + +Something that still bothers me is the fact, that we do have classes for our Handlers, but the Error responses are still +generated in the routing-matching section and not in special classes. Also we have still left some cases to chance, for +example if there is an error in creating our RequestHandler class or if the call to the 'handle' function fails. We still +have our whoopsie error-handler but i like to be more explicit in my control flow. + +In order to do that we need to define some special Exceptions that we can throw and catch explicitly. Lets add a new +Folder/Namespace to our src directory called Exceptions. And define the classes NotFound, MethodNotAllowed and +InternalServerError. All three should extend phps Base Exception class. + +Here is my NotFound.php for example. + +```php + $attributeValue) { + $request = $request->withAttribute($attributeName, $attributeValue); + } + $response = $handler->handle($request); + break; + case Dispatcher::METHOD_NOT_ALLOWED: + throw new MethodNotAllowed; + + case Dispatcher::NOT_FOUND: + default: + throw new NotFound; + } +} catch (MethodNotAllowed) { + $response = (new Response)->withStatus(405); + $response->getBody()->write('Not Allowed'); +} catch (NotFound) { + $response = (new Response)->withStatus(404); + $response->getBody()->write('Not Found'); +} catch (Throwable $t) { + throw new InternalServerError($t->getMessage(), $t->getCode(), $t); +} +``` + +Check if our code still works, try to trigger some errors, run phpstan and the fix command +and don't forget to commit your changes. + +[<< previous](06-router.md) | [next >>](08-inversion-of-control.md) diff --git a/implementation/18-caching/data/pages/08-inversion-of-control.md b/implementation/18-caching/data/pages/08-inversion-of-control.md new file mode 100644 index 0000000..21f4f23 --- /dev/null +++ b/implementation/18-caching/data/pages/08-inversion-of-control.md @@ -0,0 +1,54 @@ +[<< previous](07-dispatching-to-a-class.md) | [next >>](09-dependency-injector.md) + +### Inversion of Control + +In the last part you have set up a controller class and generated our Http-Response-object in that class, but if we +want to switch to a more powerfull Http-Implementation later, or need to create our own for some special purposes, then +we would need to edit every one of our request handlers to call a different constructor of the class. + +The sane option is to use [inversion of control](http://en.wikipedia.org/wiki/Inversion_of_control). This means that +instead of giving the class the responsiblity of creating the object it needs, you just ask for them. This is done +with [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection). + +If this sounds a little complicated right now, don't worry. Just follow the tutorial and once you see how it is +implemented, it will make sense. + +Change your `Hello` action to the following: + +```php +getAttribute('name', 'Stranger'); + $body = $this->response->getBody(); + + $body->write('Hello ' . $name . '!'); + + return $this->response + ->withBody($body) + ->withStatus(200); + } +} +``` + +Now the code will result in an error because we are not actually injecting anything. So let's fix that in the `Bootstrap.php` where we dispatch when a route was found: + +```php +$handler = new $className($response); +``` + +Of course we need to also update all the other handlers. + +[<< previous](07-dispatching-to-a-class.md) | [next >>](09-dependency-injector.md) diff --git a/implementation/18-caching/data/pages/09-dependency-injector.md b/implementation/18-caching/data/pages/09-dependency-injector.md new file mode 100644 index 0000000..7f7c6a2 --- /dev/null +++ b/implementation/18-caching/data/pages/09-dependency-injector.md @@ -0,0 +1,213 @@ +[<< previous](08-inversion-of-control.md) | [next >>](10-invoker.md) + +### Dependency Injector + +A dependency injector resolves the dependencies of your class and makes sure that the correct objects are injected when +the class is instantiated. + +Again the psr has defined an [interface](https://www.php-fig.org/psr/psr-11/) for dependency injection that we can work +with. Almost all common dependency injection containers implement this interface, so it is a good starting point to look +for a [suitable solution on packagist](https://packagist.org/providers/psr/container-implementation). + +I choose the [PHP-DI](https://packagist.org/packages/php-di/php-di) container, as it is easy to configure and provides some very [powerfull features](https://php-di.org/#autowiring) +out of the box. + +After installing the container through composer create a new file with the name 'dependencies.php' in your config folder: + +```php +addDefinitions([ + \Psr\Http\Message\ResponseInterface::class => \DI\create(\Laminas\Diactoros\Response::class), + \Psr\Http\Message\ServerRequestInterface::class => fn () => \Laminas\Diactoros\ServerRequestFactory::fromGlobals(), +]); + +return $builder->build(); +``` + +In this file we create a containerbuilder, add some definitions to it and return the container. +As the container supports autowiring we only need to define services where we want to use a specific implementation of +an interface. + +In the example i used two different ways of defining the service. The first is by using the 'create' method of PHP-DI to +tell the container that it should create a Diactoros\Response object when ever I query a ResponseInterface, in the second +exampler I choose to write a small factory closure that wraps the Laminas Requestfactory. + +Make sure to read the documentation on definition types on the [PHP-DI website](https://php-di.org/doc/php-definitions.html#definition-types), +as we will use that extensively. + +Of course your `Bootstrap.php` will also need to be changed. Before you were setting up `$request` and `$response` with `new` calls. Switch that to the dependency container. We do not need to get the response here, as the container will create and use it internally +to create our Handler-Object + +```php +$container = require __DIR__ . '/../config/dependencies.php'; +assert($container instanceof \Psr\Container\ContainerInterface); + +$request = $container->get(\Psr\Http\Message\ServerRequestInterface::class); +assert($request instanceof \Psr\Http\Message\ServerRequestInterface); +``` + +The other part that has to be changed is the dispatching of the route. Before you had the following code: + +```php +$className = $routeInfo[1]; +$handler = new $className($response); +assert($handler instanceof \Psr\Http\Server\RequestHandlerInterface) +foreach ($routeInfo[2] as $attributeName => $attributeValue) { + $request = $request->withAttribute($attributeName, $attributeValue); +} +$response = $handler->handle($request); +``` + +Change that to the following: + +```php +/** @var RequestHandlerInterface $handler */ +$className = $routeInfo[1]; +$handler = $container->get($className); +assert($handler instanceof RequestHandlerInterface); +foreach ($routeInfo[2] as $attributeName => $attributeValue) { + $request = $request->withAttribute($attributeName, $attributeValue); +} +$response = $handler->handle($request); +``` + +Make sure to use the container fetch the response object in the catch blocks as well: + +```php +} catch (MethodNotAllowed) { + $response = $container->get(ResponseInterface::class); + assert($response instanceof ResponseInterface); + $response = $response->withStatus(405); + $response->getBody()->write('Not Allowed'); +} catch (NotFound) { + $response = $container->get(ResponseInterface::class); + assert($response instanceof ResponseInterface); + $response = $response->withStatus(404); + $response->getBody()->write('Not Found'); +} +``` + +Now all your controller constructor dependencies will be automatically resolved with PHP-DI. + +We can now use that to inject all kinds of services. Often we need to work with the Current time to do some comparisons +in an application. Of course we are writing S.O.L.I.D. and testable code so that we would never be so crazy as to call +`$time = new \DateTimeImmutable();` in our Action directly, because then we would need to change the system time of we +want to work with a different date in a test. + +Therefore we are creating a new Namespace called 'Service\Time' where we introduce a Now-Interface and an Implementation +that creates us a DateTimeImmutable object with the current date and time. + +src/Service/Time/Now.php: +```php +namespace Lubian\NoFramework\Service\Time; + +interface Now +{ + public function __invoke(): \DateTimeImmutable; +} +``` +src/Service/Time/SystemClockNow.php: +```php +namespace Lubian\NoFramework\Service\Time; + +final class SystemClockNow implements Now +{ + + public function __invoke(): \DateTimeImmutable + { + return new \DateTimeImmutable; + } +} +``` +If we want to use that Service in our HelloAction we just need to add it as another argument for the Constructor and +update the handle-method to use the new class property: + +```php +getAttribute('name', 'Stranger'); + $nowAsString = ($this->now)()->format('H:i:s'); + $body = $this->response->getBody(); + + $body->write('Hello ' . $name . '!'); + $body->write(' The Time is ' . $nowAsString); + + return $this->response + ->withBody($body) + ->withStatus(200); + } +} +``` + +If you open the route in your browser you should see that the current time gets displayed. This happens because PHP-DI +automatically figures out what classes are requested in the constructor and tries to create the objects needed. + +But we do not want to depend on the SystemClockNow implementation in our class because that would violate our sacred +S.O.L.I.D. principles therefore we need to change the Typehint to the Now interface: + +```php + public function __construct( + private ResponseInterface $response, + private Now $now, + ) +``` + +When we are now accessing the Handler in the Browser we get an Error because we have not defined which implementation +should be use to satisfy dependencies on the Now interface. So lets add that definition to our dependencies file: + +```php +\Lubian\NoFramework\Service\Time\Now::class => fn () => new \Lubian\NoFramework\Service\Time\SystemClockNow(), +``` + +we could also use the PHP-DI create method to delegate the object creation to the container implementation: +```php +\Lubian\NoFramework\Service\Time\Now::class => DI\create(\Lubian\NoFramework\Service\Time\SystemClockNow::class), +``` + +this way the container can try to resolve any dependencies that the class might have internally, but prefer the other +method because we are not depending on this specific dependency injection implementation. + +Either way the container should now be able to correctly resolve the dependency on the Now interfacen when you are +requesting the Hello action. + +If you run phpstan now, you will get some errors, because the get method on the ContainerInterface returns 'mixed'. As +we will adress these issues later, lets tell phpstan that we know about the issue and we can ignore it for now. This way +we wont get any warnings for this particular issue, but for any other issues we add to our code. + +Update the phpstan.neon file to include a "baseline" file: + +``` +includes: + - phpstan-baseline.neon + +parameters: + level: 9 + paths: + - src +``` + +if we run phpstan with './vendor/bin/phpstan analyse --generate-baseline' it will add all current errors to that file and +ignore them in the future. You can also add that command to your composer.json for easier access. I have called it just +'baseline' + +[<< previous](08-inversion-of-control.md) | [next >>](10-invoker.md) \ No newline at end of file diff --git a/implementation/18-caching/data/pages/10-invoker.md b/implementation/18-caching/data/pages/10-invoker.md new file mode 100644 index 0000000..3033fae --- /dev/null +++ b/implementation/18-caching/data/pages/10-invoker.md @@ -0,0 +1,102 @@ +[<< previous](09-dependency-injector.md) | [next >>](11-templating.md) + +### Invoker + +Currently all our Actions need to implement the RequestHandlerInterface, which forces us to accept the Request as the +one and only argument to our handle function, but most of the time we only need a few attributes in our Action a long +with some services and not the whole Requestobject with all its various properties. + +If we take our Hello action for example we only need a response object, the time service and the 'name' information from +the request-uri. And as that class only provides one simple method we could easily make that invokable as we alreay named +the class hello and it would be redundant to also call the the method hello. So an updated version of that class could +look like this: + +```php +final class Hello +{ + public function __invoke( + ResponseInterface $response, + Now $now, + string $name = 'Stranger', + ): ResponseInterface + { + $body = $this->response->getBody(); + $nowString = $now->get()->format('H:i:s'); + + $body->write('Hello ' . $name . '!'); + $body->write(' The Time is ' . $nowString); + return $response + ->withBody($body) + ->withStatus(200); + } +} +``` + +It would also be neat if we could define a classname plus a method as target handler in our routes, or even a short +closure function if we want to redirect all requests from '/' to '/hello' because we have not defined a handler for the +rootpath of our application yet. + +```php +$r->addRoute('GET', '/hello[/{name}]', Hello::class); +$r->addRoute('GET', '/other-route', [Other::class, 'someFunctionName']); +$r->addRoute('GET', '/', fn (Response $r) => $r->withStatus(302)->withHeader('Location', '/hello')); +``` + +In order to support this crazy route definitions we would need to write a lot of for actually calling the result of the +route dispatcher. If the result is a name of an invokable class we would use the container to create an instance of that +class for us and then use the [reflection api](https://www.php.net/manual/en/book.reflection.php) to figure out what +arguments the __invoke function has, try to fetch all arguments from the container and then add some more from the router +if they are needed and available. The same if we have an array of a class name with a function to call, and for a simple +callable we would need to manually use reflection as well to resolve all the arguments. + +But we are quite lucky as the PHP-DI container provides us with a [great 'call' method](https://php-di.org/doc/container.html#call) +which handles all of that for us. + +After you added the described changes to your routes file you can modify the Dispatcher::FOUND case of you $routeInfo +switch section in the Bootstrap.php file to use the container->call() method: + +```php +$handler = $routeInfo[1]; +$args = $routeInfo[2]; +foreach ($routeInfo[2] as $attributeName => $attributeValue) { + $request = $request->withAttribute($attributeName, $attributeValue); +} +$args['request'] = $request; +$response = $container->call($handler, $args); +``` + +Try to open [localhost:1234/](http://localhost:1234/) in your browser and check if you are getting redirected to '/hello'. + +But by now you should know that I do not like to depend on specific implementations and the call method is not defined in +the psr/container interface. Therefore we would not be able to use that if we are ever switching to the symfony container +or any other implementation. + +Fortunately for us (or me) the PHP-CI container ships that function as its own class that is independent of the specific +container implementation so we could use it with any container that implements the ContainerInterface. And best of all +the class ships with its own [Interface](https://github.com/PHP-DI/Invoker/blob/master/src/InvokerInterface.php) that +we could implement if we ever want to write our own implementation or we could write an adapter that uses a different +class that solves the same problem. + +But for now we are using the solution provided by PHP-DI. +So lets request a Service implementing the InvokerInterface from the container and use that inside of the switch-case block + +```php +$handler = $routeInfo[1]; +$args = $routeInfo[2] ?? []; +foreach ($routeInfo[2] as $attributeName => $attributeValue) { + $request = $request->withAttribute($attributeName, $attributeValue); +} +$args['request'] = $request; +$invoker = $container->get(InvokerInterface::class); +assert($invoker instanceof InvokerInterface); +$response = $invoker->call($handler, $args); +assert($response instanceof ResponseInterface); +``` + +Now we are able to define absolutely everything in routes that is considered a [callable](https://www.php.net/manual/de/language.types.callable.php) +by php, and even some more. + +But let us move on to something more fun and add some templating functionality to our application as we are trying to build +a website in the end. + +[<< previous](09-dependency-injector.md) | [next >>](11-templating.md) diff --git a/implementation/18-caching/data/pages/11-templating.md b/implementation/18-caching/data/pages/11-templating.md new file mode 100644 index 0000000..7bfe1aa --- /dev/null +++ b/implementation/18-caching/data/pages/11-templating.md @@ -0,0 +1,236 @@ +[<< previous](10-invoker.md) | [next >>](12-configuration.md) + +### Templating + +A template engine is not necessary with PHP because the language itself can take care of that. But it can make things +like escaping values easier. They also make it easier to draw a clear line between your application logic and the +template files which should only put your variables into the HTML code. + +A good quick read on this is [ircmaxell on templating](http://blog.ircmaxell.com/2012/12/on-templating.html). Please +also read [this](http://chadminick.com/articles/simple-php-template-engine.html) for a different opinion on the topic. +Personally I don't have a strong opinion on the topic, so decide yourself which approach works better for you. + +For this tutorial we will use a PHP implementation of [Mustache](https://github.com/bobthecow/mustache.php). So install +that package before you continue (`composer require mustache/mustache`). + +Another well known alternative would be [Twig](http://twig.sensiolabs.org/). + +Now please go and have a look at the source code of the +[engine class](https://github.com/bobthecow/mustache.php/blob/master/src/Mustache/Engine.php). As you can see, the class +does not implement an interface. + +You could just type hint against the concrete class. But the problem with this approach is that you create tight +coupling. + +In other words, all your code that uses the engine will be coupled to this mustache package. If you want to change the +implementation you have a problem. Maybe you want to switch to Twig, maybe you want to write your own class or you want +to add functionality to the engine. You can't do that without going back and changing all your code that is tightly +coupled. + +What we want is loose coupling. We will type hint against an interface and not a class/implementation. So if you need +another implementation, you just implement that interface in your new class and inject the new class instead. + +Instead of editing the code of the package we will use the [adapter pattern](http://en.wikipedia.org/wiki/Adapter_pattern). +This sounds a lot more complicated than it is, so just follow along. + +First let's define the interface that we want. Remember the [interface segregation principle](http://en.wikipedia.org/wiki/Interface_segregation_principle). +This means that instead of large interfaces with a lot of methods we want to make each interface as small as possible. +A class can implement multiple interfaces if necessary. + +So what does our template engine actually need to do? For now we really just need a simple `render` method. Create a +new folder in your `src/` folder with the name `Template` where you can put all the template related things. + +In there create a new interface `Renderer.php` that looks like this: + +```php + $data */ + public function render(string $template, array $data = []) : string; +} +``` + +Now that this is sorted out, let's create the implementation for mustache. In the same folder, create the file +`MustacheRenderer.php` with the following content: + +```php +engine->render($template, $data); + } +} +``` + +As you can see the adapter is really simple. While the original class had a lot of methods, our adapter is really simple +and only fulfills the interface. + +Of course we also have to add a definition in our `dependencies.php` file because otherwise the container won't know +which implementation he has to inject when you hint for the interface. Add this line: + +```php +[ + ... + \Lubian\NoFramework\Template\Renderer::class => DI\create(\Lubian\NoFramework\Template\MustacheRenderer::class) + ->constructor(new Mustache_Engine), +] +``` + +Now update the Hello.php class to require an implementation of our renderer interface +and use that to render a string using mustache syntax. + + +```php +final class Hello +{ + public function __invoke( + ResponseInterface $response, + Now $now, + Renderer $renderer, + string $name = 'Stranger', + ): ResponseInterface { + $body = $response->getBody(); + $data = [ + 'now' => $now()->format('H:i:s'), + 'name' => $name, + ]; + + $content = $renderer->render( + 'Hello {{name}}, the time is {{now}}!', + $data, + ); + + $body->write($content); + + return $response + ->withStatus(200) + ->withBody($body); + } +} +``` + +Now go check quickly in your browser if everything works. By default Mustache uses a simple string handler. +But what we want is template files, so let's go back and change that. + +To make this change we need to pass an options array to the `Mustache_Engine` constructor. So let's go back to the +`dependencies.php` file and add the following code: + +```php +[ + ... + Mustache_Loader_FilesystemLoader::class => fn() => new Mustache_Loader_FilesystemLoader(__DIR__ . '/../templates', ['extension' => '.html']), + Mustache_Engine::class => fn (Mustache_Loader_FilesystemLoader $MLFsl) => new Mustache_Engine(['loader' => $MLFsl]), +] +``` + +We are passing an options array because we want to use the `.html` extension instead of the default `.mustache` extension. +Why? Other template languages use a similar syntax and if we ever decide to change to something else then we won't have +to rename all the template files. + +To let PHP-DI use its magic for creating our MustacheRenderer class we need to tell it exactly how to wire all the +dependencies, therefore I defined how to create the Filesystemloader, on the next line we typehinted that loader +in the short closure which acts as a factory method for the Mustache_Engine, as PHP-DI automatically injects the Object +we can then use it in the factory. + +In your project root folder, create a `templates` folder. In there, create a file `hello.html`. The content of the file should look like this: + +``` +

Hello World

+Hello {{ name }} +``` + +Now you can go back to your `Hello` action and change the render line to `$html = $this->renderer->render('hello', $data);` + +Navigate to the hello page in your browser to make sure everything works. + +One thing that still bothers me is the fact that we have some configuration paths scattered in our dependencies +file. We could add a simple valueobject to our code that gives us a typesafe access to our configuration +values. + +Lets create a 'Settings' class in our './src' Folder: + +```php +addDefinitions([ + Settings::class => fn () => require __DIR__ '/settings.php', + ResponseInterface::class => create(Response::class), + ServerRequestInterface::class => fn () => ServerRequestFactory::fromGlobals(), + Renderer::class => fn (ME $me) => new Mustache($me), + MLFsl::class => fn (Settings $s) => new MLFsl($s->templateDir, ['extension' => $s->templateExtension]), + ME::class => fn (MLFsl $MLFsl) => new ME(['loader' => $MLFsl]), +]); + +return $builder->build(); +``` + + + +And as always, don't forget to commit your changes. + + +[<< previous](10-invoker.md) | [next >>](12-configuration.md) diff --git a/implementation/18-caching/data/pages/12-configuration.md b/implementation/18-caching/data/pages/12-configuration.md new file mode 100644 index 0000000..4b60c19 --- /dev/null +++ b/implementation/18-caching/data/pages/12-configuration.md @@ -0,0 +1,200 @@ +[<< previous](11-templating.md) | [next >>](13-refactoring.md) + +### Configuration + +In the last chapter we added some more definitions to our dependencies.php in that definitions +we needed to pass quite a few configuration settings and filesystem strings to the constructors +of the classes. This might work for a small projects, but if we are growing we want to source that out to a more explicit file that holds all the configuration valuse for our project. + +As this is not a problem unique to our project there are already a some options available. Some projects use [.env](https://github.com/vlucas/phpdotenv) files, others use [.ini](https://www.php.net/manual/de/function.parse-ini-file.php), there is [yaml](https://www.php.net/manual/de/function.yaml-parse-file.php) as well some frameworks have implemented complex Readers for many configuration file formats that can be used, take a look at the [laminas config component](https://docs.laminas.dev/laminas-config/reader/) for example. + +As i am a big fan of writing everything in php, which gives our IDE the chance to autocomplete our code better I am quite happy the PHP8 gives us some tools to achieve easy to use configuration via php. You can take a look at [this blogpost](https://stitcher.io/blog/what-about-config-builders) to read about some considerations on that topic before moving on. + +Lets create a 'Settings' class in our './src' Folder: + +```php +filePath; + } +} +``` + +If we later want to use yaml or ini files for our Settings we can easily write a different provider to read those files +and craft a settings object from them. + +As we have now created a completely new Namespace and Folder and our SettingsProvider is all alone we could add another +factory for our Container because everyone should have a Friend :) + +```php +settingsProvider->getSettings(); + $dependencies = require $settings->dependenciesFile; + $dependencies[Settings::class] = fn () => $settings; + $builder->addDefinitions($dependencies); + return $builder->build(); + } +} +``` + +For this to work we need to change our dependencies.php file to just return the array of definitions: +And here we can instantly use the Settings object to create our template engine. + +```php + fn (ResponseFactory $rf) => $rf->createResponse(), + ServerRequestInterface::class => fn (ServerRequestFactory $rf) => $rf::fromGlobals(), + Now::class => fn (SystemClockNow $n) => $n, + Renderer::class => fn (Mustache_Engine $e) => new MustacheRenderer($e), + MLF::class => fn (Settings $s) => new MLF($s->templateDir, ['extension' => $s->templateExtension]), + ME::class => fn (MLF $mfl) => new ME(['loader' => $mfl]), +]; +``` + +Now we can change our Bootstrap.php file to use the new Factories for the creation of the Initial Objects: + +```php +... +error_reporting(E_ALL); + +$settingsProvider = new FileSystemSettingsProvider(__DIR__ . '/../config/settings.php'); +$container = (new SettingsContainerProvider($settingsProvider))->getContainer(); + +$settings = $settingsProvider->getSettings(); + +$whoops = new Run; +if ($settings->environment === 'dev') { + $whoops->pushHandler(new PrettyPageHandler); +} else { + $whoops->pushHandler(function (Throwable $e): void { + error_log('Error: ' . $e->getMessage(), $e->getCode()); + echo 'An Error happened'; + }); +} +$whoops->register(); +... +``` + +Check if everything still works, run your code quality checks and commit the changes before moving on the the next chapter. + +[<< previous](11-templating.md) | [next >>](13-refactoring.md) diff --git a/implementation/18-caching/data/pages/13-refactoring.md b/implementation/18-caching/data/pages/13-refactoring.md new file mode 100644 index 0000000..6dbbb8d --- /dev/null +++ b/implementation/18-caching/data/pages/13-refactoring.md @@ -0,0 +1,373 @@ +[<< previous](12-configuration.md) | [next >>](14-middleware.md) + +### Refactoring + +By now our Bootstrap.php file has grown quite a bit, and with the addition of our dependency container there is now no +reason not to introduce a lot of classes and interfaces for all the that are happening in the bootstrap file. +After all the bootstrap file should just set up the classes needed for the handling logic and execute them. + +At the bottom of our Bootstrap.php we have our Response-Emitter Logic, lets create an Interface and a class for that. +As I am really lazy I just selected the code in PhpStorm, klicken on 'Refactor -> extract method' then selected the +method and clicked on 'Refactor -> extract class'. I choose 'BasicEmitter' for the classname, changed the method to non +static and extracted an interface. + +'./src/Http/Emitter.php' +```php +getHeaders() as $name => $values) { + $first = strtolower($name) !== 'set-cookie'; + foreach ($values as $value) { + $header = sprintf('%s: %s', $name, $value); + header($header, $first); + $first = false; + } + } + + $statusLine = sprintf( + 'HTTP/%s %s %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + ); + header($statusLine, true, $response->getStatusCode()); + + if ($withoutBody) { + return; + } + echo $response->getBody(); + } +} +``` +After registering the BasicEmitter to implement the Emitter interface in the dependencies file you can use the following +code in the Bootstrap.php to emit the response: + +```php +/** @var Emitter $emitter */ +$emitter = $container->get(Emitter::class); +$emitter->emit($response); +``` + +If at some point you need a [more advanced emitter](https://github.com/httpsoft/http-emitter), you could now easily +write an adapter that implements your emitter interface and wraps that more advanced emitter + +Now that we have our Emitter in a seperate class we need to take care of the big block that handles our routing and +calling the routerhandler that in the passes the request to a function and gets the response. + +For this to steps to be seperated we are going to create two more classes: +1. a RouteDecorator, that finds the correct handler for the requests and adds its findings to the Request Object +2. A Requesthandler that implements the RequestHandlerInterface, gets the information for the request handler from the + requestobject, fetches the correct object from the container and calls it to create a response. + +Lets create the HandlerInterface first: + +```php +getAttribute($this->routeAttributeName, false); + assert($handler !== false); + $vars = $request->getAttributes(); + $vars['request'] = $request; + $response = $this->invoker->call($handler, $vars); + if (! $response instanceof ResponseInterface) { + throw new InternalServerError('Handler returned invalid response'); + } + return $response; + } + + public function setRouteAttributeName(string $routeAttributeName = '__route_handler'): void + { + $this->routeAttributeName = $routeAttributeName; + } +} + +``` + +We will define our routing class to implement the MiddlewareInterface, you can install that with 'composer require psr/http-server-middleware'. +The interface requires us to implement a method called 'process' a Request as its first argument and an RequestHandler +as the second one. The return value of the method needs to be a Responseobject. We will learn more about Middlewares in +the next chapter. + +```php +dispatcher->dispatch( + $request->getMethod(), + $request->getUri()->getPath(), + ); + + if ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) { + throw new MethodNotAllowed; + } + + if ($routeInfo[0] === Dispatcher::FOUND) { + foreach ($routeInfo[2] as $attributeName => $attributeValue) { + $request = $request->withAttribute($attributeName, $attributeValue); + } + return $request->withAttribute( + $this->routeAttributeName, + $routeInfo[1] + ); + } + + throw new NotFound; + } + + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + try { + $request = $this->decorateRequest($request); + } catch (NotFound) { + $response = $this->responseFactory->createResponse(404); + $response->getBody()->write('Not Found'); + return $response; + } catch (MethodNotAllowed) { + return $this->responseFactory->createResponse(405); + } catch (Throwable $t) { + throw new InternalServerError($t->getMessage(), $t->getCode(), $t); + } + + if ($handler instanceof RoutedRequestHandler) { + $handler->setRouteAttributeName($this->routeAttributeName); + } + return $handler->handle($request); + } +} +``` + +Before we can use all the new services in our Bootstrap file we need to add the definitions to our container. +```php +[ + '...', + Emitter::class => fn (BasicEmitter $e) => $e, + RoutedRequestHandler::class => fn (InvokerRoutedHandler $h) => $h, + MiddlewareInterface::class => fn (RouteMiddleware $r) => $r, + Dispatcher::class => fn (Settings $s) => simpleDispatcher(require __DIR__ . '/routes.php'), + ResponseFactoryInterface::class => fn (ResponseFactory $rf) => $rf, +], +``` + +And then we can update our Bootstrap.php to fetch all the services and let them handle the request. + +```php +... +$routeMiddleWare = $container->get(MiddlewareInterface::class); +assert($routeMiddleWare instanceof MiddlewareInterface); +$handler = $container->get(RoutedRequestHandler::class); +assert($handler instanceof RequestHandlerInterface); +$emitter = $container->get(Emitter::class); +assert($emitter instanceof Emitter); + +$request = $container->get(ServerRequestInterface::class); +assert($request instanceof ServerRequestInterface); + +$response = $routeMiddleWare->process($request, $handler); +$emitter->emit($response); +``` +Now we have wrapped all the important parts in our Bootstrap.php into seperate classes, but it is still quite a lot of +code and also many calls the container (and i have to write way too many docblocks to that phpstan doenst yell at me). + +So we should just add another class that wraps all of our Request-Handling Classes into a clearly defined structure. + +I will follow symfonys example and call this class our kernel. Before i create that class i will recap what our class +should require to function properly. + +* A RequestFactory + We want our Kernel to be able to build the request itself +* An Emitter + Without an Emitter we will not be able to send the response to the client +* RouteMiddleware + To decore the request with the correct handler for the requested route +* RequestHandler + To delegate the request to the correct funtion that creates the response + +As the Psr ContainerInterface leaves us to much handiwork to easily create a Serverrequest I will extend that interface +to give us easier access to a requestobject and wrap the Diactorors RequestFactory in an Adapter that satisfies our +interface: + +```php +factory::fromGlobals(); + } + + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface + { + return $this->factory->createServerRequest($method, $uri, $serverParams); + } +} +``` + +For later shenanigans I will let our Kernel implement the RequestHandlerInterface, this is how my version looks now: + +```php +routeMiddleware->process($request, $this->handler); + } + + public function run(): void + { + $request = $this->requestFactory->fromGlobals(); + $response = $this->handle($request); + $this->emitter->emit($response); + } +} + +``` + +We can now replace everything after the ErrorHandler in our Bootstrap.php with these few lines + +```php +$app = $container->get(Kernel::class); +assert($app instanceof Kernel); + +$app->run(); +``` + +You might get some Errors here because the Container cannot resolve all the dependencies, try to fix those errors by looking +at the Whoops output and adding the needed definitions to the dependencies.php file. + +And as always, don't forget to commit your changes. + +[<< previous](12-configuration.md) | [next >>](14-middleware.md) diff --git a/implementation/18-caching/data/pages/14-middleware.md b/implementation/18-caching/data/pages/14-middleware.md new file mode 100644 index 0000000..81f82a5 --- /dev/null +++ b/implementation/18-caching/data/pages/14-middleware.md @@ -0,0 +1,303 @@ +[<< previous](12-refactoring.md) | [next >>](15-adding-content.md) + +### Middleware + +In the last chapter we wrote our RouterClass to implement the middleware interface, and in this chapter I want to explain +a bit more about what this interface does and why it is used in many applications. + +The Middlewares are basically a number of wrappers that stand between the client and your application. Each request gets +passed through all the middlewares, gets handled by our controllers and then the response gets passed back through all +the middlewars to the client/emitter. + +So every Middleware can modify the request before it goes on to the next middleware (and finally the handler) and the +response after it gets created by our handlers. + +So lets take a look at the middleware and the requesthandler interfaces + +```php +interface MiddlewareInterface +{ + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface; +} + +interface RequestHandlerInterface +{ + public function handle(ServerRequestInterface $request): ResponseInterface; +} +``` + +The RequestHandlerInterface gets only a request and returns a response, the MiddlewareInterface gets a request and a +requesthandler and returns a response. So the logical thing for the Middleware is to use the handler to produce the +response. + +But the middleware could just ignore the handler and produce a response on its own as the interface just requires us +to produce a response. + +A simple example for that would be a caching middleware. The basic idea is that we want to cache all request from users +that are not logged in. This way we can save a lot of processing power in rendering the html and fetching data from the +database. + +In this scenario we assume that we have an authentication middleware that checks if a user is logged in and decorates +the request with an 'isAuthenticated' attribute. + +If the 'isAuthenticated' attribute is set to false, we check if we have a cached response and return that, if that +response is not already cached, than we let the handler create the response and store that in the cache for a few +seconds + +```php +interface CacheInterface +{ + public function get(string $key, callable $resolver, int $ttl): mixed; +} +``` + +The first parameter is the identifier for the cache, the second is a callable that produces the value and the last one +defines the seconds that the cache should keep the item. If the cache doesnt have an item with the given key then it uses +the callable to produce the value and stores it for the time specified in ttl. + +so lets write our caching middleware: + +```php +final class CachingMiddleware implements MiddlewareInterface +{ + public function __construct(private CacheInterface $cache){} + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + if ($request->getAttribute('isAuthenticated', false) && $request->getMethod() === 'GET') { + $key = $request->getUri()->getPath(); + return $this->cache->get($key, fn() => $handler->handle($request), 10); + } + return $handler->handle($request); + } +} +``` + +we can also modify the response after it has been created by our application, for example we could implement a gzip +middleware, or for more simple and silly example a middleware that adds a Dank Meme header to all our response so that the browser +know that our application is used to serve dank memes: + +```php +final class DankMemeMiddleware implements MiddlewareInterface +{ + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + $response = $handler->handle($request); + return $response->withAddedHeader('Meme', 'Dank'); + } +} +``` + +but for our application we are going to just add two external middlewares: + +* [Trailing-slash](https://github.com/middlewares/trailing-slash) to remove the trailing slash from all routes. +* [whoops middleware](https://github.com/middlewares/whoops) to wrap our error handler into a nice middleware + +```bash +composer require middlewares/trailing-slash +composer require middlewares/whoops +``` + +The whoops middleware should be the first middleware to be executed so that we catch any errors that are thrown in the +application as well as the middleware stack. + +Our desired request -> response flow looks something like this: + + Client + | ^ + v | + Kernel + | ^ + v | + Whoops Middleware + | ^ + v | + TrailingSlash + | ^ + v | + Routing + | ^ + v | + ContainerResolver + | ^ + v | + Controller/Action + +As every middleware expects a RequestHandlerInterface as its second argument we need some extra code that wraps every +middleware as a RequestHandler and chains them together with the ContainerRouteDecoratedResolver as the last Handler. + +```php +interface Pipeline +{ + public function dispatch(ServerRequestInterface $request): ResponseInterface; +} +``` + +And our implementation looks something like this: + +```php + $middlewares + */ + public function __construct( + private array $middlewares, + private RequestHandlerInterface $tip, + private ContainerInterface $container, + ) { + } + + public function dispatch(ServerRequestInterface $request): ResponseInterface + { + $this->buildStack(); + return $this->tip->handle($request); + } + + private function buildStack(): void + { + foreach (array_reverse($this->middlewares) as $middleware) { + $next = $this->tip; + if ($middleware instanceof MiddlewareInterface) { + $this->tip = $this->wrapMiddleware($middleware, $next); + } + if (is_string($middleware)) { + $this->tip = $this->wrapResolvedMiddleware($middleware, $next); + } + } + } + + private function wrapResolvedMiddleware(string $middleware, RequestHandlerInterface $next): RequestHandlerInterface + { + return new class ($middleware, $next, $this->container) implements RequestHandlerInterface { + public function __construct( + private readonly string $middleware, + private readonly RequestHandlerInterface $handler, + private readonly ContainerInterface $container, + ) { + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + $middleware = $this->container->get($this->middleware); + assert($middleware instanceof MiddlewareInterface); + return $middleware->process($request, $this->handler); + } + }; + } + + private function wrapMiddleware(MiddlewareInterface $middleware, RequestHandlerInterface $next): RequestHandlerInterface + { + return new class ($middleware, $next) implements RequestHandlerInterface { + public function __construct( + private readonly MiddlewareInterface $middleware, + private readonly RequestHandlerInterface $handler, + ) { + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + return $this->middleware->process($request, $this->handler); + } + }; + } +} +``` + +Here we define our constructor to require two arguments: an array of middlewares and a requesthandler as the final code +that should produce our response. + +In the buildStack() method we wrap every middleware as a RequestHandler with the current tip property as the $next argument +and store that itself as the current tip. + +There are of course a lot of more sophisticated ways to build a pipeline/dispatcher that you can check out at the [middlewares github](https://github.com/middlewares/awesome-psr15-middlewares#dispatcher) + +Lets add a simple factory to our dependencies.php file that creates our middlewarepipeline +Lets create a simple Factory that loads an Array of Middlewares from the Config folder and uses that to build our pipeline + +```php +settings->middlewaresFile; + return new ContainerPipeline($middlewares, $this->tip, $this->container); + } +} +``` + +And configure the container to use the Factory to create the Pipeline: + +```php + ..., + Pipeline::class => fn (PipelineProvider $p) => $p->getPipeline(), + ... +``` +And of course a new file called middlewares.php in our config folder: +```php +pipeline->dispatch($request); +} +``` + +Lets try if you can make the kernel work with our created Pipeline implementation. For the future we could improve our +pipeline a little bit, so that it can accept a class-string of a middleware and resolves that with the help of a +dependency container, if you want you can do that as well. + +**A quick note about docblocks:** You might have noticed, that I rarely add docblocks to my the code in the examples, and +when I do it seems kind of random. My philosophy is that I only add docblocks when there is no way to automatically get +the exact type from the code itself. For me docblocks only serve two purposes: help my IDE to understand what it choices +it has for code completion and to help the static analysis to better understand the code. There is a great blogpost +about the [cost and value of DocBlocks](https://localheinz.com/blog/2018/05/06/cost-and-value-of-docblocks/), although it +is written in 2018 at a time before PHP 7.4 was around everything written there is still valid today. + +[<< previous](12-refactoring.md) | [next >>](15-adding-content.md) diff --git a/implementation/18-caching/data/pages/15-adding-content.md b/implementation/18-caching/data/pages/15-adding-content.md new file mode 100644 index 0000000..64562fa --- /dev/null +++ b/implementation/18-caching/data/pages/15-adding-content.md @@ -0,0 +1,253 @@ +[<< previous](14-middleware.md) | [next >>](16-data-repository.md) + +### Adding Content + +By now we did not really display anything but some examples to in our application and it is now time to make our app +display some content. For example we could our app be able to display the Markdown files used in this tutorial as +nicely rendered HTML Pages that can be viewed in the browser instead of the editor you are using. + +So lets start by copying the markdown files to our app directory. I have created a new folder 'data/pages' and placed all +the markdown files in there. + +Next we need a markdown parser, a pretty simple one is [Parsedown](https://parsedown.org/), if you want more features +you could also use the [Commonmark parser](https://commonmark.thephpleague.com/). I will choose Parsedown here, but you +can use whatever you like. + +After installing Parsedown lets write a Markdownparser interface and an implementation using parsedown. + +We only need one function that receives a string of Markdown and returns the HTML represantion (as a string as well). + + + +```php +parser->parse($markdown); + } +} +``` + +We could now use the ParsedownRender class directly in our actions by typehinting the classname as an argument to the +constructor or a method, but as we always want to rely on an interface instead of an implementation we need to define +the the ParsedownRenderer as the correct implementation for the MarkdownRenderer interface in the dependencies file: + +```php +... + \Lubian\NoFramework\Template\MarkdownParser::class => fn(\Lubian\NoFramework\Template\ParsedownParser $p) => $p, +... +``` + +You can test that in our "Other.php" action and try out if the Parser works and is able to render Markdown to HTML: + +```php +public function someFunctionName(ResponseInterface $response, MarkdownParser $parser): ResponseInterface +{ + $html = $parser->parse('This *works* **too!**'); + $response->getBody()->write($html); + return $response->withStatus(200); +} +``` + +But we want to display complete Pages written in Markdown, it would also be neat to be able to display a list of all +available pages. For that we need a few things: + +Firstly we need two new Templates, one for the list of the Pages, and the second one for displaying a single pages +content. Create a new folder in `templates/page` with to files: + +`templates/page/list.html` +```html + + + + + Pages + + + +
+ +
+ + +``` + +This template iterates over a provided array of pages, each element consists of the two properties: an id and a title, +those are simply displayed using an unordered list. + +`templates/page/show.html` +```html + + + + + {{title}} + + + + + + +
+ {{{content}}} +
+ + +``` + +The second templates displays a single rendered markdown page. As data it expects the title and the content as array. +I used an extra bracket for the content ```{{{content}}}``` so that the Mustache-Renderer does not escape the provided +html and thereby destroys the the parsed markdown. + +You might have spotted that I added [Pico.css](https://picocss.com/) which is just a very small css framework to make the +pages a little bit nicer to look at. It mostly provides some typography styles that work great with rendered Markdown, +but you can leave that out or use any other css framework you like. There is also some Javascript that adds syntax +highlighting to the code. + +After you have taken care of the templating side we can now create an new Action class with two methods to display use +our markdown files and the templates to create the pages. As we have two templates I propose to use Two methods in our +Action: +`src/Action/Page.php` +```php +function show(string $name): \Psr\Http\Message\ResponseInterface; +function list(): \Psr\Http\Message\ResponseInterface; +``` + +Lets define two routes. `/page` should display the overview of all pages, and if the add the name of chapter to the +route, `/page/adding-content` for example, the show action should be called with the name as a variable: + +`config/routes.php` +```php +$r->addRoute('GET', '/page', [Page::class, 'list']); +$r->addRoute('GET', '/page/{page}', [Page::class, 'show']); +``` + +Here is my Implementation. If have added a little regex replacement in the show method that replaces the links to the +next and previous chapter so that it works with our routing configuration. + +`src/Action/Page.php` +```php +getPages(), + fn (string $filename) => str_contains($filename, $page) + ) + )[0]; + $markdown = file_get_contents($page); + + // fix the next and previous buttons to work with our routing + $markdown = preg_replace('/\(\d\d-/m', '(', $markdown); + $markdown = str_replace('.md)', ')', $markdown); + + $page = str_replace([$this->pagesPath, '.md'], ['', ''], $page); + $data = [ + 'title' => substr($page, 3), + 'content' => $this->parser->parse($markdown), + ]; + $html = $this->renderer->render('page/show', $data); + $this->response->getBody()->write($html); + return $this->response; + } + + public function list(): ResponseInterface + { + $pages = array_map(function (string $page) { + $page = str_replace([$this->pagesPath, '.md'], ['', ''], $page); + return [ + 'id' => substr($page, 0, 2), + 'title' => substr($page, 3), + ]; + }, $this->getPages()); + $html = $this->renderer->render('page/list', ['pages' => $pages]); + $this->response->getBody()->write($html); + return $this->response; + } + + /** + * @return string[] + */ + private function getPages(): array + { + $files = glob($this->pagesPath . '*.md'); + if ($files === false) { + throw new InternalServerError('cannot read pages'); + } + return $files; + } +} +``` + +You can now navigate your Browser to [localhost:1234/page][http://localhost:1234/page] and try out if everything works. + +Of course this code is far from looking good. We heavily rely on the pages being files in the filesystem, and the action +should never be aware of the filesystem in the first place, also we have a lot of string replacements and other repetetive +code in the file. And phpstan is gonna scream at us a lot, but if we rewrite the code to satisfy all the checks we would +add even more lines to that simple class, so lets move on to the next chapter where we move all the logic to seperate +classes following our holy SOLID principles :) + + +[<< previous](14-middleware.md) | [next >>](16-data-repository.md) diff --git a/implementation/18-caching/data/pages/16-data-repository.md b/implementation/18-caching/data/pages/16-data-repository.md new file mode 100644 index 0000000..d9a3218 --- /dev/null +++ b/implementation/18-caching/data/pages/16-data-repository.md @@ -0,0 +1,265 @@ +[<< previous](15-adding-content.md) | [next >>](17-performance.md) + +## Data Repository + +At the end of the last chapter I mentioned being unhappy with our Pages action, because there is to much stuff happening +there. We are firstly receiving some Arguments, then we are using those to query the filesytem for the given page, +loading the specific file from the filesystem, rendering the markdown, passing the markdown to the template renderer, +adding the resulting html to the response and then returning the response. + +In order to make our pageaction independent from the filesystem and move the code that is responsible for reading the +files +to a better place I want to introduce +the [Repository Pattern](https://designpatternsphp.readthedocs.io/en/latest/More/Repository/README.html). + +I want to start by creating a class that represents the Data that is included in a page so that. For now I can spot +three +distrinct attributes. + +* the ID (or chapternumber) +* the title (or name) +* the content + +Currently all those properties are always available, but we might later be able to create new pages and store them, but +at that point in time we are not yet aware of the new available ID, so we should leave that property nullable. This +allows +us to create an object without an id and let the code that actually saves the object to a persistant store define a +valid +id on saving. + +Lets create an new Namespace called `Model` and put a `MarkdownPage.php` class in there: + +```php +dataPath . '*.md'); + if ($files === false) { + throw new InternalServerError('cannot read pages'); + } + return array_map(function (string $filename) { + $content = file_get_contents($filename); + if ($content === false) { + throw new InternalServerError('cannot read pages'); + } + $idAndTitle = str_replace([$this->dataPath, '.md'], ['', ''], $filename); + return new MarkdownPage( + (int) substr($idAndTitle, 0, 2), + substr($idAndTitle, 3), + $content + ); + }, $files); + } + + public function byName(string $name): MarkdownPage + { + $pages = array_values( + array_filter( + $this->all(), + fn (MarkdownPage $p) => $p->title === $name, + ) + ); + + if (count($pages) !== 1) { + throw new NotFound; + } + + return $pages[0]; + } +} +``` + +With that in place we need to add the required `$pagesPath` to our settings class and add specify that in our +configuration. + +`src/Settings.php` + +```php +final class Settings +{ + public function __construct( + public readonly string $environment, + public readonly string $dependenciesFile, + public readonly string $middlewaresFile, + public readonly string $templateDir, + public readonly string $templateExtension, + public readonly string $pagesPath, + ) { + } +} +``` + +`config/settings.php` + +```php +return new Settings( + environment: 'prod', + dependenciesFile: __DIR__ . '/dependencies.php', + middlewaresFile: __DIR__ . '/middlewares.php', + templateDir: __DIR__ . '/../templates', + templateExtension: '.html', + pagesPath: __DIR__ . '/../data/pages/', +); +``` + +Of course we need to define the correct implementation for the container to choose when we are requesting the Repository +interface: +`conf/dependencies.php` + +```php +MarkdownPageRepo::class => fn (FileSystemMarkdownPageRepo $r) => $r, +FileSystemMarkdownPageRepo::class => fn (Settings $s) => new FileSystemMarkdownPageRepo($s->pagesPath), +``` + +Now you can request the MarkdownPageRepo Interface in your page action and use the defined functions to get the +MarkdownPage +Objects. My `src/Action/Page.php` looks like this now: + +```php +repo->byName($page); + + // fix the next and previous buttons to work with our routing + $content = preg_replace('/\(\d\d-/m', '(', $page->content); + assert(is_string($content)); + $content = str_replace('.md)', ')', $content); + + $data = [ + 'title' => $page->title, + 'content' => $this->parser->parse($content), + ]; + + $html = $this->renderer->render('page/show', $data); + $this->response->getBody()->write($html); + return $this->response; + } + + public function list(): ResponseInterface + { + $pages = array_map(function (MarkdownPage $page) { + return [ + 'id' => $page->id, + 'title' => $page->content, + ]; + }, $this->repo->all()); + + $html = $this->renderer->render('page/list', ['pages' => $pages]); + $this->response->getBody()->write($html); + return $this->response; + } +} +``` + +Check the page in your browser if everything still works, don't forget to run phpstan and the others fixers before +committing your changes and moving on to the next chapter. + +[<< previous](15-adding-content.md) | [next >>](17-performance.md) diff --git a/implementation/18-caching/data/pages/17-performance.md b/implementation/18-caching/data/pages/17-performance.md new file mode 100644 index 0000000..c83c7d5 --- /dev/null +++ b/implementation/18-caching/data/pages/17-performance.md @@ -0,0 +1,43 @@ +[<< previous](16-data-repository.md) | [next >>](18-caching.md) + +## Autoloading performance + +Although our application is still very small and you should not really experience any performance issues right now, +there are still some things we can already consider and take a look at. If I check the network tab in my browser it takes +about 90-400ms to show a simple rendered markdownpage, with is sort of ok but in my opinion way to long as we are not +really doing anything and do not connect to any external services. Mostly we are just reading around 16 markdown files, +a template, some config files here and there and parse some markdown. So that should not really take that long. + +The problem is, that we heavily rely on autoloading for all our class files, in the `src` folder. And there are also +quite a lot of other files in composers `vendor` directory. To understand while this is becomming we should make +ourselves familiar with how [autoloading in php](https://www.php.net/manual/en/language.oop5.autoload.php) works. + +The basic idea is, that every class that php encounters has to be loaded from somewhere in the filesystem, we could +just require the files manually but that is tedious, unflexible and can often cause errors. + +The problem we are now facing is that the composer autoloader has some rules to determine from where in the filesystem +a class definition might be placed, then the autoloader tries to locate a file by the namespace and classname and if it +exists includes that file. + +If we only have a handfull of classes that does not take a lot of time, but as we are growing with our application this +easily takes longer than necesery, but fortunately composer has some options to speed up the class loading. + +Take a few minutes to read the documentation about [composer autoloader optimization](https://getcomposer.org/doc/articles/autoloader-optimization.md) + +You can try all 3 levels of optimizations, but we are going to stick with the first one for now, so lets create an +optimized classmap. + +`composer dump-autoload -o` + +After composer has finished you can start the devserver again with `composer serve` and take a look at the network tab +in your browsers devtools. + +In my case the response time falls down to under an average of 30ms with some spikes in between, but all in all it looks really good. +You can also try out the different optimization levels and see if you can spot any differences. + +Although the composer manual states not to use the optimtization in a dev environment I personally have not encountered +any errors with the first level of optimizations, so we can use that level here. If you add the line from the documentation +to your `composer.json` so that the autoloader gets optimized everytime we install new packages. + + +[<< previous](16-data-repository.md) | [next >>](18-caching.md) diff --git a/implementation/18-caching/data/pages/18-caching.md b/implementation/18-caching/data/pages/18-caching.md new file mode 100644 index 0000000..42e9cb1 --- /dev/null +++ b/implementation/18-caching/data/pages/18-caching.md @@ -0,0 +1,252 @@ +[<< previous](17-performance.md) | [next >>](19-database.md) + +**DISClAIMER** I do not really have a lot of experience when it comes to caching, so this chapter is mostly some random +thoughts and ideas I wanted to explore when writing this tutorial, you should definitely take everything that is being +said here with caution and try to read up on some other sources. But that holds true for the whole tutorial anyway :) + +## Caching + +In the last chapter we greatly improved the perfomance for the lookup of all our classfiles, but currently we do not +have any real bottlenecks in our application like complex queries. + +But in a real application we are going to execute some really heavy and time intensive database queries that can take +quite a while to be completed. + +We can simulate that by adding a simple delay in our `FileSystemMarkdownPageRepo`. + +```php + return array_map(function (string $filename) { + usleep(rand(100, 400) * 1000); + $content = file_get_contents($filename); + if ($content === false) { + throw new InternalServerError('cannot read pages'); + } + $idAndTitle = str_replace([$this->dataPath, '.md'], ['', ''], $filename); + return new MarkdownPage( + (int) substr($idAndTitle, 0, 2), + substr($idAndTitle, 3), + $content + ); +}); +``` + +Here I added a function that pauses the scripts execution for a random time between 100 and 400ms for every markdownpage +in every call of the `all()` method. + +If you open any page or even the listAction in you browser you will see, that it takes quite a time to render that page. +Although this is a silly example we do not really need to query the database on every request, so lets add a way to cache +the database results between requests. + +The PHP-Community has already adressed the issue of having easy to use access to cache libraries, there is the +[PSR-6 Caching Interface](https://www.php-fig.org/psr/psr-6) which gives us easy access to many different implementations, +then there is also a much simpler [PSR-16 Simple Cache](https://www.php-fig.org/psr/psr-16) which makes the use even more +easy, and most Caching Libraries implement Both interfaces anyway. You would think that this is more than enough solutions +to satisfy all the Caching needs around, but the Symfony People decided that Caching should be even simpler and easier +to use and defined their own [Interface](https://symfony.com/doc/current/components/cache.html#cache-component-contracts) +which only needs two methods. You should definitely take a look at the linked documentation as it really blew my mind +when I first encountered it. + +The basic idea is that you provide a callback that computes the requested value. The Cache implementation then checks +if it already has the value stored somewhere and if it doesnt it just executes the callback and stores the value for +future calls. + +It is really simple and great to use. In a real world application you should definitely use that or a PSR-16 implementation +but for this tutorial I wanted to roll out my own solution, so here we go. + +As always we are going to define an interface first, I am going to call it EasyCache and place it in the `Service/Cache` +namespace. I will require only one method which is base on the Symfony Cache Contract, and hast a key, a callback, and +the duration that the item should be cached as arguments. + +```php +cache->get( + $key, + fn () => $this->repo->all(), + 300 + ); + } + + public function byName(string $name): MarkdownPage + { + $key = base64_encode(self::class . 'byName' . $name); + return $this->cache->get( + $key, + fn () => $this->repo->byName($name), + 300 + ); + } +} +``` + +This simple wrapper just requires an EasyCache implementation and a MarkdownPageRepo in the constructor and uses them +to cache all queries for 5 minutes. The beauty is that we are not dependent on any implementation here, so we can switch +out the Repository or the Cache at any point down the road if we want to. + +In order to use that we need to update our `config/dependencies.php` to add an alias for the EasyCache interface as well +as defining our CachedMarkdownPageRepo as implementation for the MarkdownPageRepo interface: + +```php +MarkdownPageRepo::class => fn (CachedMarkdownPageRepo $r) => $r, +EasyCache::class => fn (ApcuCache $c) => $c, +``` + +If we try to access our webpage now, we are getting an error, as PHP-DI has detected a circular dependency that cannot +be autowired. + +The Problem is that our CachedMarkdownPageRepo ist defined as the implementation for the MarkdownPageRepo, but it also +requires that exact interface as a dependency. To resolve this issue we need to manually tell the container how to build +the CachedMarkdownPageRepo by adding another line to the `config/dependencies.php` file: + +```php +CachedMarkdownPageRepo::class => fn (EasyCache $c, FileSystemMarkdownPageRepo $r) => new CachedMarkdownPageRepo($c, $r), +``` + +Here we explicitly require the FileSystemMarkdownPageRepo and us that to create the CachedMarkdownPageRepo object. + +When you now navigate to the pages list or to a specific page the first load should take a while (because of our added delay) +but the following request should be answered blazingly fast. + +Before moving on to the next chapter we can take the caching approach even further, in the middleware chapter I talked +about a simple CachingMiddleware that caches all the GET-Request for some seconds, as they should not change that often, +and we can bypass most of our application logic if we just complelety cache away the responses our application generates, +and return them quite early in our Middleware-Pipeline befor the router gets called, or the invoker calls the action, +which itself uses some other services to fetch all the needed data. + +We will introduce a new `Middleware` namespace to place our `Cache.php` middleware: +```php +getMethod() !== 'GET') { + return $handler->handle($request); + } + $keyHash = base64_encode($request->getUri()->getPath()); + $result = $this->cache->get( + $keyHash, + fn () => Serializer::toString($handler->handle($request)), + 300 + ); + return Serializer::fromString($result); + } +} +``` + +The code is quite straight forward, but you might be confused by the Responseserializer I have added here, we need this +because the response body is a stream object, which doesnt always gets serialized correctly, therefore I use a class from +the laminas project to to all the heavy lifting for us. + +We need to add the now middleware to the `config/middlewares.php` file. + +```php +>](19-database.md) diff --git a/implementation/18-caching/phpstan-baseline.neon b/implementation/18-caching/phpstan-baseline.neon new file mode 100644 index 0000000..61697a1 --- /dev/null +++ b/implementation/18-caching/phpstan-baseline.neon @@ -0,0 +1,7 @@ +parameters: + ignoreErrors: + - + message: "#^Parameter \\#1 \\$callable of method Invoker\\\\InvokerInterface\\:\\:call\\(\\) expects array\\|\\(callable\\(\\)\\: mixed\\)\\|string, mixed given\\.$#" + count: 1 + path: src/Http/InvokerRoutedHandler.php + diff --git a/implementation/18-caching/phpstan.neon b/implementation/18-caching/phpstan.neon new file mode 100644 index 0000000..2eac45a --- /dev/null +++ b/implementation/18-caching/phpstan.neon @@ -0,0 +1,8 @@ +includes: + - phpstan-baseline.neon + +parameters: + level: max + paths: + - src + - config \ No newline at end of file diff --git a/implementation/18-caching/public/css/spectre-exp.min.css b/implementation/18-caching/public/css/spectre-exp.min.css new file mode 100644 index 0000000..d313774 --- /dev/null +++ b/implementation/18-caching/public/css/spectre-exp.min.css @@ -0,0 +1 @@ +/*! Spectre.css Experimentals v0.5.9 | MIT License | github.com/picturepan2/spectre */.form-autocomplete{position:relative}.form-autocomplete .form-autocomplete-input{align-content:flex-start;display:-ms-flexbox;display:flex;-ms-flex-line-pack:start;-ms-flex-wrap:wrap;flex-wrap:wrap;height:auto;min-height:1.6rem;padding:.1rem}.form-autocomplete .form-autocomplete-input.is-focused{border-color:#5755d9;box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.form-autocomplete .form-autocomplete-input .form-input{border-color:transparent;box-shadow:none;display:inline-block;-ms-flex:1 0 auto;flex:1 0 auto;height:1.2rem;line-height:.8rem;margin:.1rem;width:auto}.form-autocomplete .menu{left:0;position:absolute;top:100%;width:100%}.form-autocomplete.autocomplete-oneline .form-autocomplete-input{-ms-flex-wrap:nowrap;flex-wrap:nowrap;overflow-x:auto}.form-autocomplete.autocomplete-oneline .chip{-ms-flex:1 0 auto;flex:1 0 auto}.calendar{border:.05rem solid #dadee4;border-radius:.1rem;display:block;min-width:280px}.calendar .calendar-nav{align-items:center;background:#f7f8f9;border-top-left-radius:.1rem;border-top-right-radius:.1rem;display:-ms-flexbox;display:flex;-ms-flex-align:center;font-size:.9rem;padding:.4rem}.calendar .calendar-body,.calendar .calendar-header{display:-ms-flexbox;display:flex;-ms-flex-pack:center;-ms-flex-wrap:wrap;flex-wrap:wrap;justify-content:center;padding:.4rem 0}.calendar .calendar-body .calendar-date,.calendar .calendar-header .calendar-date{-ms-flex:0 0 14.28%;flex:0 0 14.28%;max-width:14.28%}.calendar .calendar-header{background:#f7f8f9;border-bottom:.05rem solid #dadee4;color:#bcc3ce;font-size:.7rem;text-align:center}.calendar .calendar-body{color:#66758c}.calendar .calendar-date{border:0;padding:.2rem}.calendar .calendar-date .date-item{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:0 0;border:.05rem solid transparent;border-radius:50%;color:#66758c;cursor:pointer;font-size:.7rem;height:1.4rem;line-height:1rem;outline:0;padding:.1rem;position:relative;text-align:center;text-decoration:none;transition:background .2s,border .2s,box-shadow .2s,color .2s;vertical-align:middle;white-space:nowrap;width:1.4rem}.calendar .calendar-date .date-item.date-today{border-color:#e5e5f9;color:#5755d9}.calendar .calendar-date .date-item:focus{box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.calendar .calendar-date .date-item:focus,.calendar .calendar-date .date-item:hover{background:#fefeff;border-color:#e5e5f9;color:#5755d9;text-decoration:none}.calendar .calendar-date .date-item.active,.calendar .calendar-date .date-item:active{background:#4b48d6;border-color:#3634d2;color:#fff}.calendar .calendar-date .date-item.badge::after{position:absolute;right:3px;top:3px;transform:translate(50%,-50%)}.calendar .calendar-date .calendar-event.disabled,.calendar .calendar-date .calendar-event:disabled,.calendar .calendar-date .date-item.disabled,.calendar .calendar-date .date-item:disabled{cursor:default;opacity:.25;pointer-events:none}.calendar .calendar-date.next-month .calendar-event,.calendar .calendar-date.next-month .date-item,.calendar .calendar-date.prev-month .calendar-event,.calendar .calendar-date.prev-month .date-item{opacity:.25}.calendar .calendar-range{position:relative}.calendar .calendar-range::before{background:#f1f1fc;content:"";height:1.4rem;left:0;position:absolute;right:0;top:50%;transform:translateY(-50%)}.calendar .calendar-range.range-start::before{left:50%}.calendar .calendar-range.range-end::before{right:50%}.calendar .calendar-range.range-end .date-item,.calendar .calendar-range.range-start .date-item{background:#4b48d6;border-color:#3634d2;color:#fff}.calendar .calendar-range .date-item{color:#5755d9}.calendar.calendar-lg .calendar-body{padding:0}.calendar.calendar-lg .calendar-body .calendar-date{border-bottom:.05rem solid #dadee4;border-right:.05rem solid #dadee4;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;height:5.5rem;padding:0}.calendar.calendar-lg .calendar-body .calendar-date:nth-child(7n){border-right:0}.calendar.calendar-lg .calendar-body .calendar-date:nth-last-child(-n+7){border-bottom:0}.calendar.calendar-lg .date-item{align-self:flex-end;-ms-flex-item-align:end;height:1.4rem;margin-right:.2rem;margin-top:.2rem}.calendar.calendar-lg .calendar-range::before{top:19px}.calendar.calendar-lg .calendar-range.range-start::before{left:auto;width:19px}.calendar.calendar-lg .calendar-range.range-end::before{right:19px}.calendar.calendar-lg .calendar-events{flex-grow:1;-ms-flex-positive:1;line-height:1;overflow-y:auto;padding:.2rem}.calendar.calendar-lg .calendar-event{border-radius:.1rem;display:block;font-size:.7rem;margin:.1rem auto;overflow:hidden;padding:3px 4px;text-overflow:ellipsis;white-space:nowrap}.carousel .carousel-locator:nth-of-type(1):checked~.carousel-container .carousel-item:nth-of-type(1),.carousel .carousel-locator:nth-of-type(2):checked~.carousel-container .carousel-item:nth-of-type(2),.carousel .carousel-locator:nth-of-type(3):checked~.carousel-container .carousel-item:nth-of-type(3),.carousel .carousel-locator:nth-of-type(4):checked~.carousel-container .carousel-item:nth-of-type(4),.carousel .carousel-locator:nth-of-type(5):checked~.carousel-container .carousel-item:nth-of-type(5),.carousel .carousel-locator:nth-of-type(6):checked~.carousel-container .carousel-item:nth-of-type(6),.carousel .carousel-locator:nth-of-type(7):checked~.carousel-container .carousel-item:nth-of-type(7),.carousel .carousel-locator:nth-of-type(8):checked~.carousel-container .carousel-item:nth-of-type(8){animation:carousel-slidein .75s ease-in-out 1;opacity:1;z-index:100}.carousel .carousel-locator:nth-of-type(1):checked~.carousel-nav .nav-item:nth-of-type(1),.carousel .carousel-locator:nth-of-type(2):checked~.carousel-nav .nav-item:nth-of-type(2),.carousel .carousel-locator:nth-of-type(3):checked~.carousel-nav .nav-item:nth-of-type(3),.carousel .carousel-locator:nth-of-type(4):checked~.carousel-nav .nav-item:nth-of-type(4),.carousel .carousel-locator:nth-of-type(5):checked~.carousel-nav .nav-item:nth-of-type(5),.carousel .carousel-locator:nth-of-type(6):checked~.carousel-nav .nav-item:nth-of-type(6),.carousel .carousel-locator:nth-of-type(7):checked~.carousel-nav .nav-item:nth-of-type(7),.carousel .carousel-locator:nth-of-type(8):checked~.carousel-nav .nav-item:nth-of-type(8){color:#f7f8f9}.carousel{background:#f7f8f9;display:block;overflow:hidden;-webkit-overflow-scrolling:touch;position:relative;width:100%;z-index:1}.carousel .carousel-container{height:100%;left:0;position:relative}.carousel .carousel-container::before{content:"";display:block;padding-bottom:56.25%}.carousel .carousel-container .carousel-item{animation:carousel-slideout 1s ease-in-out 1;height:100%;left:0;margin:0;opacity:0;position:absolute;top:0;width:100%}.carousel .carousel-container .carousel-item:hover .item-next,.carousel .carousel-container .carousel-item:hover .item-prev{opacity:1}.carousel .carousel-container .item-next,.carousel .carousel-container .item-prev{background:rgba(247,248,249,.25);border-color:rgba(247,248,249,.5);color:#f7f8f9;opacity:0;position:absolute;top:50%;transform:translateY(-50%);transition:all .4s;z-index:100}.carousel .carousel-container .item-prev{left:1rem}.carousel .carousel-container .item-next{right:1rem}.carousel .carousel-nav{bottom:.4rem;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;left:50%;position:absolute;transform:translateX(-50%);width:10rem;z-index:100}.carousel .carousel-nav .nav-item{color:rgba(247,248,249,.5);display:block;-ms-flex:1 0 auto;flex:1 0 auto;height:1.6rem;margin:.2rem;max-width:2.5rem;position:relative}.carousel .carousel-nav .nav-item::before{background:currentColor;content:"";display:block;height:.1rem;position:absolute;top:.5rem;width:100%}@keyframes carousel-slidein{0%{transform:translateX(100%)}100%{transform:translateX(0)}}@keyframes carousel-slideout{0%{opacity:1;transform:translateX(0)}100%{opacity:1;transform:translateX(-50%)}}.comparison-slider{height:50vh;overflow:hidden;-webkit-overflow-scrolling:touch;position:relative;width:100%}.comparison-slider .comparison-after,.comparison-slider .comparison-before{height:100%;left:0;margin:0;overflow:hidden;position:absolute;top:0}.comparison-slider .comparison-after img,.comparison-slider .comparison-before img{height:100%;object-fit:cover;object-position:left center;position:absolute;width:100%}.comparison-slider .comparison-before{width:100%;z-index:1}.comparison-slider .comparison-before .comparison-label{right:.8rem}.comparison-slider .comparison-after{max-width:100%;min-width:0;z-index:2}.comparison-slider .comparison-after::before{background:0 0;content:"";cursor:default;height:100%;left:0;position:absolute;right:.8rem;top:0;z-index:1}.comparison-slider .comparison-after::after{background:currentColor;border-radius:50%;box-shadow:0 -5px,0 5px;color:#fff;content:"";height:3px;pointer-events:none;position:absolute;right:.4rem;top:50%;transform:translate(50%,-50%);width:3px}.comparison-slider .comparison-after .comparison-label{left:.8rem}.comparison-slider .comparison-resizer{animation:first-run 1.5s 1 ease-in-out;cursor:ew-resize;height:.8rem;left:0;max-width:100%;min-width:.8rem;opacity:0;outline:0;position:relative;resize:horizontal;top:50%;transform:translateY(-50%) scaleY(30);width:0}.comparison-slider .comparison-label{background:rgba(48,55,66,.5);bottom:.8rem;color:#fff;padding:.2rem .4rem;position:absolute;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}@keyframes first-run{0%{width:0}25%{width:2.4rem}50%{width:.8rem}75%{width:1.2rem}100%{width:0}}.filter .filter-tag#tag-0:checked~.filter-nav .chip[for=tag-0],.filter .filter-tag#tag-1:checked~.filter-nav .chip[for=tag-1],.filter .filter-tag#tag-2:checked~.filter-nav .chip[for=tag-2],.filter .filter-tag#tag-3:checked~.filter-nav .chip[for=tag-3],.filter .filter-tag#tag-4:checked~.filter-nav .chip[for=tag-4],.filter .filter-tag#tag-5:checked~.filter-nav .chip[for=tag-5],.filter .filter-tag#tag-6:checked~.filter-nav .chip[for=tag-6],.filter .filter-tag#tag-7:checked~.filter-nav .chip[for=tag-7],.filter .filter-tag#tag-8:checked~.filter-nav .chip[for=tag-8]{background:#5755d9;color:#fff}.filter .filter-tag#tag-1:checked~.filter-body .filter-item:not([data-tag~=tag-1]),.filter .filter-tag#tag-2:checked~.filter-body .filter-item:not([data-tag~=tag-2]),.filter .filter-tag#tag-3:checked~.filter-body .filter-item:not([data-tag~=tag-3]),.filter .filter-tag#tag-4:checked~.filter-body .filter-item:not([data-tag~=tag-4]),.filter .filter-tag#tag-5:checked~.filter-body .filter-item:not([data-tag~=tag-5]),.filter .filter-tag#tag-6:checked~.filter-body .filter-item:not([data-tag~=tag-6]),.filter .filter-tag#tag-7:checked~.filter-body .filter-item:not([data-tag~=tag-7]),.filter .filter-tag#tag-8:checked~.filter-body .filter-item:not([data-tag~=tag-8]){display:none}.filter .filter-nav{margin:.4rem 0}.filter .filter-body{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap}.meter{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:#f7f8f9;border:0;border-radius:.1rem;display:block;height:.8rem;width:100%}.meter::-webkit-meter-inner-element{display:block}.meter::-webkit-meter-bar,.meter::-webkit-meter-even-less-good-value,.meter::-webkit-meter-optimum-value,.meter::-webkit-meter-suboptimum-value{border-radius:.1rem}.meter::-webkit-meter-bar{background:#f7f8f9}.meter::-webkit-meter-optimum-value{background:#32b643}.meter::-webkit-meter-suboptimum-value{background:#ffb700}.meter::-webkit-meter-even-less-good-value{background:#e85600}.meter:-moz-meter-optimum,.meter:-moz-meter-sub-optimum,.meter:-moz-meter-sub-sub-optimum,.meter::-moz-meter-bar{border-radius:.1rem}.meter:-moz-meter-optimum::-moz-meter-bar{background:#32b643}.meter:-moz-meter-sub-optimum::-moz-meter-bar{background:#ffb700}.meter:-moz-meter-sub-sub-optimum::-moz-meter-bar{background:#e85600}.off-canvas{display:-ms-flexbox;display:flex;-ms-flex-flow:nowrap;flex-flow:nowrap;height:100%;position:relative;width:100%}.off-canvas .off-canvas-toggle{display:block;left:.4rem;position:absolute;top:.4rem;transition:none;z-index:1}.off-canvas .off-canvas-sidebar{background:#f7f8f9;bottom:0;left:0;min-width:10rem;overflow-y:auto;position:fixed;top:0;transform:translateX(-100%);transition:transform .25s;z-index:200}.off-canvas .off-canvas-content{-ms-flex:1 1 auto;flex:1 1 auto;height:100%;padding:.4rem .4rem .4rem 4rem}.off-canvas .off-canvas-overlay{background:rgba(48,55,66,.1);border-color:transparent;border-radius:0;bottom:0;display:none;height:100%;left:0;position:fixed;right:0;top:0;width:100%}.off-canvas .off-canvas-sidebar.active,.off-canvas .off-canvas-sidebar:target{transform:translateX(0)}.off-canvas .off-canvas-sidebar.active~.off-canvas-overlay,.off-canvas .off-canvas-sidebar:target~.off-canvas-overlay{display:block;z-index:100}@media (min-width:960px){.off-canvas.off-canvas-sidebar-show .off-canvas-toggle{display:none}.off-canvas.off-canvas-sidebar-show .off-canvas-sidebar{-ms-flex:0 0 auto;flex:0 0 auto;position:relative;transform:none}.off-canvas.off-canvas-sidebar-show .off-canvas-overlay{display:none!important}}.parallax{display:block;height:auto;position:relative;width:auto}.parallax .parallax-content{box-shadow:0 1rem 2.1rem rgba(48,55,66,.3);height:auto;transform:perspective(1000px);transform-style:preserve-3d;transition:all .4s ease;width:100%}.parallax .parallax-content::before{content:"";display:block;height:100%;left:0;position:absolute;top:0;width:100%}.parallax .parallax-front{align-items:center;color:#fff;display:-ms-flexbox;display:flex;-ms-flex-align:center;-ms-flex-pack:center;height:100%;justify-content:center;left:0;position:absolute;text-align:center;text-shadow:0 0 20px rgba(48,55,66,.75);top:0;transform:translateZ(50px) scale(.95);transition:transform .4s;width:100%;z-index:1}.parallax .parallax-top-left{height:50%;left:0;outline:0;position:absolute;top:0;width:50%;z-index:100}.parallax .parallax-top-left:focus~.parallax-content,.parallax .parallax-top-left:hover~.parallax-content{transform:perspective(1000px) rotateX(3deg) rotateY(-3deg)}.parallax .parallax-top-left:focus~.parallax-content::before,.parallax .parallax-top-left:hover~.parallax-content::before{background:linear-gradient(135deg,rgba(255,255,255,.35) 0,transparent 50%)}.parallax .parallax-top-left:focus~.parallax-content .parallax-front,.parallax .parallax-top-left:hover~.parallax-content .parallax-front{transform:translate3d(4.5px,4.5px,50px) scale(.95)}.parallax .parallax-top-right{height:50%;outline:0;position:absolute;right:0;top:0;width:50%;z-index:100}.parallax .parallax-top-right:focus~.parallax-content,.parallax .parallax-top-right:hover~.parallax-content{transform:perspective(1000px) rotateX(3deg) rotateY(3deg)}.parallax .parallax-top-right:focus~.parallax-content::before,.parallax .parallax-top-right:hover~.parallax-content::before{background:linear-gradient(-135deg,rgba(255,255,255,.35) 0,transparent 50%)}.parallax .parallax-top-right:focus~.parallax-content .parallax-front,.parallax .parallax-top-right:hover~.parallax-content .parallax-front{transform:translate3d(-4.5px,4.5px,50px) scale(.95)}.parallax .parallax-bottom-left{bottom:0;height:50%;left:0;outline:0;position:absolute;width:50%;z-index:100}.parallax .parallax-bottom-left:focus~.parallax-content,.parallax .parallax-bottom-left:hover~.parallax-content{transform:perspective(1000px) rotateX(-3deg) rotateY(-3deg)}.parallax .parallax-bottom-left:focus~.parallax-content::before,.parallax .parallax-bottom-left:hover~.parallax-content::before{background:linear-gradient(45deg,rgba(255,255,255,.35) 0,transparent 50%)}.parallax .parallax-bottom-left:focus~.parallax-content .parallax-front,.parallax .parallax-bottom-left:hover~.parallax-content .parallax-front{transform:translate3d(4.5px,-4.5px,50px) scale(.95)}.parallax .parallax-bottom-right{bottom:0;height:50%;outline:0;position:absolute;right:0;width:50%;z-index:100}.parallax .parallax-bottom-right:focus~.parallax-content,.parallax .parallax-bottom-right:hover~.parallax-content{transform:perspective(1000px) rotateX(-3deg) rotateY(3deg)}.parallax .parallax-bottom-right:focus~.parallax-content::before,.parallax .parallax-bottom-right:hover~.parallax-content::before{background:linear-gradient(-45deg,rgba(255,255,255,.35) 0,transparent 50%)}.parallax .parallax-bottom-right:focus~.parallax-content .parallax-front,.parallax .parallax-bottom-right:hover~.parallax-content .parallax-front{transform:translate3d(-4.5px,-4.5px,50px) scale(.95)}.progress{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:#eef0f3;border:0;border-radius:.1rem;color:#5755d9;height:.2rem;position:relative;width:100%}.progress::-webkit-progress-bar{background:0 0;border-radius:.1rem}.progress::-webkit-progress-value{background:#5755d9;border-radius:.1rem}.progress::-moz-progress-bar{background:#5755d9;border-radius:.1rem}.progress:indeterminate{animation:progress-indeterminate 1.5s linear infinite;background:#eef0f3 linear-gradient(to right,#5755d9 30%,#eef0f3 30%) top left/150% 150% no-repeat}.progress:indeterminate::-moz-progress-bar{background:0 0}@keyframes progress-indeterminate{0%{background-position:200% 0}100%{background-position:-200% 0}}.slider{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:0 0;display:block;height:1.2rem;width:100%}.slider:focus{box-shadow:0 0 0 .1rem rgba(87,85,217,.2);outline:0}.slider.tooltip:not([data-tooltip])::after{content:attr(value)}.slider::-webkit-slider-thumb{-webkit-appearance:none;background:#5755d9;border:0;border-radius:50%;height:.6rem;margin-top:-.25rem;-webkit-transition:transform .2s;transition:transform .2s;width:.6rem}.slider::-moz-range-thumb{background:#5755d9;border:0;border-radius:50%;height:.6rem;-moz-transition:transform .2s;transition:transform .2s;width:.6rem}.slider::-ms-thumb{background:#5755d9;border:0;border-radius:50%;height:.6rem;-ms-transition:transform .2s;transition:transform .2s;width:.6rem}.slider:active::-webkit-slider-thumb{transform:scale(1.25)}.slider:active::-moz-range-thumb{transform:scale(1.25)}.slider:active::-ms-thumb{transform:scale(1.25)}.slider.disabled::-webkit-slider-thumb,.slider:disabled::-webkit-slider-thumb{background:#f7f8f9;transform:scale(1)}.slider.disabled::-moz-range-thumb,.slider:disabled::-moz-range-thumb{background:#f7f8f9;transform:scale(1)}.slider.disabled::-ms-thumb,.slider:disabled::-ms-thumb{background:#f7f8f9;transform:scale(1)}.slider::-webkit-slider-runnable-track{background:#eef0f3;border-radius:.1rem;height:.1rem;width:100%}.slider::-moz-range-track{background:#eef0f3;border-radius:.1rem;height:.1rem;width:100%}.slider::-ms-track{background:#eef0f3;border-radius:.1rem;height:.1rem;width:100%}.slider::-ms-fill-lower{background:#5755d9}.timeline .timeline-item{display:-ms-flexbox;display:flex;margin-bottom:1.2rem;position:relative}.timeline .timeline-item::before{background:#dadee4;content:"";height:100%;left:11px;position:absolute;top:1.2rem;width:2px}.timeline .timeline-item .timeline-left{-ms-flex:0 0 auto;flex:0 0 auto}.timeline .timeline-item .timeline-content{-ms-flex:1 1 auto;flex:1 1 auto;padding:2px 0 2px .8rem}.timeline .timeline-item .timeline-icon{align-items:center;border-radius:50%;color:#fff;display:-ms-flexbox;display:flex;-ms-flex-align:center;-ms-flex-pack:center;height:1.2rem;justify-content:center;text-align:center;width:1.2rem}.timeline .timeline-item .timeline-icon::before{border:.1rem solid #5755d9;border-radius:50%;content:"";display:block;height:.4rem;left:.4rem;position:absolute;top:.4rem;width:.4rem}.timeline .timeline-item .timeline-icon.icon-lg{background:#5755d9;line-height:1.2rem}.timeline .timeline-item .timeline-icon.icon-lg::before{content:none}.viewer-360{align-items:center;display:-ms-flexbox;display:flex;-ms-flex-align:center;-ms-flex-direction:column;flex-direction:column}.viewer-360 .viewer-slider[max="36"][value="1"]+.viewer-image{background-position-y:0}.viewer-360 .viewer-slider[max="36"][value="2"]+.viewer-image{background-position-y:2.8571428571%}.viewer-360 .viewer-slider[max="36"][value="3"]+.viewer-image{background-position-y:5.7142857143%}.viewer-360 .viewer-slider[max="36"][value="4"]+.viewer-image{background-position-y:8.5714285714%}.viewer-360 .viewer-slider[max="36"][value="5"]+.viewer-image{background-position-y:11.4285714286%}.viewer-360 .viewer-slider[max="36"][value="6"]+.viewer-image{background-position-y:14.2857142857%}.viewer-360 .viewer-slider[max="36"][value="7"]+.viewer-image{background-position-y:17.1428571429%}.viewer-360 .viewer-slider[max="36"][value="8"]+.viewer-image{background-position-y:20%}.viewer-360 .viewer-slider[max="36"][value="9"]+.viewer-image{background-position-y:22.8571428571%}.viewer-360 .viewer-slider[max="36"][value="10"]+.viewer-image{background-position-y:25.7142857143%}.viewer-360 .viewer-slider[max="36"][value="11"]+.viewer-image{background-position-y:28.5714285714%}.viewer-360 .viewer-slider[max="36"][value="12"]+.viewer-image{background-position-y:31.4285714286%}.viewer-360 .viewer-slider[max="36"][value="13"]+.viewer-image{background-position-y:34.2857142857%}.viewer-360 .viewer-slider[max="36"][value="14"]+.viewer-image{background-position-y:37.1428571429%}.viewer-360 .viewer-slider[max="36"][value="15"]+.viewer-image{background-position-y:40%}.viewer-360 .viewer-slider[max="36"][value="16"]+.viewer-image{background-position-y:42.8571428571%}.viewer-360 .viewer-slider[max="36"][value="17"]+.viewer-image{background-position-y:45.7142857143%}.viewer-360 .viewer-slider[max="36"][value="18"]+.viewer-image{background-position-y:48.5714285714%}.viewer-360 .viewer-slider[max="36"][value="19"]+.viewer-image{background-position-y:51.4285714286%}.viewer-360 .viewer-slider[max="36"][value="20"]+.viewer-image{background-position-y:54.2857142857%}.viewer-360 .viewer-slider[max="36"][value="21"]+.viewer-image{background-position-y:57.1428571429%}.viewer-360 .viewer-slider[max="36"][value="22"]+.viewer-image{background-position-y:60%}.viewer-360 .viewer-slider[max="36"][value="23"]+.viewer-image{background-position-y:62.8571428571%}.viewer-360 .viewer-slider[max="36"][value="24"]+.viewer-image{background-position-y:65.7142857143%}.viewer-360 .viewer-slider[max="36"][value="25"]+.viewer-image{background-position-y:68.5714285714%}.viewer-360 .viewer-slider[max="36"][value="26"]+.viewer-image{background-position-y:71.4285714286%}.viewer-360 .viewer-slider[max="36"][value="27"]+.viewer-image{background-position-y:74.2857142857%}.viewer-360 .viewer-slider[max="36"][value="28"]+.viewer-image{background-position-y:77.1428571429%}.viewer-360 .viewer-slider[max="36"][value="29"]+.viewer-image{background-position-y:80%}.viewer-360 .viewer-slider[max="36"][value="30"]+.viewer-image{background-position-y:82.8571428571%}.viewer-360 .viewer-slider[max="36"][value="31"]+.viewer-image{background-position-y:85.7142857143%}.viewer-360 .viewer-slider[max="36"][value="32"]+.viewer-image{background-position-y:88.5714285714%}.viewer-360 .viewer-slider[max="36"][value="33"]+.viewer-image{background-position-y:91.4285714286%}.viewer-360 .viewer-slider[max="36"][value="34"]+.viewer-image{background-position-y:94.2857142857%}.viewer-360 .viewer-slider[max="36"][value="35"]+.viewer-image{background-position-y:97.1428571429%}.viewer-360 .viewer-slider[max="36"][value="36"]+.viewer-image{background-position-y:100%}.viewer-360 .viewer-slider{cursor:ew-resize;-ms-flex-order:2;margin:1rem;order:2;width:60%}.viewer-360 .viewer-image{background-position-y:0;background-repeat:no-repeat;background-size:100%;-ms-flex-order:1;max-width:100%;order:1} \ No newline at end of file diff --git a/implementation/18-caching/public/css/spectre-icons.min.css b/implementation/18-caching/public/css/spectre-icons.min.css new file mode 100644 index 0000000..0276f7b --- /dev/null +++ b/implementation/18-caching/public/css/spectre-icons.min.css @@ -0,0 +1 @@ +/*! Spectre.css Icons v0.5.9 | MIT License | github.com/picturepan2/spectre */.icon{box-sizing:border-box;display:inline-block;font-size:inherit;font-style:normal;height:1em;position:relative;text-indent:-9999px;vertical-align:middle;width:1em}.icon::after,.icon::before{content:"";display:block;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%)}.icon.icon-2x{font-size:1.6rem}.icon.icon-3x{font-size:2.4rem}.icon.icon-4x{font-size:3.2rem}.accordion .icon,.btn .icon,.menu .icon,.toast .icon{vertical-align:-10%}.btn-lg .icon{vertical-align:-15%}.icon-arrow-down::before,.icon-arrow-left::before,.icon-arrow-right::before,.icon-arrow-up::before,.icon-back::before,.icon-downward::before,.icon-forward::before,.icon-upward::before{border:.1rem solid currentColor;border-bottom:0;border-right:0;height:.65em;width:.65em}.icon-arrow-down::before{transform:translate(-50%,-75%) rotate(225deg)}.icon-arrow-left::before{transform:translate(-25%,-50%) rotate(-45deg)}.icon-arrow-right::before{transform:translate(-75%,-50%) rotate(135deg)}.icon-arrow-up::before{transform:translate(-50%,-25%) rotate(45deg)}.icon-back::after,.icon-forward::after{background:currentColor;height:.1rem;width:.8em}.icon-downward::after,.icon-upward::after{background:currentColor;height:.8em;width:.1rem}.icon-back::after{left:55%}.icon-back::before{transform:translate(-50%,-50%) rotate(-45deg)}.icon-downward::after{top:45%}.icon-downward::before{transform:translate(-50%,-50%) rotate(-135deg)}.icon-forward::after{left:45%}.icon-forward::before{transform:translate(-50%,-50%) rotate(135deg)}.icon-upward::after{top:55%}.icon-upward::before{transform:translate(-50%,-50%) rotate(45deg)}.icon-caret::before{border-left:.3em solid transparent;border-right:.3em solid transparent;border-top:.3em solid currentColor;height:0;transform:translate(-50%,-25%);width:0}.icon-menu::before{background:currentColor;box-shadow:0 -.35em,0 .35em;height:.1rem;width:100%}.icon-apps::before{background:currentColor;box-shadow:-.35em -.35em,-.35em 0,-.35em .35em,0 -.35em,0 .35em,.35em -.35em,.35em 0,.35em .35em;height:3px;width:3px}.icon-resize-horiz::after,.icon-resize-horiz::before,.icon-resize-vert::after,.icon-resize-vert::before{border:.1rem solid currentColor;border-bottom:0;border-right:0;height:.45em;width:.45em}.icon-resize-horiz::before,.icon-resize-vert::before{transform:translate(-50%,-90%) rotate(45deg)}.icon-resize-horiz::after,.icon-resize-vert::after{transform:translate(-50%,-10%) rotate(225deg)}.icon-resize-horiz::before{transform:translate(-90%,-50%) rotate(-45deg)}.icon-resize-horiz::after{transform:translate(-10%,-50%) rotate(135deg)}.icon-more-horiz::before,.icon-more-vert::before{background:currentColor;border-radius:50%;box-shadow:-.4em 0,.4em 0;height:3px;width:3px}.icon-more-vert::before{box-shadow:0 -.4em,0 .4em}.icon-cross::before,.icon-minus::before,.icon-plus::before{background:currentColor;height:.1rem;width:100%}.icon-cross::after,.icon-plus::after{background:currentColor;height:100%;width:.1rem}.icon-cross::before{width:100%}.icon-cross::after{height:100%}.icon-cross::after,.icon-cross::before{transform:translate(-50%,-50%) rotate(45deg)}.icon-check::before{border:.1rem solid currentColor;border-right:0;border-top:0;height:.5em;transform:translate(-50%,-75%) rotate(-45deg);width:.9em}.icon-stop{border:.1rem solid currentColor;border-radius:50%}.icon-stop::before{background:currentColor;height:.1rem;transform:translate(-50%,-50%) rotate(45deg);width:1em}.icon-shutdown{border:.1rem solid currentColor;border-radius:50%;border-top-color:transparent}.icon-shutdown::before{background:currentColor;content:"";height:.5em;top:.1em;width:.1rem}.icon-refresh::before{border:.1rem solid currentColor;border-radius:50%;border-right-color:transparent;height:1em;width:1em}.icon-refresh::after{border:.2em solid currentColor;border-left-color:transparent;border-top-color:transparent;height:0;left:80%;top:20%;width:0}.icon-search::before{border:.1rem solid currentColor;border-radius:50%;height:.75em;left:5%;top:5%;transform:translate(0,0) rotate(45deg);width:.75em}.icon-search::after{background:currentColor;height:.1rem;left:80%;top:80%;transform:translate(-50%,-50%) rotate(45deg);width:.4em}.icon-edit::before{border:.1rem solid currentColor;height:.4em;transform:translate(-40%,-60%) rotate(-45deg);width:.85em}.icon-edit::after{border:.15em solid currentColor;border-right-color:transparent;border-top-color:transparent;height:0;left:5%;top:95%;transform:translate(0,-100%);width:0}.icon-delete::before{border:.1rem solid currentColor;border-bottom-left-radius:.1rem;border-bottom-right-radius:.1rem;border-top:0;height:.75em;top:60%;width:.75em}.icon-delete::after{background:currentColor;box-shadow:-.25em .2em,.25em .2em;height:.1rem;top:.05rem;width:.5em}.icon-share{border:.1rem solid currentColor;border-radius:.1rem;border-right:0;border-top:0}.icon-share::before{border:.1rem solid currentColor;border-left:0;border-top:0;height:.4em;left:100%;top:.25em;transform:translate(-125%,-50%) rotate(-45deg);width:.4em}.icon-share::after{border:.1rem solid currentColor;border-bottom:0;border-radius:75% 0;border-right:0;height:.5em;width:.6em}.icon-flag::before{background:currentColor;height:1em;left:15%;width:.1rem}.icon-flag::after{border:.1rem solid currentColor;border-bottom-right-radius:.1rem;border-left:0;border-top-right-radius:.1rem;height:.65em;left:60%;top:35%;width:.8em}.icon-bookmark::before{border:.1rem solid currentColor;border-bottom:0;border-top-left-radius:.1rem;border-top-right-radius:.1rem;height:.9em;width:.8em}.icon-bookmark::after{border:.1rem solid currentColor;border-bottom:0;border-left:0;border-radius:.1rem;height:.5em;transform:translate(-50%,35%) rotate(-45deg) skew(15deg,15deg);width:.5em}.icon-download,.icon-upload{border-bottom:.1rem solid currentColor}.icon-download::before,.icon-upload::before{border:.1rem solid currentColor;border-bottom:0;border-right:0;height:.5em;transform:translate(-50%,-60%) rotate(-135deg);width:.5em}.icon-download::after,.icon-upload::after{background:currentColor;height:.6em;top:40%;width:.1rem}.icon-upload::before{transform:translate(-50%,-60%) rotate(45deg)}.icon-upload::after{top:50%}.icon-copy::before{border:.1rem solid currentColor;border-bottom:0;border-radius:.1rem;border-right:0;height:.8em;left:40%;top:35%;width:.8em}.icon-copy::after{border:.1rem solid currentColor;border-radius:.1rem;height:.8em;left:60%;top:60%;width:.8em}.icon-time{border:.1rem solid currentColor;border-radius:50%}.icon-time::before{background:currentColor;height:.4em;transform:translate(-50%,-75%);width:.1rem}.icon-time::after{background:currentColor;height:.3em;transform:translate(-50%,-75%) rotate(90deg);transform-origin:50% 90%;width:.1rem}.icon-mail::before{border:.1rem solid currentColor;border-radius:.1rem;height:.8em;width:1em}.icon-mail::after{border:.1rem solid currentColor;border-right:0;border-top:0;height:.5em;transform:translate(-50%,-90%) rotate(-45deg) skew(10deg,10deg);width:.5em}.icon-people::before{border:.1rem solid currentColor;border-radius:50%;height:.45em;top:25%;width:.45em}.icon-people::after{border:.1rem solid currentColor;border-radius:50% 50% 0 0;height:.4em;top:75%;width:.9em}.icon-message{border:.1rem solid currentColor;border-bottom:0;border-radius:.1rem;border-right:0}.icon-message::before{border:.1rem solid currentColor;border-bottom-right-radius:.1rem;border-left:0;border-top:0;height:.8em;left:65%;top:40%;width:.7em}.icon-message::after{background:currentColor;border-radius:.1rem;height:.3em;left:10%;top:100%;transform:translate(0,-90%) rotate(45deg);width:.1rem}.icon-photo{border:.1rem solid currentColor;border-radius:.1rem}.icon-photo::before{border:.1rem solid currentColor;border-radius:50%;height:.25em;left:35%;top:35%;width:.25em}.icon-photo::after{border:.1rem solid currentColor;border-bottom:0;border-left:0;height:.5em;left:60%;transform:translate(-50%,25%) rotate(-45deg);width:.5em}.icon-link::after,.icon-link::before{border:.1rem solid currentColor;border-radius:5em 0 0 5em;border-right:0;height:.5em;width:.75em}.icon-link::before{transform:translate(-70%,-45%) rotate(-45deg)}.icon-link::after{transform:translate(-30%,-55%) rotate(135deg)}.icon-location::before{border:.1rem solid currentColor;border-radius:50% 50% 50% 0;height:.8em;transform:translate(-50%,-60%) rotate(-45deg);width:.8em}.icon-location::after{border:.1rem solid currentColor;border-radius:50%;height:.2em;transform:translate(-50%,-80%);width:.2em}.icon-emoji{border:.1rem solid currentColor;border-radius:50%}.icon-emoji::before{border-radius:50%;box-shadow:-.17em -.1em,.17em -.1em;height:.15em;width:.15em}.icon-emoji::after{border:.1rem solid currentColor;border-bottom-color:transparent;border-radius:50%;border-right-color:transparent;height:.5em;transform:translate(-50%,-40%) rotate(-135deg);width:.5em} \ No newline at end of file diff --git a/implementation/18-caching/public/css/spectre.min.css b/implementation/18-caching/public/css/spectre.min.css new file mode 100644 index 0000000..0fe23d9 --- /dev/null +++ b/implementation/18-caching/public/css/spectre.min.css @@ -0,0 +1 @@ +/*! Spectre.css v0.5.9 | MIT License | github.com/picturepan2/spectre */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,footer,header,nav,section{display:block}h1{font-size:2em;margin:.67em 0}figcaption,figure,main{display:block}hr{box-sizing:content-box;height:0;overflow:visible}a{background-color:transparent;-webkit-text-decoration-skip:objects}a:active,a:hover{outline-width:0}address{font-style:normal}b,strong{font-weight:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:"SF Mono","Segoe UI Mono","Roboto Mono",Menlo,Courier,monospace;font-size:1em}dfn{font-style:italic}small{font-size:80%;font-weight:400}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}audio,video{display:inline-block}audio:not([controls]){display:none;height:0}img{border-style:none}svg:not(:root){overflow:hidden}button,input,optgroup,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}fieldset{border:0;margin:0;padding:0}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{display:inline-block;vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details,menu{display:block}summary{display:list-item;outline:0}canvas{display:inline-block}template{display:none}[hidden]{display:none}*,::after,::before{box-sizing:inherit}html{box-sizing:border-box;font-size:20px;line-height:1.5;-webkit-tap-highlight-color:transparent}body{background:#fff;color:#3b4351;font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",sans-serif;font-size:.8rem;overflow-x:hidden;text-rendering:optimizeLegibility}a{color:#5755d9;outline:0;text-decoration:none}a:focus{box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}a.active,a:active,a:focus,a:hover{color:#302ecd;text-decoration:underline}a:visited{color:#807fe2}h1,h2,h3,h4,h5,h6{color:inherit;font-weight:500;line-height:1.2;margin-bottom:.5em;margin-top:0}.h1,.h2,.h3,.h4,.h5,.h6{font-weight:500}.h1,h1{font-size:2rem}.h2,h2{font-size:1.6rem}.h3,h3{font-size:1.4rem}.h4,h4{font-size:1.2rem}.h5,h5{font-size:1rem}.h6,h6{font-size:.8rem}p{margin:0 0 1.2rem}a,ins,u{-webkit-text-decoration-skip:ink edges;text-decoration-skip:ink edges}abbr[title]{border-bottom:.05rem dotted;cursor:help;text-decoration:none}kbd{background:#303742;border-radius:.1rem;color:#fff;font-size:.7rem;line-height:1.25;padding:.1rem .2rem}mark{background:#ffe9b3;border-bottom:.05rem solid #ffd367;border-radius:.1rem;color:#3b4351;padding:.05rem .1rem 0}blockquote{border-left:.1rem solid #dadee4;margin-left:0;padding:.4rem .8rem}blockquote p:last-child{margin-bottom:0}ol,ul{margin:.8rem 0 .8rem .8rem;padding:0}ol ol,ol ul,ul ol,ul ul{margin:.8rem 0 .8rem .8rem}ol li,ul li{margin-top:.4rem}ul{list-style:disc inside}ul ul{list-style-type:circle}ol{list-style:decimal inside}ol ol{list-style-type:lower-alpha}dl dt{font-weight:700}dl dd{margin:.4rem 0 .8rem 0}.lang-zh,.lang-zh-hans,html:lang(zh),html:lang(zh-Hans){font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Helvetica Neue",sans-serif}.lang-zh-hant,html:lang(zh-Hant){font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang TC","Hiragino Sans CNS","Microsoft JhengHei","Helvetica Neue",sans-serif}.lang-ja,html:lang(ja){font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Hiragino Sans","Hiragino Kaku Gothic Pro","Yu Gothic",YuGothic,Meiryo,"Helvetica Neue",sans-serif}.lang-ko,html:lang(ko){font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Malgun Gothic","Helvetica Neue",sans-serif}.lang-cjk ins,.lang-cjk u,:lang(ja) ins,:lang(ja) u,:lang(zh) ins,:lang(zh) u{border-bottom:.05rem solid;text-decoration:none}.lang-cjk del+del,.lang-cjk del+s,.lang-cjk ins+ins,.lang-cjk ins+u,.lang-cjk s+del,.lang-cjk s+s,.lang-cjk u+ins,.lang-cjk u+u,:lang(ja) del+del,:lang(ja) del+s,:lang(ja) ins+ins,:lang(ja) ins+u,:lang(ja) s+del,:lang(ja) s+s,:lang(ja) u+ins,:lang(ja) u+u,:lang(zh) del+del,:lang(zh) del+s,:lang(zh) ins+ins,:lang(zh) ins+u,:lang(zh) s+del,:lang(zh) s+s,:lang(zh) u+ins,:lang(zh) u+u{margin-left:.125em}.table{border-collapse:collapse;border-spacing:0;text-align:left;width:100%}.table.table-striped tbody tr:nth-of-type(odd){background:#f7f8f9}.table tbody tr.active,.table.table-striped tbody tr.active{background:#eef0f3}.table.table-hover tbody tr:hover{background:#eef0f3}.table.table-scroll{display:block;overflow-x:auto;padding-bottom:.75rem;white-space:nowrap}.table td,.table th{border-bottom:.05rem solid #dadee4;padding:.6rem .4rem}.table th{border-bottom-width:.1rem}.btn{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:#fff;border:.05rem solid #5755d9;border-radius:.1rem;color:#5755d9;cursor:pointer;display:inline-block;font-size:.8rem;height:1.8rem;line-height:1.2rem;outline:0;padding:.25rem .4rem;text-align:center;text-decoration:none;transition:background .2s,border .2s,box-shadow .2s,color .2s;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;vertical-align:middle;white-space:nowrap}.btn:focus{box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.btn:focus,.btn:hover{background:#f1f1fc;border-color:#4b48d6;text-decoration:none}.btn.active,.btn:active{background:#4b48d6;border-color:#3634d2;color:#fff;text-decoration:none}.btn.active.loading::after,.btn:active.loading::after{border-bottom-color:#fff;border-left-color:#fff}.btn.disabled,.btn:disabled,.btn[disabled]{cursor:default;opacity:.5;pointer-events:none}.btn.btn-primary{background:#5755d9;border-color:#4b48d6;color:#fff}.btn.btn-primary:focus,.btn.btn-primary:hover{background:#4240d4;border-color:#3634d2;color:#fff}.btn.btn-primary.active,.btn.btn-primary:active{background:#3a38d2;border-color:#302ecd;color:#fff}.btn.btn-primary.loading::after{border-bottom-color:#fff;border-left-color:#fff}.btn.btn-success{background:#32b643;border-color:#2faa3f;color:#fff}.btn.btn-success:focus{box-shadow:0 0 0 .1rem rgba(50,182,67,.2)}.btn.btn-success:focus,.btn.btn-success:hover{background:#30ae40;border-color:#2da23c;color:#fff}.btn.btn-success.active,.btn.btn-success:active{background:#2a9a39;border-color:#278e34;color:#fff}.btn.btn-success.loading::after{border-bottom-color:#fff;border-left-color:#fff}.btn.btn-error{background:#e85600;border-color:#d95000;color:#fff}.btn.btn-error:focus{box-shadow:0 0 0 .1rem rgba(232,86,0,.2)}.btn.btn-error:focus,.btn.btn-error:hover{background:#de5200;border-color:#cf4d00;color:#fff}.btn.btn-error.active,.btn.btn-error:active{background:#c44900;border-color:#b54300;color:#fff}.btn.btn-error.loading::after{border-bottom-color:#fff;border-left-color:#fff}.btn.btn-link{background:0 0;border-color:transparent;color:#5755d9}.btn.btn-link.active,.btn.btn-link:active,.btn.btn-link:focus,.btn.btn-link:hover{color:#302ecd}.btn.btn-sm{font-size:.7rem;height:1.4rem;padding:.05rem .3rem}.btn.btn-lg{font-size:.9rem;height:2rem;padding:.35rem .6rem}.btn.btn-block{display:block;width:100%}.btn.btn-action{padding-left:0;padding-right:0;width:1.8rem}.btn.btn-action.btn-sm{width:1.4rem}.btn.btn-action.btn-lg{width:2rem}.btn.btn-clear{background:0 0;border:0;color:currentColor;height:1rem;line-height:.8rem;margin-left:.2rem;margin-right:-2px;opacity:1;padding:.1rem;text-decoration:none;width:1rem}.btn.btn-clear:focus,.btn.btn-clear:hover{background:rgba(247,248,249,.5);opacity:.95}.btn.btn-clear::before{content:"\2715"}.btn-group{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-wrap:wrap;flex-wrap:wrap}.btn-group .btn{-ms-flex:1 0 auto;flex:1 0 auto}.btn-group .btn:first-child:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0}.btn-group .btn:not(:first-child):not(:last-child){border-radius:0;margin-left:-.05rem}.btn-group .btn:last-child:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0;margin-left:-.05rem}.btn-group .btn.active,.btn-group .btn:active,.btn-group .btn:focus,.btn-group .btn:hover{z-index:1}.btn-group.btn-group-block{display:-ms-flexbox;display:flex}.btn-group.btn-group-block .btn{-ms-flex:1 0 0;flex:1 0 0}.form-group:not(:last-child){margin-bottom:.4rem}fieldset{margin-bottom:.8rem}legend{font-size:.9rem;font-weight:500;margin-bottom:.8rem}.form-label{display:block;line-height:1.2rem;padding:.3rem 0}.form-label.label-sm{font-size:.7rem;padding:.1rem 0}.form-label.label-lg{font-size:.9rem;padding:.4rem 0}.form-input{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:#fff;background-image:none;border:.05rem solid #bcc3ce;border-radius:.1rem;color:#3b4351;display:block;font-size:.8rem;height:1.8rem;line-height:1.2rem;max-width:100%;outline:0;padding:.25rem .4rem;position:relative;transition:background .2s,border .2s,box-shadow .2s,color .2s;width:100%}.form-input:focus{border-color:#5755d9;box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.form-input:-ms-input-placeholder{color:#bcc3ce}.form-input::-ms-input-placeholder{color:#bcc3ce}.form-input::placeholder{color:#bcc3ce}.form-input.input-sm{font-size:.7rem;height:1.4rem;padding:.05rem .3rem}.form-input.input-lg{font-size:.9rem;height:2rem;padding:.35rem .6rem}.form-input.input-inline{display:inline-block;vertical-align:middle;width:auto}.form-input[type=file]{height:auto}textarea.form-input,textarea.form-input.input-lg,textarea.form-input.input-sm{height:auto}.form-input-hint{color:#bcc3ce;font-size:.7rem;margin-top:.2rem}.has-success .form-input-hint,.is-success+.form-input-hint{color:#32b643}.has-error .form-input-hint,.is-error+.form-input-hint{color:#e85600}.form-select{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:#fff;border:.05rem solid #bcc3ce;border-radius:.1rem;color:inherit;font-size:.8rem;height:1.8rem;line-height:1.2rem;outline:0;padding:.25rem .4rem;vertical-align:middle;width:100%}.form-select:focus{border-color:#5755d9;box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.form-select::-ms-expand{display:none}.form-select.select-sm{font-size:.7rem;height:1.4rem;padding:.05rem 1.1rem .05rem .3rem}.form-select.select-lg{font-size:.9rem;height:2rem;padding:.35rem 1.4rem .35rem .6rem}.form-select[multiple],.form-select[size]{height:auto;padding:.25rem .4rem}.form-select[multiple] option,.form-select[size] option{padding:.1rem .2rem}.form-select:not([multiple]):not([size]){background:#fff url("data:image/svg+xml;charset=utf8,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%204%205'%3E%3Cpath%20fill='%23667189'%20d='M2%200L0%202h4zm0%205L0%203h4z'/%3E%3C/svg%3E") no-repeat right .35rem center/.4rem .5rem;padding-right:1.2rem}.has-icon-left,.has-icon-right{position:relative}.has-icon-left .form-icon,.has-icon-right .form-icon{height:.8rem;margin:0 .25rem;position:absolute;top:50%;transform:translateY(-50%);width:.8rem;z-index:2}.has-icon-left .form-icon{left:.05rem}.has-icon-left .form-input{padding-left:1.3rem}.has-icon-right .form-icon{right:.05rem}.has-icon-right .form-input{padding-right:1.3rem}.form-checkbox,.form-radio,.form-switch{display:block;line-height:1.2rem;margin:.2rem 0;min-height:1.4rem;padding:.1rem .4rem .1rem 1.2rem;position:relative}.form-checkbox input,.form-radio input,.form-switch input{clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;position:absolute;width:1px}.form-checkbox input:focus+.form-icon,.form-radio input:focus+.form-icon,.form-switch input:focus+.form-icon{border-color:#5755d9;box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.form-checkbox input:checked+.form-icon,.form-radio input:checked+.form-icon,.form-switch input:checked+.form-icon{background:#5755d9;border-color:#5755d9}.form-checkbox .form-icon,.form-radio .form-icon,.form-switch .form-icon{border:.05rem solid #bcc3ce;cursor:pointer;display:inline-block;position:absolute;transition:background .2s,border .2s,box-shadow .2s,color .2s}.form-checkbox.input-sm,.form-radio.input-sm,.form-switch.input-sm{font-size:.7rem;margin:0}.form-checkbox.input-lg,.form-radio.input-lg,.form-switch.input-lg{font-size:.9rem;margin:.3rem 0}.form-checkbox .form-icon,.form-radio .form-icon{background:#fff;height:.8rem;left:0;top:.3rem;width:.8rem}.form-checkbox input:active+.form-icon,.form-radio input:active+.form-icon{background:#eef0f3}.form-checkbox .form-icon{border-radius:.1rem}.form-checkbox input:checked+.form-icon::before{background-clip:padding-box;border:.1rem solid #fff;border-left-width:0;border-top-width:0;content:"";height:9px;left:50%;margin-left:-3px;margin-top:-6px;position:absolute;top:50%;transform:rotate(45deg);width:6px}.form-checkbox input:indeterminate+.form-icon{background:#5755d9;border-color:#5755d9}.form-checkbox input:indeterminate+.form-icon::before{background:#fff;content:"";height:2px;left:50%;margin-left:-5px;margin-top:-1px;position:absolute;top:50%;width:10px}.form-radio .form-icon{border-radius:50%}.form-radio input:checked+.form-icon::before{background:#fff;border-radius:50%;content:"";height:6px;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);width:6px}.form-switch{padding-left:2rem}.form-switch .form-icon{background:#bcc3ce;background-clip:padding-box;border-radius:.45rem;height:.9rem;left:0;top:.25rem;width:1.6rem}.form-switch .form-icon::before{background:#fff;border-radius:50%;content:"";display:block;height:.8rem;left:0;position:absolute;top:0;transition:background .2s,border .2s,box-shadow .2s,color .2s,left .2s;width:.8rem}.form-switch input:checked+.form-icon::before{left:14px}.form-switch input:active+.form-icon::before{background:#f7f8f9}.input-group{display:-ms-flexbox;display:flex}.input-group .input-group-addon{background:#f7f8f9;border:.05rem solid #bcc3ce;border-radius:.1rem;line-height:1.2rem;padding:.25rem .4rem;white-space:nowrap}.input-group .input-group-addon.addon-sm{font-size:.7rem;padding:.05rem .3rem}.input-group .input-group-addon.addon-lg{font-size:.9rem;padding:.35rem .6rem}.input-group .form-input,.input-group .form-select{-ms-flex:1 1 auto;flex:1 1 auto;width:1%}.input-group .input-group-btn{z-index:1}.input-group .form-input:first-child:not(:last-child),.input-group .form-select:first-child:not(:last-child),.input-group .input-group-addon:first-child:not(:last-child),.input-group .input-group-btn:first-child:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0}.input-group .form-input:not(:first-child):not(:last-child),.input-group .form-select:not(:first-child):not(:last-child),.input-group .input-group-addon:not(:first-child):not(:last-child),.input-group .input-group-btn:not(:first-child):not(:last-child){border-radius:0;margin-left:-.05rem}.input-group .form-input:last-child:not(:first-child),.input-group .form-select:last-child:not(:first-child),.input-group .input-group-addon:last-child:not(:first-child),.input-group .input-group-btn:last-child:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0;margin-left:-.05rem}.input-group .form-input:focus,.input-group .form-select:focus,.input-group .input-group-addon:focus,.input-group .input-group-btn:focus{z-index:2}.input-group .form-select{width:auto}.input-group.input-inline{display:-ms-inline-flexbox;display:inline-flex}.form-input.is-success,.form-select.is-success,.has-success .form-input,.has-success .form-select{background:#f9fdfa;border-color:#32b643}.form-input.is-success:focus,.form-select.is-success:focus,.has-success .form-input:focus,.has-success .form-select:focus{box-shadow:0 0 0 .1rem rgba(50,182,67,.2)}.form-input.is-error,.form-select.is-error,.has-error .form-input,.has-error .form-select{background:#fffaf7;border-color:#e85600}.form-input.is-error:focus,.form-select.is-error:focus,.has-error .form-input:focus,.has-error .form-select:focus{box-shadow:0 0 0 .1rem rgba(232,86,0,.2)}.form-checkbox.is-error .form-icon,.form-radio.is-error .form-icon,.form-switch.is-error .form-icon,.has-error .form-checkbox .form-icon,.has-error .form-radio .form-icon,.has-error .form-switch .form-icon{border-color:#e85600}.form-checkbox.is-error input:checked+.form-icon,.form-radio.is-error input:checked+.form-icon,.form-switch.is-error input:checked+.form-icon,.has-error .form-checkbox input:checked+.form-icon,.has-error .form-radio input:checked+.form-icon,.has-error .form-switch input:checked+.form-icon{background:#e85600;border-color:#e85600}.form-checkbox.is-error input:focus+.form-icon,.form-radio.is-error input:focus+.form-icon,.form-switch.is-error input:focus+.form-icon,.has-error .form-checkbox input:focus+.form-icon,.has-error .form-radio input:focus+.form-icon,.has-error .form-switch input:focus+.form-icon{border-color:#e85600;box-shadow:0 0 0 .1rem rgba(232,86,0,.2)}.form-checkbox.is-error input:indeterminate+.form-icon,.has-error .form-checkbox input:indeterminate+.form-icon{background:#e85600;border-color:#e85600}.form-input:not(:-ms-input-placeholder):invalid{border-color:#e85600}.form-input:not(:placeholder-shown):invalid{border-color:#e85600}.form-input:not(:-ms-input-placeholder):invalid:focus{background:#fffaf7;box-shadow:0 0 0 .1rem rgba(232,86,0,.2)}.form-input:not(:placeholder-shown):invalid:focus{background:#fffaf7;box-shadow:0 0 0 .1rem rgba(232,86,0,.2)}.form-input:not(:-ms-input-placeholder):invalid+.form-input-hint{color:#e85600}.form-input:not(:placeholder-shown):invalid+.form-input-hint{color:#e85600}.form-input.disabled,.form-input:disabled,.form-select.disabled,.form-select:disabled{background-color:#eef0f3;cursor:not-allowed;opacity:.5}.form-input[readonly]{background-color:#f7f8f9}input.disabled+.form-icon,input:disabled+.form-icon{background:#eef0f3;cursor:not-allowed;opacity:.5}.form-switch input.disabled+.form-icon::before,.form-switch input:disabled+.form-icon::before{background:#fff}.form-horizontal{padding:.4rem 0}.form-horizontal .form-group{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap}.form-inline{display:inline-block}.label{background:#eef0f3;border-radius:.1rem;color:#455060;display:inline-block;line-height:1.25;padding:.1rem .2rem}.label.label-rounded{border-radius:5rem;padding-left:.4rem;padding-right:.4rem}.label.label-primary{background:#5755d9;color:#fff}.label.label-secondary{background:#f1f1fc;color:#5755d9}.label.label-success{background:#32b643;color:#fff}.label.label-warning{background:#ffb700;color:#fff}.label.label-error{background:#e85600;color:#fff}code{background:#fcf2f2;border-radius:.1rem;color:#d73e48;font-size:85%;line-height:1.25;padding:.1rem .2rem}.code{border-radius:.1rem;color:#3b4351;position:relative}.code::before{color:#bcc3ce;content:attr(data-lang);font-size:.7rem;position:absolute;right:.4rem;top:.1rem}.code code{background:#f7f8f9;color:inherit;display:block;line-height:1.5;overflow-x:auto;padding:1rem;width:100%}.img-responsive{display:block;height:auto;max-width:100%}.img-fit-cover{object-fit:cover}.img-fit-contain{object-fit:contain}.video-responsive{display:block;overflow:hidden;padding:0;position:relative;width:100%}.video-responsive::before{content:"";display:block;padding-bottom:56.25%}.video-responsive embed,.video-responsive iframe,.video-responsive object{border:0;bottom:0;height:100%;left:0;position:absolute;right:0;top:0;width:100%}video.video-responsive{height:auto;max-width:100%}video.video-responsive::before{content:none}.video-responsive-4-3::before{padding-bottom:75%}.video-responsive-1-1::before{padding-bottom:100%}.figure{margin:0 0 .4rem 0}.figure .figure-caption{color:#66758c;margin-top:.4rem}.container{margin-left:auto;margin-right:auto;padding-left:.4rem;padding-right:.4rem;width:100%}.container.grid-xl{max-width:1296px}.container.grid-lg{max-width:976px}.container.grid-md{max-width:856px}.container.grid-sm{max-width:616px}.container.grid-xs{max-width:496px}.show-lg,.show-md,.show-sm,.show-xl,.show-xs{display:none!important}.cols,.columns{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-left:-.4rem;margin-right:-.4rem}.cols.col-gapless,.columns.col-gapless{margin-left:0;margin-right:0}.cols.col-gapless>.column,.columns.col-gapless>.column{padding-left:0;padding-right:0}.cols.col-oneline,.columns.col-oneline{-ms-flex-wrap:nowrap;flex-wrap:nowrap;overflow-x:auto}.column,[class~=col-]{-ms-flex:1;flex:1;max-width:100%;padding-left:.4rem;padding-right:.4rem}.column.col-1,.column.col-10,.column.col-11,.column.col-12,.column.col-2,.column.col-3,.column.col-4,.column.col-5,.column.col-6,.column.col-7,.column.col-8,.column.col-9,.column.col-auto,[class~=col-].col-1,[class~=col-].col-10,[class~=col-].col-11,[class~=col-].col-12,[class~=col-].col-2,[class~=col-].col-3,[class~=col-].col-4,[class~=col-].col-5,[class~=col-].col-6,[class~=col-].col-7,[class~=col-].col-8,[class~=col-].col-9,[class~=col-].col-auto{-ms-flex:none;flex:none}.col-12{width:100%}.col-11{width:91.66666667%}.col-10{width:83.33333333%}.col-9{width:75%}.col-8{width:66.66666667%}.col-7{width:58.33333333%}.col-6{width:50%}.col-5{width:41.66666667%}.col-4{width:33.33333333%}.col-3{width:25%}.col-2{width:16.66666667%}.col-1{width:8.33333333%}.col-auto{-ms-flex:0 0 auto;flex:0 0 auto;max-width:none;width:auto}.col-mx-auto{margin-left:auto;margin-right:auto}.col-ml-auto{margin-left:auto}.col-mr-auto{margin-right:auto}@media (max-width:1280px){.col-xl-1,.col-xl-10,.col-xl-11,.col-xl-12,.col-xl-2,.col-xl-3,.col-xl-4,.col-xl-5,.col-xl-6,.col-xl-7,.col-xl-8,.col-xl-9,.col-xl-auto{-ms-flex:none;flex:none}.col-xl-12{width:100%}.col-xl-11{width:91.66666667%}.col-xl-10{width:83.33333333%}.col-xl-9{width:75%}.col-xl-8{width:66.66666667%}.col-xl-7{width:58.33333333%}.col-xl-6{width:50%}.col-xl-5{width:41.66666667%}.col-xl-4{width:33.33333333%}.col-xl-3{width:25%}.col-xl-2{width:16.66666667%}.col-xl-1{width:8.33333333%}.col-xl-auto{width:auto}.hide-xl{display:none!important}.show-xl{display:block!important}}@media (max-width:960px){.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-auto{-ms-flex:none;flex:none}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-auto{width:auto}.hide-lg{display:none!important}.show-lg{display:block!important}}@media (max-width:840px){.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-auto{-ms-flex:none;flex:none}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-auto{width:auto}.hide-md{display:none!important}.show-md{display:block!important}}@media (max-width:600px){.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-auto{-ms-flex:none;flex:none}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-auto{width:auto}.hide-sm{display:none!important}.show-sm{display:block!important}}@media (max-width:480px){.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-auto{-ms-flex:none;flex:none}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-auto{width:auto}.hide-xs{display:none!important}.show-xs{display:block!important}}.hero{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:justify;justify-content:space-between;padding-bottom:4rem;padding-top:4rem}.hero.hero-sm{padding-bottom:2rem;padding-top:2rem}.hero.hero-lg{padding-bottom:8rem;padding-top:8rem}.hero .hero-body{padding:.4rem}.navbar{align-items:stretch;display:-ms-flexbox;display:flex;-ms-flex-align:stretch;-ms-flex-pack:justify;-ms-flex-wrap:wrap;flex-wrap:wrap;justify-content:space-between}.navbar .navbar-section{align-items:center;display:-ms-flexbox;display:flex;-ms-flex:1 0 0;flex:1 0 0;-ms-flex-align:center}.navbar .navbar-section:not(:first-child):last-child{-ms-flex-pack:end;justify-content:flex-end}.navbar .navbar-center{align-items:center;display:-ms-flexbox;display:flex;-ms-flex:0 0 auto;flex:0 0 auto;-ms-flex-align:center}.navbar .navbar-brand{font-size:.9rem;text-decoration:none}.accordion input:checked~.accordion-header>.icon:first-child,.accordion[open] .accordion-header>.icon:first-child{transform:rotate(90deg)}.accordion input:checked~.accordion-body,.accordion[open] .accordion-body{max-height:50rem}.accordion .accordion-header{display:block;padding:.2rem .4rem}.accordion .accordion-header .icon{transition:transform .25s}.accordion .accordion-body{margin-bottom:.4rem;max-height:0;overflow:hidden;transition:max-height .25s}summary.accordion-header::-webkit-details-marker{display:none}.avatar{background:#5755d9;border-radius:50%;color:rgba(255,255,255,.85);display:inline-block;font-size:.8rem;font-weight:300;height:1.6rem;line-height:1.25;margin:0;position:relative;vertical-align:middle;width:1.6rem}.avatar.avatar-xs{font-size:.4rem;height:.8rem;width:.8rem}.avatar.avatar-sm{font-size:.6rem;height:1.2rem;width:1.2rem}.avatar.avatar-lg{font-size:1.2rem;height:2.4rem;width:2.4rem}.avatar.avatar-xl{font-size:1.6rem;height:3.2rem;width:3.2rem}.avatar img{border-radius:50%;height:100%;position:relative;width:100%;z-index:1}.avatar .avatar-icon,.avatar .avatar-presence{background:#fff;bottom:14.64%;height:50%;padding:.1rem;position:absolute;right:14.64%;transform:translate(50%,50%);width:50%;z-index:2}.avatar .avatar-presence{background:#bcc3ce;border-radius:50%;box-shadow:0 0 0 .1rem #fff;height:.5em;width:.5em}.avatar .avatar-presence.online{background:#32b643}.avatar .avatar-presence.busy{background:#e85600}.avatar .avatar-presence.away{background:#ffb700}.avatar[data-initial]::before{color:currentColor;content:attr(data-initial);left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);z-index:1}.badge{position:relative;white-space:nowrap}.badge:not([data-badge])::after,.badge[data-badge]::after{background:#5755d9;background-clip:padding-box;border-radius:.5rem;box-shadow:0 0 0 .1rem #fff;color:#fff;content:attr(data-badge);display:inline-block;transform:translate(-.05rem,-.5rem)}.badge[data-badge]::after{font-size:.7rem;height:.9rem;line-height:1;min-width:.9rem;padding:.1rem .2rem;text-align:center;white-space:nowrap}.badge:not([data-badge])::after,.badge[data-badge=""]::after{height:6px;min-width:6px;padding:0;width:6px}.badge.btn::after{position:absolute;right:0;top:0;transform:translate(50%,-50%)}.badge.avatar::after{position:absolute;right:14.64%;top:14.64%;transform:translate(50%,-50%);z-index:100}.breadcrumb{list-style:none;margin:.2rem 0;padding:.2rem 0}.breadcrumb .breadcrumb-item{color:#66758c;display:inline-block;margin:0;padding:.2rem 0}.breadcrumb .breadcrumb-item:not(:last-child){margin-right:.2rem}.breadcrumb .breadcrumb-item:not(:last-child) a{color:#66758c}.breadcrumb .breadcrumb-item:not(:first-child)::before{color:#66758c;content:"/";padding-right:.4rem}.bar{background:#eef0f3;border-radius:.1rem;display:-ms-flexbox;display:flex;-ms-flex-wrap:nowrap;flex-wrap:nowrap;height:.8rem;width:100%}.bar.bar-sm{height:.2rem}.bar .bar-item{background:#5755d9;color:#fff;display:block;-ms-flex-negative:0;flex-shrink:0;font-size:.7rem;height:100%;line-height:.8rem;position:relative;text-align:center;width:0}.bar .bar-item:first-child{border-bottom-left-radius:.1rem;border-top-left-radius:.1rem}.bar .bar-item:last-child{border-bottom-right-radius:.1rem;border-top-right-radius:.1rem;-ms-flex-negative:1;flex-shrink:1}.bar-slider{height:.1rem;margin:.4rem 0;position:relative}.bar-slider .bar-item{left:0;padding:0;position:absolute}.bar-slider .bar-item:not(:last-child):first-child{background:#eef0f3;z-index:1}.bar-slider .bar-slider-btn{background:#5755d9;border:0;border-radius:50%;height:.6rem;padding:0;position:absolute;right:0;top:50%;transform:translate(50%,-50%);width:.6rem}.bar-slider .bar-slider-btn:active{box-shadow:0 0 0 .1rem #5755d9}.card{background:#fff;border:.05rem solid #dadee4;border-radius:.1rem;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.card .card-body,.card .card-footer,.card .card-header{padding:.8rem;padding-bottom:0}.card .card-body:last-child,.card .card-footer:last-child,.card .card-header:last-child{padding-bottom:.8rem}.card .card-body{-ms-flex:1 1 auto;flex:1 1 auto}.card .card-image{padding-top:.8rem}.card .card-image:first-child{padding-top:0}.card .card-image:first-child img{border-top-left-radius:.1rem;border-top-right-radius:.1rem}.card .card-image:last-child img{border-bottom-left-radius:.1rem;border-bottom-right-radius:.1rem}.chip{align-items:center;background:#eef0f3;border-radius:5rem;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;font-size:90%;height:1.2rem;line-height:.8rem;margin:.1rem;max-width:320px;overflow:hidden;padding:.2rem .4rem;text-decoration:none;text-overflow:ellipsis;vertical-align:middle;white-space:nowrap}.chip.active{background:#5755d9;color:#fff}.chip .avatar{margin-left:-.4rem;margin-right:.2rem}.chip .btn-clear{border-radius:50%;transform:scale(.75)}.dropdown{display:inline-block;position:relative}.dropdown .menu{animation:slide-down .15s ease 1;display:none;left:0;max-height:50vh;overflow-y:auto;position:absolute;top:100%}.dropdown.dropdown-right .menu{left:auto;right:0}.dropdown .dropdown-toggle:focus+.menu,.dropdown .menu:hover,.dropdown.active .menu{display:block}.dropdown .btn-group .dropdown-toggle:nth-last-child(2){border-bottom-right-radius:.1rem;border-top-right-radius:.1rem}.empty{background:#f7f8f9;border-radius:.1rem;color:#66758c;padding:3.2rem 1.6rem;text-align:center}.empty .empty-icon{margin-bottom:.8rem}.empty .empty-subtitle,.empty .empty-title{margin:.4rem auto}.empty .empty-action{margin-top:.8rem}.menu{background:#fff;border-radius:.1rem;box-shadow:0 .05rem .2rem rgba(48,55,66,.3);list-style:none;margin:0;min-width:180px;padding:.4rem;transform:translateY(.2rem);z-index:300}.menu.menu-nav{background:0 0;box-shadow:none}.menu .menu-item{margin-top:0;padding:0 .4rem;position:relative;text-decoration:none}.menu .menu-item>a{border-radius:.1rem;color:inherit;display:block;margin:0 -.4rem;padding:.2rem .4rem;text-decoration:none}.menu .menu-item>a:focus,.menu .menu-item>a:hover{background:#f1f1fc;color:#5755d9}.menu .menu-item>a.active,.menu .menu-item>a:active{background:#f1f1fc;color:#5755d9}.menu .menu-item .form-checkbox,.menu .menu-item .form-radio,.menu .menu-item .form-switch{margin:.1rem 0}.menu .menu-item+.menu-item{margin-top:.2rem}.menu .menu-badge{align-items:center;display:-ms-flexbox;display:flex;-ms-flex-align:center;height:100%;position:absolute;right:0;top:0}.menu .menu-badge .label{margin-right:.4rem}.modal{align-items:center;bottom:0;display:none;-ms-flex-align:center;-ms-flex-pack:center;justify-content:center;left:0;opacity:0;overflow:hidden;padding:.4rem;position:fixed;right:0;top:0}.modal.active,.modal:target{display:-ms-flexbox;display:flex;opacity:1;z-index:400}.modal.active .modal-overlay,.modal:target .modal-overlay{background:rgba(247,248,249,.75);bottom:0;cursor:default;display:block;left:0;position:absolute;right:0;top:0}.modal.active .modal-container,.modal:target .modal-container{animation:slide-down .2s ease 1;z-index:1}.modal.modal-sm .modal-container{max-width:320px;padding:0 .4rem}.modal.modal-lg .modal-overlay{background:#fff}.modal.modal-lg .modal-container{box-shadow:none;max-width:960px}.modal-container{background:#fff;border-radius:.1rem;box-shadow:0 .2rem .5rem rgba(48,55,66,.3);display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;max-height:75vh;max-width:640px;padding:0 .8rem;width:100%}.modal-container.modal-fullheight{max-height:100vh}.modal-container .modal-header{color:#303742;padding:.8rem}.modal-container .modal-body{overflow-y:auto;padding:.8rem;position:relative}.modal-container .modal-footer{padding:.8rem;text-align:right}.nav{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;list-style:none;margin:.2rem 0}.nav .nav-item a{color:#66758c;padding:.2rem .4rem;text-decoration:none}.nav .nav-item a:focus,.nav .nav-item a:hover{color:#5755d9}.nav .nav-item.active>a{color:#505c6e;font-weight:700}.nav .nav-item.active>a:focus,.nav .nav-item.active>a:hover{color:#5755d9}.nav .nav{margin-bottom:.4rem;margin-left:.8rem}.pagination{display:-ms-flexbox;display:flex;list-style:none;margin:.2rem 0;padding:.2rem 0}.pagination .page-item{margin:.2rem .05rem}.pagination .page-item span{display:inline-block;padding:.2rem .2rem}.pagination .page-item a{border-radius:.1rem;display:inline-block;padding:.2rem .4rem;text-decoration:none}.pagination .page-item a:focus,.pagination .page-item a:hover{color:#5755d9}.pagination .page-item.disabled a{cursor:default;opacity:.5;pointer-events:none}.pagination .page-item.active a{background:#5755d9;color:#fff}.pagination .page-item.page-next,.pagination .page-item.page-prev{-ms-flex:1 0 50%;flex:1 0 50%}.pagination .page-item.page-next{text-align:right}.pagination .page-item .page-item-title{margin:0}.pagination .page-item .page-item-subtitle{margin:0;opacity:.5}.panel{border:.05rem solid #dadee4;border-radius:.1rem;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.panel .panel-footer,.panel .panel-header{-ms-flex:0 0 auto;flex:0 0 auto;padding:.8rem}.panel .panel-nav{-ms-flex:0 0 auto;flex:0 0 auto}.panel .panel-body{-ms-flex:1 1 auto;flex:1 1 auto;overflow-y:auto;padding:0 .8rem}.popover{display:inline-block;position:relative}.popover .popover-container{left:50%;opacity:0;padding:.4rem;position:absolute;top:0;transform:translate(-50%,-50%) scale(0);transition:transform .2s;width:320px;z-index:300}.popover :focus+.popover-container,.popover:hover .popover-container{display:block;opacity:1;transform:translate(-50%,-100%) scale(1)}.popover.popover-right .popover-container{left:100%;top:50%}.popover.popover-right :focus+.popover-container,.popover.popover-right:hover .popover-container{transform:translate(0,-50%) scale(1)}.popover.popover-bottom .popover-container{left:50%;top:100%}.popover.popover-bottom :focus+.popover-container,.popover.popover-bottom:hover .popover-container{transform:translate(-50%,0) scale(1)}.popover.popover-left .popover-container{left:0;top:50%}.popover.popover-left :focus+.popover-container,.popover.popover-left:hover .popover-container{transform:translate(-100%,-50%) scale(1)}.popover .card{border:0;box-shadow:0 .2rem .5rem rgba(48,55,66,.3)}.step{display:-ms-flexbox;display:flex;-ms-flex-wrap:nowrap;flex-wrap:nowrap;list-style:none;margin:.2rem 0;width:100%}.step .step-item{-ms-flex:1 1 0;flex:1 1 0;margin-top:0;min-height:1rem;position:relative;text-align:center}.step .step-item:not(:first-child)::before{background:#5755d9;content:"";height:2px;left:-50%;position:absolute;top:9px;width:100%}.step .step-item a{color:#5755d9;display:inline-block;padding:20px 10px 0;text-decoration:none}.step .step-item a::before{background:#5755d9;border:.1rem solid #fff;border-radius:50%;content:"";display:block;height:.6rem;left:50%;position:absolute;top:.2rem;transform:translateX(-50%);width:.6rem;z-index:1}.step .step-item.active a::before{background:#fff;border:.1rem solid #5755d9}.step .step-item.active~.step-item::before{background:#dadee4}.step .step-item.active~.step-item a{color:#bcc3ce}.step .step-item.active~.step-item a::before{background:#dadee4}.tab{align-items:center;border-bottom:.05rem solid #dadee4;display:-ms-flexbox;display:flex;-ms-flex-align:center;-ms-flex-wrap:wrap;flex-wrap:wrap;list-style:none;margin:.2rem 0 .15rem 0}.tab .tab-item{margin-top:0}.tab .tab-item a{border-bottom:.1rem solid transparent;color:inherit;display:block;margin:0 .4rem 0 0;padding:.4rem .2rem .3rem .2rem;text-decoration:none}.tab .tab-item a:focus,.tab .tab-item a:hover{color:#5755d9}.tab .tab-item a.active,.tab .tab-item.active a{border-bottom-color:#5755d9;color:#5755d9}.tab .tab-item.tab-action{-ms-flex:1 0 auto;flex:1 0 auto;text-align:right}.tab .tab-item .btn-clear{margin-top:-.2rem}.tab.tab-block .tab-item{-ms-flex:1 0 0;flex:1 0 0;text-align:center}.tab.tab-block .tab-item a{margin:0}.tab.tab-block .tab-item .badge[data-badge]::after{position:absolute;right:.1rem;top:.1rem;transform:translate(0,0)}.tab:not(.tab-block) .badge{padding-right:0}.tile{align-content:space-between;align-items:flex-start;display:-ms-flexbox;display:flex;-ms-flex-align:start;-ms-flex-line-pack:justify}.tile .tile-action,.tile .tile-icon{-ms-flex:0 0 auto;flex:0 0 auto}.tile .tile-content{-ms-flex:1 1 auto;flex:1 1 auto}.tile .tile-content:not(:first-child){padding-left:.4rem}.tile .tile-content:not(:last-child){padding-right:.4rem}.tile .tile-subtitle,.tile .tile-title{line-height:1.2rem}.tile.tile-centered{align-items:center;-ms-flex-align:center}.tile.tile-centered .tile-content{overflow:hidden}.tile.tile-centered .tile-subtitle,.tile.tile-centered .tile-title{margin-bottom:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.toast{background:rgba(48,55,66,.95);border:.05rem solid #303742;border-color:#303742;border-radius:.1rem;color:#fff;display:block;padding:.4rem;width:100%}.toast.toast-primary{background:rgba(87,85,217,.95);border-color:#5755d9}.toast.toast-success{background:rgba(50,182,67,.95);border-color:#32b643}.toast.toast-warning{background:rgba(255,183,0,.95);border-color:#ffb700}.toast.toast-error{background:rgba(232,86,0,.95);border-color:#e85600}.toast a{color:#fff;text-decoration:underline}.toast a.active,.toast a:active,.toast a:focus,.toast a:hover{opacity:.75}.toast .btn-clear{margin:.1rem}.toast p:last-child{margin-bottom:0}.tooltip{position:relative}.tooltip::after{background:rgba(48,55,66,.95);border-radius:.1rem;bottom:100%;color:#fff;content:attr(data-tooltip);display:block;font-size:.7rem;left:50%;max-width:320px;opacity:0;overflow:hidden;padding:.2rem .4rem;pointer-events:none;position:absolute;text-overflow:ellipsis;transform:translate(-50%,.4rem);transition:opacity .2s,transform .2s;white-space:pre;z-index:300}.tooltip:focus::after,.tooltip:hover::after{opacity:1;transform:translate(-50%,-.2rem)}.tooltip.disabled,.tooltip[disabled]{pointer-events:auto}.tooltip.tooltip-right::after{bottom:50%;left:100%;transform:translate(-.2rem,50%)}.tooltip.tooltip-right:focus::after,.tooltip.tooltip-right:hover::after{transform:translate(.2rem,50%)}.tooltip.tooltip-bottom::after{bottom:auto;top:100%;transform:translate(-50%,-.4rem)}.tooltip.tooltip-bottom:focus::after,.tooltip.tooltip-bottom:hover::after{transform:translate(-50%,.2rem)}.tooltip.tooltip-left::after{bottom:50%;left:auto;right:100%;transform:translate(.4rem,50%)}.tooltip.tooltip-left:focus::after,.tooltip.tooltip-left:hover::after{transform:translate(-.2rem,50%)}@keyframes loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes slide-down{0%{opacity:0;transform:translateY(-1.6rem)}100%{opacity:1;transform:translateY(0)}}.text-primary{color:#5755d9!important}a.text-primary:focus,a.text-primary:hover{color:#4240d4}a.text-primary:visited{color:#6c6ade}.text-secondary{color:#e5e5f9!important}a.text-secondary:focus,a.text-secondary:hover{color:#d1d0f4}a.text-secondary:visited{color:#fafafe}.text-gray{color:#bcc3ce!important}a.text-gray:focus,a.text-gray:hover{color:#adb6c4}a.text-gray:visited{color:#cbd0d9}.text-light{color:#fff!important}a.text-light:focus,a.text-light:hover{color:#f2f2f2}a.text-light:visited{color:#fff}.text-dark{color:#3b4351!important}a.text-dark:focus,a.text-dark:hover{color:#303742}a.text-dark:visited{color:#455060}.text-success{color:#32b643!important}a.text-success:focus,a.text-success:hover{color:#2da23c}a.text-success:visited{color:#39c94b}.text-warning{color:#ffb700!important}a.text-warning:focus,a.text-warning:hover{color:#e6a500}a.text-warning:visited{color:#ffbe1a}.text-error{color:#e85600!important}a.text-error:focus,a.text-error:hover{color:#cf4d00}a.text-error:visited{color:#ff6003}.bg-primary{background:#5755d9!important;color:#fff}.bg-secondary{background:#f1f1fc!important}.bg-dark{background:#303742!important;color:#fff}.bg-gray{background:#f7f8f9!important}.bg-success{background:#32b643!important;color:#fff}.bg-warning{background:#ffb700!important;color:#fff}.bg-error{background:#e85600!important;color:#fff}.c-hand{cursor:pointer}.c-move{cursor:move}.c-zoom-in{cursor:zoom-in}.c-zoom-out{cursor:zoom-out}.c-not-allowed{cursor:not-allowed}.c-auto{cursor:auto}.d-block{display:block}.d-inline{display:inline}.d-inline-block{display:inline-block}.d-flex{display:-ms-flexbox;display:flex}.d-inline-flex{display:-ms-inline-flexbox;display:inline-flex}.d-hide,.d-none{display:none!important}.d-visible{visibility:visible}.d-invisible{visibility:hidden}.text-hide{background:0 0;border:0;color:transparent;font-size:0;line-height:0;text-shadow:none}.text-assistive{border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.divider,.divider-vert{display:block;position:relative}.divider-vert[data-content]::after,.divider[data-content]::after{background:#fff;color:#bcc3ce;content:attr(data-content);display:inline-block;font-size:.7rem;padding:0 .4rem;transform:translateY(-.65rem)}.divider{border-top:.05rem solid #f1f3f5;height:.05rem;margin:.4rem 0}.divider[data-content]{margin:.8rem 0}.divider-vert{display:block;padding:.8rem}.divider-vert::before{border-left:.05rem solid #dadee4;bottom:.4rem;content:"";display:block;left:50%;position:absolute;top:.4rem;transform:translateX(-50%)}.divider-vert[data-content]::after{left:50%;padding:.2rem 0;position:absolute;top:50%;transform:translate(-50%,-50%)}.loading{color:transparent!important;min-height:.8rem;pointer-events:none;position:relative}.loading::after{animation:loading .5s infinite linear;background:0 0;border:.1rem solid #5755d9;border-radius:50%;border-right-color:transparent;border-top-color:transparent;content:"";display:block;height:.8rem;left:50%;margin-left:-.4rem;margin-top:-.4rem;opacity:1;padding:0;position:absolute;top:50%;width:.8rem;z-index:1}.loading.loading-lg{min-height:2rem}.loading.loading-lg::after{height:1.6rem;margin-left:-.8rem;margin-top:-.8rem;width:1.6rem}.clearfix::after{clear:both;content:"";display:table}.float-left{float:left!important}.float-right{float:right!important}.p-relative{position:relative!important}.p-absolute{position:absolute!important}.p-fixed{position:fixed!important}.p-sticky{position:-webkit-sticky!important;position:sticky!important}.p-centered{display:block;float:none;margin-left:auto;margin-right:auto}.flex-centered{align-items:center;display:-ms-flexbox;display:flex;-ms-flex-align:center;-ms-flex-pack:center;justify-content:center}.m-0{margin:0!important}.mb-0{margin-bottom:0!important}.ml-0{margin-left:0!important}.mr-0{margin-right:0!important}.mt-0{margin-top:0!important}.mx-0{margin-left:0!important;margin-right:0!important}.my-0{margin-bottom:0!important;margin-top:0!important}.m-1{margin:.2rem!important}.mb-1{margin-bottom:.2rem!important}.ml-1{margin-left:.2rem!important}.mr-1{margin-right:.2rem!important}.mt-1{margin-top:.2rem!important}.mx-1{margin-left:.2rem!important;margin-right:.2rem!important}.my-1{margin-bottom:.2rem!important;margin-top:.2rem!important}.m-2{margin:.4rem!important}.mb-2{margin-bottom:.4rem!important}.ml-2{margin-left:.4rem!important}.mr-2{margin-right:.4rem!important}.mt-2{margin-top:.4rem!important}.mx-2{margin-left:.4rem!important;margin-right:.4rem!important}.my-2{margin-bottom:.4rem!important;margin-top:.4rem!important}.p-0{padding:0!important}.pb-0{padding-bottom:0!important}.pl-0{padding-left:0!important}.pr-0{padding-right:0!important}.pt-0{padding-top:0!important}.px-0{padding-left:0!important;padding-right:0!important}.py-0{padding-bottom:0!important;padding-top:0!important}.p-1{padding:.2rem!important}.pb-1{padding-bottom:.2rem!important}.pl-1{padding-left:.2rem!important}.pr-1{padding-right:.2rem!important}.pt-1{padding-top:.2rem!important}.px-1{padding-left:.2rem!important;padding-right:.2rem!important}.py-1{padding-bottom:.2rem!important;padding-top:.2rem!important}.p-2{padding:.4rem!important}.pb-2{padding-bottom:.4rem!important}.pl-2{padding-left:.4rem!important}.pr-2{padding-right:.4rem!important}.pt-2{padding-top:.4rem!important}.px-2{padding-left:.4rem!important;padding-right:.4rem!important}.py-2{padding-bottom:.4rem!important;padding-top:.4rem!important}.s-rounded{border-radius:.1rem}.s-circle{border-radius:50%}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-normal{font-weight:400}.text-bold{font-weight:700}.text-italic{font-style:italic}.text-large{font-size:1.2em}.text-small{font-size:.9em}.text-tiny{font-size:.8em}.text-muted{opacity:.8}.text-ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-clip{overflow:hidden;text-overflow:clip;white-space:nowrap}.text-break{-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;word-break:break-word;word-wrap:break-word} \ No newline at end of file diff --git a/implementation/18-caching/public/favicon.ico b/implementation/18-caching/public/favicon.ico new file mode 100644 index 0000000..09499b8 Binary files /dev/null and b/implementation/18-caching/public/favicon.ico differ diff --git a/implementation/18-caching/public/index.php b/implementation/18-caching/public/index.php new file mode 100644 index 0000000..32f5eb3 --- /dev/null +++ b/implementation/18-caching/public/index.php @@ -0,0 +1,5 @@ +getBody(); + $data = [ + 'now' => $now()->format('H:i:s'), + 'name' => $name, + ]; + + $content = $renderer->render('hello', $data); + + $body->write($content); + + return $response + ->withStatus(200) + ->withBody($body); + } +} diff --git a/implementation/18-caching/src/Action/Other.php b/implementation/18-caching/src/Action/Other.php new file mode 100644 index 0000000..da9ceaf --- /dev/null +++ b/implementation/18-caching/src/Action/Other.php @@ -0,0 +1,16 @@ +parse('This *works* **too!**'); + $response->getBody()->write($html); + return $response->withStatus(200); + } +} diff --git a/implementation/18-caching/src/Action/Page.php b/implementation/18-caching/src/Action/Page.php new file mode 100644 index 0000000..96696e4 --- /dev/null +++ b/implementation/18-caching/src/Action/Page.php @@ -0,0 +1,60 @@ +repo->byName($page); + + // fix the next and previous buttons to work with our routing + $content = preg_replace('/\(\d\d-/m', '(', $page->content); + assert(is_string($content)); + $content = str_replace('.md)', ')', $content); + + $data = [ + 'title' => $page->title, + 'content' => $this->parser->parse($content), + ]; + + $html = $this->renderer->render('page/show', $data); + $this->response->getBody()->write($html); + return $this->response; + } + + public function list(): ResponseInterface + { + $pages = array_map(function (MarkdownPage $page) { + return [ + 'id' => $page->id, + 'title' => $page->title, + ]; + }, $this->repo->all()); + + $html = $this->renderer->render('page/list', ['pages' => $pages]); + $this->response->getBody()->write($html); + return $this->response; + } +} diff --git a/implementation/18-caching/src/Bootstrap.php b/implementation/18-caching/src/Bootstrap.php new file mode 100644 index 0000000..3abc2e5 --- /dev/null +++ b/implementation/18-caching/src/Bootstrap.php @@ -0,0 +1,40 @@ +getContainer(); + +$settings = $settingsProvider->getSettings(); + +$whoops = new Run; +if ($settings->environment === 'dev') { + $whoops->pushHandler(new PrettyPageHandler); +} else { + $whoops->pushHandler(function (Throwable $e): void { + error_log('Error: ' . $e->getMessage(), (int) $e->getCode()); + echo 'An Error happened'; + }); +} +$whoops->register(); + +$app = $container->get(Kernel::class); +assert($app instanceof Kernel); + +$app->run(); diff --git a/implementation/18-caching/src/Exception/InternalServerError.php b/implementation/18-caching/src/Exception/InternalServerError.php new file mode 100644 index 0000000..9c3b369 --- /dev/null +++ b/implementation/18-caching/src/Exception/InternalServerError.php @@ -0,0 +1,9 @@ +factory::fromGlobals(); + } + + /** + * @param UriInterface|string $uri + * @param array $serverParams + */ + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface + { + return $this->factory->createServerRequest($method, $uri, $serverParams); + } +} diff --git a/implementation/18-caching/src/Factory/FileSystemSettingsProvider.php b/implementation/18-caching/src/Factory/FileSystemSettingsProvider.php new file mode 100644 index 0000000..f071078 --- /dev/null +++ b/implementation/18-caching/src/Factory/FileSystemSettingsProvider.php @@ -0,0 +1,22 @@ +filePath; + assert($settings instanceof Settings); + return $settings; + } +} diff --git a/implementation/18-caching/src/Factory/PipelineProvider.php b/implementation/18-caching/src/Factory/PipelineProvider.php new file mode 100644 index 0000000..77738f8 --- /dev/null +++ b/implementation/18-caching/src/Factory/PipelineProvider.php @@ -0,0 +1,25 @@ +settings->middlewaresFile; + return new ContainerPipeline($middlewares, $this->tip, $this->container); + } +} diff --git a/implementation/18-caching/src/Factory/RequestFactory.php b/implementation/18-caching/src/Factory/RequestFactory.php new file mode 100644 index 0000000..2b17abc --- /dev/null +++ b/implementation/18-caching/src/Factory/RequestFactory.php @@ -0,0 +1,11 @@ +settingsProvider->getSettings(); + $dependencies = require $settings->dependenciesFile; + $dependencies[Settings::class] = $settings; + $builder->addDefinitions($dependencies); + // $builder->enableCompilation('/tmp'); + return $builder->build(); + } +} diff --git a/implementation/18-caching/src/Factory/SettingsProvider.php b/implementation/18-caching/src/Factory/SettingsProvider.php new file mode 100644 index 0000000..ce1c5f0 --- /dev/null +++ b/implementation/18-caching/src/Factory/SettingsProvider.php @@ -0,0 +1,10 @@ +getHeaders() as $name => $values) { + $first = strtolower($name) !== 'set-cookie'; + foreach ($values as $value) { + $header = sprintf('%s: %s', $name, $value); + header($header, $first); + $first = false; + } + } + + $statusLine = sprintf( + 'HTTP/%s %s %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + ); + header($statusLine, true, $response->getStatusCode()); + + if ($withoutBody) { + return; + } + + echo $response->getBody(); + } +} diff --git a/implementation/18-caching/src/Http/ContainerPipeline.php b/implementation/18-caching/src/Http/ContainerPipeline.php new file mode 100644 index 0000000..816cedd --- /dev/null +++ b/implementation/18-caching/src/Http/ContainerPipeline.php @@ -0,0 +1,82 @@ + $middlewares + * @param RequestHandlerInterface $tip + * @param ContainerInterface $container + */ + public function __construct( + private array $middlewares, + private RequestHandlerInterface $tip, + private ContainerInterface $container, + ) { + } + + public function dispatch(ServerRequestInterface $request): ResponseInterface + { + $this->buildStack(); + return $this->tip->handle($request); + } + + private function buildStack(): void + { + foreach (array_reverse($this->middlewares) as $middleware) { + $next = $this->tip; + if ($middleware instanceof MiddlewareInterface) { + $this->tip = $this->wrapMiddleware($middleware, $next); + } + if (is_string($middleware)) { + $this->tip = $this->wrapResolvedMiddleware($middleware, $next); + } + } + } + + private function wrapResolvedMiddleware(string $middleware, RequestHandlerInterface $next): RequestHandlerInterface + { + return new class ($middleware, $next, $this->container) implements RequestHandlerInterface { + public function __construct( + private readonly string $middleware, + private readonly RequestHandlerInterface $handler, + private readonly ContainerInterface $container, + ) { + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + $middleware = $this->container->get($this->middleware); + assert($middleware instanceof MiddlewareInterface); + return $middleware->process($request, $this->handler); + } + }; + } + + private function wrapMiddleware(MiddlewareInterface $middleware, RequestHandlerInterface $next): RequestHandlerInterface + { + return new class ($middleware, $next) implements RequestHandlerInterface { + public function __construct( + private readonly MiddlewareInterface $middleware, + private readonly RequestHandlerInterface $handler, + ) { + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + return $this->middleware->process($request, $this->handler); + } + }; + } +} diff --git a/implementation/18-caching/src/Http/Emitter.php b/implementation/18-caching/src/Http/Emitter.php new file mode 100644 index 0000000..ce4c035 --- /dev/null +++ b/implementation/18-caching/src/Http/Emitter.php @@ -0,0 +1,10 @@ +getAttribute($this->routeAttributeName, false); + $vars = $request->getAttributes(); + $vars['request'] = $request; + $response = $this->invoker->call($handler, $vars); + if (! $response instanceof ResponseInterface) { + throw new InternalServerError('Handler returned invalid response'); + } + return $response; + } + + public function setRouteAttributeName(string $routeAttributeName = '__route_handler'): void + { + $this->routeAttributeName = $routeAttributeName; + } +} diff --git a/implementation/18-caching/src/Http/Pipeline.php b/implementation/18-caching/src/Http/Pipeline.php new file mode 100644 index 0000000..1a9dcda --- /dev/null +++ b/implementation/18-caching/src/Http/Pipeline.php @@ -0,0 +1,11 @@ +dispatcher->dispatch( + $request->getMethod(), + $request->getUri()->getPath(), + ); + + if ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) { + throw new MethodNotAllowed; + } + + if ($routeInfo[0] === Dispatcher::FOUND) { + foreach ($routeInfo[2] as $attributeName => $attributeValue) { + $request = $request->withAttribute($attributeName, $attributeValue); + } + return $request->withAttribute( + $this->routeAttributeName, + $routeInfo[1] + ); + } + + throw new NotFound; + } + + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + try { + $request = $this->decorateRequest($request); + } catch (NotFound) { + $response = $this->responseFactory->createResponse(404); + $response->getBody()->write('Not Found'); + return $response; + } catch (MethodNotAllowed) { + return $this->responseFactory->createResponse(405); + } catch (Throwable $t) { + throw new InternalServerError($t->getMessage(), $t->getCode(), $t); + } + + if ($handler instanceof RoutedRequestHandler) { + $handler->setRouteAttributeName($this->routeAttributeName); + } + return $handler->handle($request); + } +} diff --git a/implementation/18-caching/src/Http/RoutedRequestHandler.php b/implementation/18-caching/src/Http/RoutedRequestHandler.php new file mode 100644 index 0000000..a7407c9 --- /dev/null +++ b/implementation/18-caching/src/Http/RoutedRequestHandler.php @@ -0,0 +1,10 @@ +pipeline->dispatch($request); + } + + public function run(): void + { + $request = $this->requestFactory->fromGlobals(); + $response = $this->handle($request); + $this->emitter->emit($response); + } +} diff --git a/implementation/18-caching/src/Middleware/Cache.php b/implementation/18-caching/src/Middleware/Cache.php new file mode 100644 index 0000000..8460761 --- /dev/null +++ b/implementation/18-caching/src/Middleware/Cache.php @@ -0,0 +1,38 @@ +getMethod() !== 'GET') { + return $handler->handle($request); + } + $keyHash = base64_encode($request->getUri()->getPath()); + $result = $this->cache->get( + $keyHash, + fn () => $this->serializer::toString($handler->handle($request)), + 300 + ); + assert(is_string($result)); + return $this->serializer::fromString($result); + } +} diff --git a/implementation/18-caching/src/Model/MarkdownPage.php b/implementation/18-caching/src/Model/MarkdownPage.php new file mode 100644 index 0000000..df244fd --- /dev/null +++ b/implementation/18-caching/src/Model/MarkdownPage.php @@ -0,0 +1,13 @@ +cache->get( + $key, + fn () => $this->repo->all(), + 300 + ); + assert(is_array($result)); + foreach ($result as $page) { + assert($page instanceof MarkdownPage); + } + return $result; + } + + public function byName(string $name): MarkdownPage + { + $key = base64_encode(self::class . 'byName' . $name); + $result = $this->cache->get( + $key, + fn () => $this->repo->byName($name), + 300 + ); + assert($result instanceof MarkdownPage); + return $result; + } +} diff --git a/implementation/18-caching/src/Repository/FileSystemMarkdownPageRepo.php b/implementation/18-caching/src/Repository/FileSystemMarkdownPageRepo.php new file mode 100644 index 0000000..cca350e --- /dev/null +++ b/implementation/18-caching/src/Repository/FileSystemMarkdownPageRepo.php @@ -0,0 +1,61 @@ +dataPath . '*.md'); + if ($files === false) { + throw new InternalServerError('cannot read pages'); + } + return array_map(function (string $filename) { + $content = file_get_contents($filename); + if ($content === false) { + throw new InternalServerError('cannot read pages'); + } + $idAndTitle = str_replace([$this->dataPath, '.md'], ['', ''], $filename); + return new MarkdownPage( + (int) substr($idAndTitle, 0, 2), + substr($idAndTitle, 3), + $content + ); + }, $files); + } + + public function byName(string $name): MarkdownPage + { + $pages = array_values( + array_filter( + $this->all(), + fn (MarkdownPage $p) => $p->title === $name, + ) + ); + + if (count($pages) !== 1) { + throw new NotFound; + } + + return $pages[0]; + } +} diff --git a/implementation/18-caching/src/Repository/MarkdownPageRepo.php b/implementation/18-caching/src/Repository/MarkdownPageRepo.php new file mode 100644 index 0000000..0792d32 --- /dev/null +++ b/implementation/18-caching/src/Repository/MarkdownPageRepo.php @@ -0,0 +1,15 @@ +engine->render($template, $data); + } +} diff --git a/implementation/18-caching/src/Template/ParsedownParser.php b/implementation/18-caching/src/Template/ParsedownParser.php new file mode 100644 index 0000000..2ffd287 --- /dev/null +++ b/implementation/18-caching/src/Template/ParsedownParser.php @@ -0,0 +1,17 @@ +parser->parse($markdown); + } +} diff --git a/implementation/18-caching/src/Template/Renderer.php b/implementation/18-caching/src/Template/Renderer.php new file mode 100644 index 0000000..ff916ed --- /dev/null +++ b/implementation/18-caching/src/Template/Renderer.php @@ -0,0 +1,11 @@ + $data + */ + public function render(string $template, array $data = []): string; +} diff --git a/implementation/18-caching/templates/hello.html b/implementation/18-caching/templates/hello.html new file mode 100644 index 0000000..15a4cd2 --- /dev/null +++ b/implementation/18-caching/templates/hello.html @@ -0,0 +1,6 @@ +{{> partials/head }} +
+

Hello {{name}}

+

The time is {{now}}

+
+{{> partials/foot }} diff --git a/implementation/18-caching/templates/page.html b/implementation/18-caching/templates/page.html new file mode 100644 index 0000000..c3c5284 --- /dev/null +++ b/implementation/18-caching/templates/page.html @@ -0,0 +1,5 @@ +{{> partials/head }} +
+ {{{content}}} +
+{{> partials/foot }} diff --git a/implementation/18-caching/templates/page/list.html b/implementation/18-caching/templates/page/list.html new file mode 100644 index 0000000..bf42348 --- /dev/null +++ b/implementation/18-caching/templates/page/list.html @@ -0,0 +1,19 @@ + + + + + Pages + + + +
+ +
+ + \ No newline at end of file diff --git a/implementation/18-caching/templates/page/show.html b/implementation/18-caching/templates/page/show.html new file mode 100644 index 0000000..abe295e --- /dev/null +++ b/implementation/18-caching/templates/page/show.html @@ -0,0 +1,17 @@ + + + + + {{title}} + + + + + + +
+ {{{content}}} +
+ + \ No newline at end of file diff --git a/implementation/18-caching/templates/pagelist.html b/implementation/18-caching/templates/pagelist.html new file mode 100644 index 0000000..538e2c4 --- /dev/null +++ b/implementation/18-caching/templates/pagelist.html @@ -0,0 +1,11 @@ +{{> partials/head }} +
+ +
+{{> partials/foot }} diff --git a/implementation/18-caching/templates/partials/foot.html b/implementation/18-caching/templates/partials/foot.html new file mode 100644 index 0000000..17c7245 --- /dev/null +++ b/implementation/18-caching/templates/partials/foot.html @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/implementation/18-caching/templates/partials/head.html b/implementation/18-caching/templates/partials/head.html new file mode 100644 index 0000000..421d387 --- /dev/null +++ b/implementation/18-caching/templates/partials/head.html @@ -0,0 +1,11 @@ + + + + + No Framework: {{title}} + + + + + +