Completed
Push — master ( 04aca3...4b3d1a )
by
unknown
03:17
created

CollectionNormalizer::normalize()   D

Complexity

Conditions 21
Paths 353

Size

Total Lines 74
Code Lines 43

Duplication

Lines 38
Ratio 51.35 %

Importance

Changes 0
Metric Value
dl 38
loc 74
rs 4.0359
c 0
b 0
f 0
cc 21
eloc 43
nc 353
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\JsonApi\Serializer;
15
16
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
17
use ApiPlatform\Core\DataProvider\PaginatorInterface;
18
use ApiPlatform\Core\DataProvider\PartialPaginatorInterface;
19
use ApiPlatform\Core\Exception\RuntimeException;
20
use ApiPlatform\Core\Serializer\ContextTrait;
21
use ApiPlatform\Core\Util\IriHelper;
22
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
23
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
24
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
25
26
/**
27
 * Normalizes collections in the JSON API format.
28
 *
29
 * @author Kevin Dunglas <[email protected]>
30
 * @author Hamza Amrouche <[email protected]>
31
 * @author Baptiste Meyer <[email protected]>
32
 */
33
final class CollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface
34
{
35
    use ContextTrait;
36
    use NormalizerAwareTrait;
37
38
    const FORMAT = 'jsonapi';
39
40
    private $resourceClassResolver;
41
    private $pageParameterName;
42
43
    public function __construct(ResourceClassResolverInterface $resourceClassResolver, string $pageParameterName)
44
    {
45
        $this->resourceClassResolver = $resourceClassResolver;
46
        $this->pageParameterName = $pageParameterName;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function supportsNormalization($data, $format = null)
53
    {
54
        return self::FORMAT === $format && (is_array($data) || ($data instanceof \Traversable));
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function normalize($object, $format = null, array $context = [])
61
    {
62
        $data = [];
63 View Code Duplication
        if (isset($context['api_sub_level'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
64
            foreach ($object as $index => $obj) {
65
                $data[$index] = $this->normalizer->normalize($obj, $format, $context);
66
            }
67
68
            return $data;
69
        }
70
71
        $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null, true);
72
        $context = $this->initContext($resourceClass, $context);
73
        $parsed = IriHelper::parseIri($context['request_uri'] ?? '/', $this->pageParameterName);
74
75
        $currentPage = $lastPage = $itemsPerPage = $pageTotalItems = null;
76 View Code Duplication
        if ($paginated = $isPaginator = $object instanceof PartialPaginatorInterface) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
77
            if ($object instanceof PaginatorInterface) {
78
                $paginated = 1. !== $lastPage = $object->getLastPage();
79
            } else {
80
                $pageTotalItems = (float) count($object);
81
            }
82
83
            $currentPage = $object->getCurrentPage();
84
            $itemsPerPage = $object->getItemsPerPage();
85
        }
86
87
        $data = [
88
            'data' => [],
89
            'links' => [
90
                'self' => IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $paginated ? $currentPage : null),
91
            ],
92
        ];
93
94 View Code Duplication
        if ($paginated) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
            if (null !== $lastPage) {
96
                $data['links']['first'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, 1.);
97
                $data['links']['last'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $lastPage);
98
            }
99
100
            if (1. !== $currentPage) {
101
                $data['links']['prev'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage - 1.);
102
            }
103
104
            if (null !== $lastPage && $currentPage !== $lastPage || null === $lastPage && $pageTotalItems >= $itemsPerPage) {
105
                $data['links']['next'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage + 1.);
106
            }
107
        }
108
109
        foreach ($object as $obj) {
110
            $item = $this->normalizer->normalize($obj, $format, $context);
111
112
            if (!isset($item['data'])) {
113
                throw new RuntimeException('The JSON API document must contain a "data" key.');
114
            }
115
116
            $data['data'][] = $item['data'];
117
        }
118
119 View Code Duplication
        if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
120
            is_array($object) ||
121
            ($paginated = $object instanceof PaginatorInterface) ||
122
            $object instanceof \Countable && !$object instanceof PartialPaginatorInterface
123
        ) {
124
            $data['meta']['totalItems'] = $paginated ? (int) $object->getTotalItems() : count($object);
125
        }
126
127
        if ($isPaginator) {
128
            $data['meta']['itemsPerPage'] = (int) $itemsPerPage;
129
            $data['meta']['currentPage'] = (int) $currentPage;
130
        }
131
132
        return $data;
133
    }
134
}
135