Passed
Push — master ( 6be800...01ae67 )
by
unknown
02:02
created

CollectionNormalizer::normalize()   C

Complexity

Conditions 7
Paths 25

Size

Total Lines 28
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 13
nc 25
nop 3
1
<?php
2
/*
3
 * This file is part of AppBundle the package.
4
 *
5
 * (c) Ruslan Muriev <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace RonteLtd\JsonApiBundle\Serializer\Normalizer;
12
13
use RonteLtd\JsonApiBundle\Serializer\Exception\LogicException;
14
use RonteLtd\JsonApiBundle\Serializer\Mapping\Factory\MetadataFactoryInterface;
15
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
16
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
17
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
18
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
19
20
/**
21
 * Class CollectionNormalizer
22
 *
23
 * @package RonteLtd\JsonApiBundle\Serializer\Normalizer
24
 * @author Ruslan Muriev <[email protected]>
25
 */
26
class CollectionNormalizer extends AbstractNormalizer
27
{
28
    /**
29
     * ObjectNormalizer constructor.
30
     *
31
     * @param MetadataFactoryInterface $metadataFactory
32
     * @param ClassMetadataFactoryInterface|null $classMetadataFactory
33
     * @param NameConverterInterface|null $nameConverter
34
     */
35
    public function __construct(MetadataFactoryInterface $metadataFactory, ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null)
36
    {
37
        parent::__construct($classMetadataFactory, $nameConverter);
38
39
        $this->metadataFactory = $metadataFactory;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function supportsNormalization($data, $format = null)
46
    {
47
        return ($data instanceof Collection);
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function normalize($collection, $format = null, array $context = array())
54
    {
55
        if (!$collection instanceof Collection) {
56
            return $collection;
57
        }
58
59
        if (!empty($collection->getJsonapi())) {
60
            $jsonApiData['jsonapi'] = $collection->getJsonapi();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$jsonApiData was never initialized. Although not strictly required by PHP, it is generally a good practice to add $jsonApiData = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
61
        }
62
63
        if (!empty($collection->getLinks())) {
64
            $jsonApiData['links'] = $collection->getLinks();
0 ignored issues
show
Bug introduced by
The variable $jsonApiData does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
65
        }
66
67
        if (!empty($collection->getMeta())) {
68
            $jsonApiData['meta'] = $collection->getMeta();
69
        }
70
71
//        $jsonApiData['included'] = []; TODO implement
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
72
73
        foreach ($collection as $item) {
74
            if ($this->serializer instanceof NormalizerInterface) {
0 ignored issues
show
Bug introduced by
The class Symfony\Component\Serial...zer\NormalizerInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
75
                $jsonApiData['data'][] = $this->serializer->normalize($item);
76
            }
77
        }
78
79
        return $jsonApiData;
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function supportsDenormalization($data, $type, $format = null)
86
    {
87
        return false;
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function denormalize($data, $class, $format = null, array $context = array())
94
    {
95
        throw new LogicException(sprintf('Cannot denormalize with "%s".', \JsonSerializable::class));
96
    }
97
}