Passed
Push — master ( eb8ece...8a2d63 )
by Derek Stephen
01:41
created

ApiCollectionPaginator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 41
c 1
b 0
f 0
dl 0
loc 79
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
B process() 0 67 6
A __construct() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Bone\BoneDoctrine\Middleware;
6
7
use Doctrine\Common\Collections\ArrayCollection;
8
use Doctrine\ORM\EntityManagerInterface;
9
use JMS\Serializer\SerializerInterface;
0 ignored issues
show
Bug introduced by
The type JMS\Serializer\SerializerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Laminas\Diactoros\Response\JsonResponse;
0 ignored issues
show
Bug introduced by
The type Laminas\Diactoros\Response\JsonResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
use Psr\Http\Server\MiddlewareInterface;
14
use Psr\Http\Server\RequestHandlerInterface;
15
16
use Symfony\Component\Serializer\Serializer;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Serializer\Serializer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use Symfony\Component\Serializer\Encoder\JsonEncoder;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Serializer\Encoder\JsonEncoder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Serial...alizer\ObjectNormalizer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
20
abstract class ApiCollectionPaginator implements MiddlewareInterface
21
{
22
    public function __construct(
23
        private EntityManagerInterface $entityManager,
24
        private SerializerInterface $serializer,
25
    ) {}
26
27
    abstract public function getEntityClass(): string;
28
    abstract public function getWhereCriteria(): array;
29
    abstract public function getOrderByCriteria(): array;
30
    abstract public function getRequestAttributeName(): string;
31
32
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
33
    {
34
        $params = $request->getQueryParams();
35
        $page = isset($params['page']) ? (int) $params['page'] : 1;
36
        $limit = isset($params['limit']) ? (int) $params['limit'] : 25;
37
        $offset = ($page *  $limit) - $limit;
38
        $entityClass = $this->getEntityClass();
39
        $whereCriteria = $this->getWhereCriteria();
40
        $orderByCriteria = $this->getWhereCriteria();
41
        $requestAttributeName = $this->getRequestAttributeName();
0 ignored issues
show
Unused Code introduced by
The assignment to $requestAttributeName is dead and can be removed.
Loading history...
42
        $entities = $this->entityManager->getRepository($entityClass)->findBy($whereCriteria, $orderByCriteria, $limit, $offset);
43
        $totalRecords = $this->entityManager->getRepository($entityClass)->count($whereCriteria);
44
        $totalPages = (int) ceil($totalRecords / $limit);
45
        $uri = $request->getUri();
46
47
        $hal = [
48
            '_links' => [
49
                'self' => [
50
                    'href' => $uri->getScheme() . '://' . $uri->getHost() . $uri->getPath(),
51
                ],
52
                'first' => [
53
                    'href' => $uri->getScheme() . '://' . $uri->getHost() . $uri->getPath(),
54
                ],
55
            ],
56
        ];
57
58
        if ($page !== 1) {
59
            $hal['_links']['prev'] = [
60
                'href' => $uri->getScheme() . '://' . $uri->getHost() . $uri->getPath() . '?page=' . ($page - 1),
61
            ];
62
        }
63
64
        if ($page !== $totalPages) {
65
            $hal['_links']['next'] = [
66
                'href' => $uri->getScheme() . '://' . $uri->getHost() . $uri->getPath() . '?page=' . ($page + 1),
67
            ];
68
        }
69
70
        $hal['_links']['last'] = [
71
            'href' => $uri->getScheme() . '://' . $uri->getHost() . $uri->getPath() . '?page=' . $totalPages,
72
        ];
73
74
        $hal['_embedded'] = [];
75
76
        $encoders = [new JsonEncoder()];
77
        $normalizers = [new ObjectNormalizer()];
78
        $serializer = new Serializer($normalizers, $encoders);
79
80
//        foreach ($entities as $entity) {
81
            $hal['_embedded'][] = $serializer->serialize($entities, 'json'); //$entity->toArray();
82
//        }
83
84
        $hal['totalPages'] = $totalPages;
85
        $hal['totalRecords'] = $totalRecords;
86
        /** @todo add _self links for entities in collection */
87
        foreach ($hal['_embedded'] as $key => $value) {
88
            $hal['_embedded'][$key]['_links'] = [
89
                'self' => [
90
                    'href' => $uri->getScheme() . '://' . $uri->getHost() . $uri->getPath() . '/' . $value['id'],
91
                ],
92
            ];
93
        }
94
95
        $response = new JsonResponse($hal);
96
        $response = $response->withHeader('Content-Type', 'application/hal+json');
97
98
        return $response;
99
    }
100
}
101