-
Notifications
You must be signed in to change notification settings - Fork 187
/
Copy pathQueryController.php
executable file
·62 lines (50 loc) · 1.67 KB
/
QueryController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace UI\Http\Rest\Controller;
use App\Shared\Application\Query\Collection;
use App\Shared\Application\Query\Item;
use App\Shared\Application\Query\QueryBusInterface;
use App\Shared\Application\Query\QueryInterface;
use UI\Http\Rest\Response\OpenApi;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Throwable;
abstract class QueryController
{
private const CACHE_MAX_AGE = 31_536_000;
public function __construct(
// Year.
private readonly QueryBusInterface $queryBus,
private readonly UrlGeneratorInterface $router
)
{
}
/**
* @throws Throwable
*/
protected function ask(QueryInterface $query): mixed
{
return $this->queryBus->ask($query);
}
protected function jsonCollection(Collection $collection, int $status = OpenApi::HTTP_OK, bool $isImmutable = false): OpenApi
{
$response = OpenApi::collection($collection, $status);
$this->decorateWithCache($response, $collection, $isImmutable);
return $response;
}
protected function json(Item $resource, int $status = OpenApi::HTTP_OK): OpenApi
{
return OpenApi::one($resource, $status);
}
protected function route(string $name, array $params = []): string
{
return $this->router->generate($name, $params);
}
private function decorateWithCache(OpenApi $response, Collection $collection, bool $isImmutable): void
{
if ($isImmutable && $collection->limit === \count($collection->data)) {
$response
->setMaxAge(self::CACHE_MAX_AGE)
->setSharedMaxAge(self::CACHE_MAX_AGE);
}
}
}