Skip to content

Commit

Permalink
Enable cache for Format I Entity
Browse files Browse the repository at this point in the history
  • Loading branch information
jbelien committed Jun 20, 2019
1 parent c11fbcf commit 47f3fb3
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 4 deletions.
1 change: 1 addition & 0 deletions src/App/ConfigProvider.php
Expand Up @@ -36,6 +36,7 @@ public function getDependencies(): array
],
'factories' => [
Handler\FormatI\CandidateHandler::class => Handler\FormatI\CandidateHandlerFactory::class,
Handler\FormatI\EntityHandler::class => Handler\FormatI\EntityHandlerFactory::class,
],
];
}
Expand Down
35 changes: 31 additions & 4 deletions src/App/Handler/FormatI/EntityHandler.php
@@ -1,6 +1,6 @@
<?php

declare(strict_types=1);
declare (strict_types = 1);

namespace App\Handler\FormatI;

Expand All @@ -9,11 +9,36 @@
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Router\RouteResult;
use App\Cache;

class EntityHandler implements RequestHandlerInterface
{
private $cache;
private $headers = [
'Cache-Control' => 'max-age=86400, public',
];

public function __construct(bool $cache)
{
$this->cache = $cache;
}

public function handle(ServerRequestInterface $request): ResponseInterface
{
$routeResult = $request->getAttribute(RouteResult::class);

if ($this->cache === true) {
$path = Cache::path($routeResult->getMatchedRouteName(), $routeResult->getMatchedParams());
$cache = new Cache($path);

$json = $cache->get();

if (!is_null($json)) {
return new JsonResponse($json, 200, $this->headers);
}
}

$year = $request->getAttribute('year');
$type = $request->getAttribute('type');

Expand All @@ -22,8 +47,10 @@ public function handle(ServerRequestInterface $request): ResponseInterface

$entity = new Entity(intval($year), $type, $test);

return new JsonResponse($entity->getArray(), 200, [
'Cache-Control' => 'max-age=86400, public',
]);
if ($this->cache === true && isset($cache)) {
$cache->set($entity->getArray());
}

return new JsonResponse($entity->getArray(), 200, $this->headers);
}
}
21 changes: 21 additions & 0 deletions src/App/Handler/FormatI/EntityHandlerFactory.php
@@ -0,0 +1,21 @@
<?php

declare (strict_types = 1);

namespace App\Handler\FormatI;

use App\Cache;
use Psr\Container\ContainerInterface;
use Psr\Http\Server\RequestHandlerInterface;

class EntityHandlerFactory
{
public function __invoke(ContainerInterface $container): RequestHandlerInterface
{
$config = $container->get('config');

$cache = $config[Cache::ENABLE_CACHE] ?? false;

return new EntityHandler($cache);
}
}

0 comments on commit 47f3fb3

Please sign in to comment.