Completed
Push — master ( c6433c...a8c688 )
by Gerrit
38:24
created

extractValueFromDataArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 18
c 0
b 0
f 0
ccs 7
cts 8
cp 0.875
rs 9.6666
cc 3
nc 3
nop 2
crap 3.0175
1
<?php
2
/**
3
 * Copyright (C) 2018 Gerrit Addiks.
4
 * This package (including this file) was released under the terms of the GPL-3.0.
5
 * You should have received a copy of the GNU General Public License along with this program.
6
 * If not, see <http://www.gnu.org/licenses/> or send me a mail so i can send you a copy.
7
 *
8
 * @license GPL-3.0
9
 *
10
 * @author Gerrit Addiks <[email protected]>
11
 */
12
13
namespace Addiks\SymfonyGenerics\Controllers;
14
15
use Addiks\SymfonyGenerics\Controllers\ControllerHelperInterface;
16
use InvalidArgumentException;
17
use Webmozart\Assert\Assert;
18
use Symfony\Component\Serializer\SerializerInterface;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\Serializer\Encoder\EncoderInterface;
21
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
22
use DOMDocument;
23
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
24
use ErrorException;
25
26
final class GenericEntityFetchController
27
{
28
29
    /**
30
     * @var ControllerHelperInterface
31
     */
32
    private $controllerHelper;
33
34
    /**
35
     * @var EncoderInterface|null
36
     */
37
    private $encoder;
38
39
    /**
40
     * @var NormalizerInterface|null
41
     */
42
    private $normalizer;
43
44
    /**
45
     * @var array|null
46
     */
47
    private $dataTemplate;
48
49
    /**
50
     * @var string|null
51
     */
52
    private $authorizationAttribute;
53
54
    /**
55
     * @var string
56
     */
57
    private $entityClass;
58
59
    /**
60
     * @var string
61
     */
62
    private $format;
63
64 11
    public function __construct(
65
        ControllerHelperInterface $controllerHelper,
66
        array $options
67
    ) {
68 11
        Assert::null($this->controllerHelper);
69 11
        Assert::keyExists($options, 'entity-class');
70
71 10
        $options = array_merge([
72 10
            'format' => 'json',
73
            'encoder' => null,
74
            'normalizer' => null,
75
            'data-template' => null,
76
            'authorization-attribute' => null
77 10
        ], $options);
78
79 10
        Assert::true(is_null($options['encoder']) || $options['encoder'] instanceof EncoderInterface);
80 9
        Assert::true(is_null($options['normalizer']) || $options['normalizer'] instanceof NormalizerInterface);
81 8
        Assert::classExists($options['entity-class']);
82
83 7
        $this->controllerHelper = $controllerHelper;
84 7
        $this->encoder = $options['encoder'];
85 7
        $this->normalizer = $options['normalizer'];
86 7
        $this->entityClass = $options['entity-class'];
87 7
        $this->format = $options['format'];
88 7
        $this->dataTemplate = $options['data-template'];
89 7
        $this->authorizationAttribute = $options['authorization-attribute'];
90 7
    }
91
92 6
    public function fetchEntity(string $entityId): Response
93
    {
94
        /** @var object|null $entity */
95 6
        $entity = $this->controllerHelper->findEntity($this->entityClass, $entityId);
96
97 6
        if (is_null($entity)) {
98 1
            throw new InvalidArgumentException(sprintf(
99 1
                "Could not find entity with id '%s'!",
100 1
                $entityId
101
            ));
102
        }
103
104 5
        if (!empty($this->authorizationAttribute)) {
105 1
            $this->controllerHelper->denyAccessUnlessGranted($this->authorizationAttribute, $entity);
106
        }
107
108
        /** @var array $normalizedEntity */
109 4
        $normalizedEntity = array();
0 ignored issues
show
Unused Code introduced by
$normalizedEntity is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
110
111 4
        if ($this->normalizer instanceof NormalizerInterface) {
112 1
            $normalizedEntity = $this->normalizer->normalize($entity);
113
114
        } else {
115 3
            $normalizer = new ObjectNormalizer();
116
117 3
            $normalizedEntity = $normalizer->normalize($entity);
118
        }
119
120 4
        if (!is_array($normalizedEntity)) {
121 1
            throw new ErrorException("Result of normalize process must be an array!");
122
        }
123
124 3
        if (!is_null($this->dataTemplate)) {
125 2
            $normalizedEntity = $this->applyDataTemplate($normalizedEntity, $this->dataTemplate);
126
        }
127
128
        /** @var string $serializedEntity */
129 2
        $serializedEntity = "";
0 ignored issues
show
Unused Code introduced by
$serializedEntity is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
130
131 2
        if ($this->encoder instanceof EncoderInterface) {
132
            $serializedEntity = $this->encoder->encode($normalizedEntity, $this->format);
133
134
        } else {
135 2
            $serializedEntity = json_encode($normalizedEntity);
136
        }
137
138 2
        return new Response($serializedEntity);
139
    }
140
141 2
    private function applyDataTemplate(array $data, array $dataTemplate): array
142
    {
143
        /** @var array $result */
144 2
        $result = array();
145
146 2
        foreach ($dataTemplate as $key => $templateEntry) {
147
            /** @var string|array $templateEntry */
148
149
            /** @var mixed $entryResult */
150 2
            $entryResult = null;
0 ignored issues
show
Unused Code introduced by
$entryResult is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
151
152 2
            if (is_string($templateEntry)) {
153 2
                $entryResult = $this->extractValueFromDataArray($data, explode(".", $templateEntry));
154
155 1
            } elseif (is_array($templateEntry)) {
156
                $entryResult = $this->applyDataTemplate($data, $templateEntry);
157
158
            } else {
159 1
                throw new ErrorException("Invalid entry for data-template, must be string or array!");
160
            }
161
162 2
            $result[$key] = $entryResult;
163
        }
164
165 1
        return $result;
166
    }
167
168
    /**
169
     * @return mixed
170
     */
171 2
    private function extractValueFromDataArray(array $data, array $path)
172
    {
173
        /** @var string $key */
174 2
        $key = array_shift($path);
175
176
        /** @var mixed $value */
177 2
        $value = null;
178
179 2
        if (isset($data[$key])) {
180 2
            $value = $data[$key];
181
182 2
            if (!empty($path)) {
183
                $value = $this->extractValueFromDataArray($value, $path);
184
            }
185
        }
186
187 2
        return $value;
188
    }
189
190
}
191