PaginatedCollectionObjectNormalizer::normalize()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 11
cts 11
cp 1
rs 9.552
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 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 PaginatedCollectionObjectNormalizer implements NormalizerInterface, NormalizerAwareInterface
27
{
28
    use NormalizerAwareTrait;
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 2
    public function supportsNormalization($data, $format = null): bool
34
    {
35 2
        return $data instanceof PaginatedResourceCollection;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     *
41
     * @param PaginatedResourceCollection $object
42
     */
43 1
    public function normalize($object, $format = null, array $context = []): array
44
    {
45 1
        $normalizedItems = [];
46
47 1
        foreach ($object as $item) {
48 1
            $normalizedItems[] = $this->normalizer->normalize($item, $format, $context);
49
        }
50
51 1
        $normalizedRelations = $this->normalizer->normalize($object->getRelations(), $format, $context);
52
53
        return [
54
            'state'     => [
55 1
                'page'   => $object->getPage(),
56 1
                'limit'  => $object->getLimit(),
57 1
                'pages'  => (int) (\ceil($object->getTotal() / $object->getLimit())),
58 1
                'total'  => $object->getTotal(),
59 1
                '_links' => $normalizedRelations,
60
            ],
61
            '_embedded' => [
62 1
                'items' => $normalizedItems,
63
            ],
64
        ];
65
    }
66
}
67