Passed
Push — master ( 928c25...8579cb )
by Gerrit
02:16
created

ArgumentCompiler::buildArguments()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 2
dl 0
loc 20
ccs 8
cts 8
cp 1
crap 3
rs 9.6
c 0
b 0
f 0
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\Services;
14
15
use Addiks\SymfonyGenerics\Services\ArgumentCompilerInterface;
16
use Addiks\SymfonyGenerics\Arguments\ArgumentFactory\ArgumentFactory;
17
use Addiks\SymfonyGenerics\Arguments\Argument;
18
use Symfony\Component\HttpFoundation\Request;
19
use Webmozart\Assert\Assert;
20
use ErrorException;
21
use ReflectionType;
22
use ReflectionFunctionAbstract;
23
use ReflectionParameter;
24
use ReflectionException;
25
use Symfony\Component\HttpFoundation\RequestStack;
26
use Addiks\SymfonyGenerics\Arguments\ArgumentContextInterface;
27
use InvalidArgumentException;
28
use Addiks\SymfonyGenerics\Controllers\ControllerHelperInterface;
29
30
final class ArgumentCompiler implements ArgumentCompilerInterface
31
{
32
33
    /**
34
     * @var ArgumentFactory
35
     */
36
    private $argumentFactory;
37
38
    /**
39
     * @var RequestStack
40
     */
41
    private $requestStack;
42
43
    /**
44
     * @var ArgumentContextInterface
45
     */
46
    private $argumentContext;
47
48
    /**
49
     * @var ControllerHelperInterface
50
     */
51
    private $controllerHelper;
52
53 11
    public function __construct(
54
        ArgumentFactory $argumentFactory,
55
        RequestStack $requestStack,
56
        ArgumentContextInterface $argumentContext,
57
        ControllerHelperInterface $controllerHelper
58
    ) {
59 11
        $this->argumentFactory = $argumentFactory;
60 11
        $this->requestStack = $requestStack;
61 11
        $this->argumentContext = $argumentContext;
62 11
        $this->controllerHelper = $controllerHelper;
63 11
    }
64
65 6
    public function buildArguments(
66
        array $argumentsConfiguration,
67
        array $additionalData = array()
68
    ): array {
69
        /** @var array $argumentValues */
70 6
        $argumentValues = array();
71
72 6
        $this->argumentContext->clear();
73 6
        foreach ($additionalData as $key => $value) {
74 3
            $this->argumentContext->set($key, $value);
75
        }
76
77 6
        foreach ($argumentsConfiguration as $key => $argumentConfiguration) {
78
            /** @var array|string $argumentConfiguration */
79
80 5
            $argumentValues[$key] = $this->resolveArgumentConfiguration($argumentConfiguration);
81
        }
82
83 3
        return $argumentValues;
84
    }
85
86 5
    public function buildCallArguments(
87
        ReflectionFunctionAbstract $routineReflection,
88
        array $argumentsConfiguration,
89
        array $predefinedArguments = array(),
90
        array $additionalData = array()
91
    ): array {
92
        /** @var array<int, mixed> $callArguments */
93 5
        $callArguments = array();
94
95 5
        $this->argumentContext->clear();
96 5
        foreach ($additionalData as $key => $value) {
97 4
            $this->argumentContext->set($key, $value);
98
        }
99
100 5
        foreach ($routineReflection->getParameters() as $index => $parameterReflection) {
101
            /** @var ReflectionParameter $parameterReflection */
102
103 4
            if (isset($predefinedArguments[$index])) {
104 2
                $callArguments[$index] = $predefinedArguments[$index];
105 2
                continue;
106
            }
107
108 4
            $callArguments[$index] = $this->resolveParameterReflection(
109 4
                $parameterReflection,
110 4
                $argumentsConfiguration,
111 4
                $index
112
            );
113
        }
114
115 4
        return $callArguments;
116
    }
117
118
    /**
119
     * @param array|string|bool|null $argumentConfiguration
120
     *
121
     * @return mixed
122
     */
123 8
    private function resolveArgumentConfiguration($argumentConfiguration)
124
    {
125 8
        Assert::oneOf(
126 8
            gettype($argumentConfiguration),
127 8
            ['string', 'array', 'NULL', 'boolean'],
128 8
            "Arguments must be defined as string, array, bool or null!"
129
        );
130
131
        /** @var Argument|null $argument */
132 7
        $argument = null;
0 ignored issues
show
Unused Code introduced by
$argument 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...
133
134 7
        if (is_bool($argumentConfiguration) || is_null($argumentConfiguration)) {
135
            return $argumentConfiguration;
136
137 7
        } else if ($argumentConfiguration === '') {
138
            return '';
139
140 7
        } elseif (is_array($argumentConfiguration)) {
141 2
            Assert::true($this->argumentFactory->understandsArray($argumentConfiguration), sprintf(
142 2
                "Argument '%s' could not be understood!",
143 2
                preg_replace("/\s+/is", "", var_export($argumentConfiguration, true))
144
            ));
145
146 1
            $argument = $this->argumentFactory->createArgumentFromArray($argumentConfiguration);
147
148
        } else {
149 5
            Assert::true($this->argumentFactory->understandsString($argumentConfiguration), sprintf(
150 5
                "Argument '%s' could not be understood!",
151 5
                $argumentConfiguration
152
            ));
153
154 4
            $argument = $this->argumentFactory->createArgumentFromString(trim($argumentConfiguration));
155
        }
156
157 5
        return $argument->resolve();
158
    }
159
160
    /**
161
     * @return mixed
162
     */
163 4
    private function resolveParameterReflection(
164
        ReflectionParameter $parameterReflection,
165
        array $argumentsConfiguration,
166
        int $index
167
    ) {
168
        /** @var string $parameterName */
169 4
        $parameterName = $parameterReflection->getName();
0 ignored issues
show
Bug introduced by
Consider using $parameterReflection->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
170
171
        /** @var string|null $parameterTypeName */
172 4
        $parameterTypeName = $this->getTypeNameFromReflectionParameter($parameterReflection);
173
174 4
        if (isset($argumentsConfiguration[$parameterName])) {
175
            /** @var mixed $value */
176 1
            $value = $this->resolveArgumentConfiguration($argumentsConfiguration[$parameterName]);
177
178 1
            if (!empty($parameterTypeName)) {
179
                if (class_exists($parameterTypeName)) {
180
                    $value = $this->controllerHelper->findEntity($parameterTypeName, $value);
181
                }
182
            }
183
184 1
            return $value;
185
186 3
        } elseif (isset($argumentsConfiguration[$index])) {
187 2
            return $this->resolveArgumentConfiguration($argumentsConfiguration[$index]);
188
189 2
        } elseif ($parameterTypeName === Request::class) {
190 1
            return $this->requestStack->getCurrentRequest();
191
192
        } else {
193 1
            return $this->getDefaultValueFromParameterReflectionSafely($parameterReflection);
194
        }
195
196
        return null;
0 ignored issues
show
Unused Code introduced by
return null; 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...
197
    }
198
199
    /**
200
     * @return mixed
201
     */
202 1
    private function getDefaultValueFromParameterReflectionSafely(ReflectionParameter $parameterReflection)
203
    {
204
        try {
205 1
            return $parameterReflection->getDefaultValue();
206
207 1
        } catch (ReflectionException $exception) {
208
            /** @var string $parameterName */
209 1
            $parameterName = $parameterReflection->getName();
0 ignored issues
show
Bug introduced by
Consider using $parameterReflection->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
210
211
            /** @var ReflectionFunctionAbstract $routineReflection */
212 1
            $routineReflection = $parameterReflection->getDeclaringFunction();
213
214 1
            throw new InvalidArgumentException(sprintf(
215 1
                "Missing argument '%s' for the call to '%s'!",
216 1
                $parameterName,
217 1
                $routineReflection->getName()
218
            ));
219
        }
220
    }
221
222 4
    private function getTypeNameFromReflectionParameter(ReflectionParameter $parameterReflection): ?string
223
    {
224
        /** @var string|null $parameterTypeName */
225 4
        $parameterTypeName = null;
226
227 4
        if ($parameterReflection->hasType()) {
228
            /** @var ReflectionType|null $parameterType */
229 1
            $parameterType = $parameterReflection->getType();
230
231 1
            if ($parameterType instanceof ReflectionType) {
0 ignored issues
show
Bug introduced by
The class ReflectionType does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
232 1
                $parameterTypeName = $parameterType->__toString();
233
            }
234
        }
235
236 4
        return $parameterTypeName;
237
    }
238
239
}
240