Passed
Push — master ( e1d378...f1a11e )
by Vitaliy
11:08 queued 21s
created

Serializer::prepareDenormalizer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
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\Serializer;
15
16
use FiveLab\Component\Resource\Resource\ResourceInterface;
17
use FiveLab\Component\Resource\Serializer\Events\AfterDenormalizationEvent;
18
use FiveLab\Component\Resource\Serializer\Events\AfterNormalizationEvent;
19
use FiveLab\Component\Resource\Serializer\Events\BeforeDenormalizationEvent;
20
use FiveLab\Component\Resource\Serializer\Events\BeforeNormalizationEvent;
21
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
22
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
23
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
24
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
25
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
26
use Symfony\Component\Serializer\Serializer as SymfonySerializer;
27
28
/**
29
 * Override the default serializer for add ability for adding dynamically
30
 * normalizers before serialization and deserialization processes.
31
 *
32
 * @author Vitaliy Zhuk <[email protected]>
33
 */
34
class Serializer extends SymfonySerializer implements SerializerInterface
35
{
36
    /**
37
     * @var EventDispatcherInterface
38
     */
39
    private $eventDispatcher;
40
41
    /**
42
     * Constructor.
43
     *
44
     * @param array                    $normalizers
45
     * @param array                    $encoders
46
     * @param EventDispatcherInterface $eventDispatcher
47
     */
48 8
    public function __construct(
49
        array $normalizers,
50
        array $encoders,
51
        EventDispatcherInterface $eventDispatcher
52
    ) {
53 8
        parent::__construct($normalizers, $encoders);
54
55 8
        $this->eventDispatcher = $eventDispatcher;
56 8
    }
57
58
    /**
59
     * {@inheritdoc}
60
     *
61
     * @throws \Exception
62
     */
63 4
    public function normalize($data, $format = null, array $context = [])
64
    {
65 4
        if ($data instanceof ResourceInterface) {
66 4
            $event = new BeforeNormalizationEvent($data, (string) $format, $context);
67 4
            $this->eventDispatcher->dispatch(SerializationEvents::BEFORE_NORMALIZATION, $event);
68
        }
69
70 4
        $countNormalizers = 0;
71
72 4 View Code Duplication
        if (\array_key_exists('normalizers', $context)) {
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...
73
            /** @var NormalizerInterface[] $normalizers */
74 2
            $normalizers = \array_reverse($context['normalizers']);
75
76 2
            foreach ($normalizers as $normalizer) {
77 2
                if ($normalizer instanceof NormalizerInterface) {
78 2
                    $countNormalizers++;
79
80 2
                    $this->prepareNormalizer($normalizer);
81 2
                    \array_unshift($this->normalizers, $normalizer);
82
                }
83
            }
84
        }
85
86
        try {
87 4
            $normalized = parent::normalize($data, $format, $context);
88 3
        } finally {
89 4
            for ($i = 0; $i < $countNormalizers; $i++) {
0 ignored issues
show
Unused Code introduced by
$i = 0; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
Bug introduced by
The variable $i 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...
90 2
                \array_shift($this->normalizers);
91
            }
92
        }
93
94 3 View Code Duplication
        if ($data instanceof ResourceInterface) {
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 3
            $event = new AfterNormalizationEvent($data, $normalized, (string) $format, $context);
96 3
            $this->eventDispatcher->dispatch(SerializationEvents::AFTER_NORMALIZATION, $event);
97
        }
98
99 3
        return $normalized;
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105 4
    public function denormalize($data, $type, $format = null, array $context = [])
106
    {
107 4 View Code Duplication
        if (\is_a($type, ResourceInterface::class, true)) {
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...
108 4
            $event = new BeforeDenormalizationEvent($data, $type, $format, $context);
109 4
            $this->eventDispatcher->dispatch(SerializationEvents::BEFORE_DENORMALIZATION, $event);
110
        }
111
112 4
        $countDenormalizers = 0;
113
114 4 View Code Duplication
        if (\array_key_exists('normalizers', $context)) {
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...
115
            /** @var NormalizerInterface[] $normalizers */
116 2
            $normalizers = \array_reverse($context['normalizers']);
117
118 2
            foreach ($normalizers as $normalizer) {
119 2
                if ($normalizer instanceof DenormalizerInterface) {
120 2
                    $countDenormalizers++;
121
122 2
                    $this->prepareDenormalizer($normalizer);
123 2
                    \array_unshift($this->normalizers, $normalizer);
124
                }
125
            }
126
        }
127
128
        try {
129 4
            $denormalized = parent::denormalize($data, $type, $format, $context);
130 3
        } finally {
131 4
            for ($i = 0; $i < $countDenormalizers; $i++) {
0 ignored issues
show
Unused Code introduced by
$i = 0; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
Bug introduced by
The variable $i 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...
132 2
                \array_shift($this->normalizers);
133
            }
134
        }
135
136 3 View Code Duplication
        if (\is_a($type, ResourceInterface::class, true)) {
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...
137 3
            $event = new AfterDenormalizationEvent($data, $denormalized, (string) $format, $context);
0 ignored issues
show
Documentation introduced by
$denormalized is of type object|array, but the function expects a object<FiveLab\Component...urce\ResourceInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
138 3
            $this->eventDispatcher->dispatch(SerializationEvents::AFTER_DENORMALIZATION, $event);
139
        }
140
141 3
        return $denormalized;
142
    }
143
144
    /**
145
     * Prepare normalizer
146
     *
147
     * @param NormalizerInterface $normalizer
148
     */
149 2
    private function prepareNormalizer(NormalizerInterface $normalizer): void
150
    {
151 2
        if ($normalizer instanceof NormalizerAwareInterface) {
152 2
            $normalizer->setNormalizer($this);
153
        }
154 2
    }
155
156
    /**
157
     * Prepare denormalizer
158
     *
159
     * @param DenormalizerInterface $denormalizer
160
     */
161 2
    private function prepareDenormalizer(DenormalizerInterface $denormalizer): void
162
    {
163 2
        if ($denormalizer instanceof DenormalizerAwareInterface) {
164 2
            $denormalizer->setDenormalizer($this);
165
        }
166 2
    }
167
}
168