Passed
Pull Request — master (#2)
by Vitaliy
03:08 queued 36s
created

PaginatedCollectionNormalizer   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
c 0
b 0
f 0
dl 0
loc 37
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A supportsNormalization() 0 3 1
A normalize() 0 20 2
1
<?php
2
3
declare(strict_types = 1);
4
5
/*
6
 * This file is part of the FiveLab Resource package
7
 *
8
 * (c) FiveLab
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code
12
 */
13
14
namespace FiveLab\Component\Resource\Serializers\Hateoas\Normalizer;
15
16
use FiveLab\Component\Resource\Resource\PaginatedResourceCollection;
17
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
18
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
19
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
20
21
/**
22
 * The normalizer for normalize paginated resource collection for HATEOAS format.
23
 *
24
 * @author Vitaliy Zhuk <[email protected]>
25
 */
26
class PaginatedCollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface
27
{
28
    use NormalizerAwareTrait;
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function supportsNormalization($data, $format = null): bool
34
    {
35
        return $data instanceof PaginatedResourceCollection;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     *
41
     * @param PaginatedResourceCollection $object
42
     */
43
    public function normalize($object, $format = null, array $context = []): array
44
    {
45
        $normalizedItems = [];
46
47
        foreach ($object as $item) {
48
            $normalizedItems[] = $this->normalizer->normalize($item, $format, $context);
49
        }
50
51
        $normalizedRelations = $this->normalizer->normalize($object->getRelations(), $format, $context);
52
53
        return [
54
            'state'     => [
55
                'page'   => $object->getPage(),
56
                'limit'  => $object->getLimit(),
57
                'pages'  => (int) (\ceil($object->getTotal() / $object->getLimit())),
58
                'total'  => $object->getTotal(),
59
                '_links' => $normalizedRelations,
60
            ],
61
            '_embedded' => [
62
                'items' => $normalizedItems,
63
            ],
64
        ];
65
    }
66
}
67