Passed
Push — master ( 30392d...72ef56 )
by Gerrit
02:00
created

ArgumentCompiler::resolveParameterReflection()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 9
cts 10
cp 0.9
rs 9.504
c 0
b 0
f 0
cc 4
nc 4
nop 3
crap 4.016
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
29
final class ArgumentCompiler implements ArgumentCompilerInterface
30
{
31
32
    /**
33
     * @var ArgumentFactory
34
     */
35
    private $argumentFactory;
36
37
    /**
38
     * @var RequestStack
39
     */
40
    private $requestStack;
41
42
    /**
43
     * @var ArgumentContextInterface
44
     */
45
    private $argumentContext;
46
47 10
    public function __construct(
48
        ArgumentFactory $argumentFactory,
49
        RequestStack $requestStack,
50
        ArgumentContextInterface $argumentContext
51
    ) {
52 10
        $this->argumentFactory = $argumentFactory;
53 10
        $this->requestStack = $requestStack;
54 10
        $this->argumentContext = $argumentContext;
55 10
    }
56
57 6
    public function buildArguments(
58
        array $argumentsConfiguration,
59
        Request $request,
60
        array $additionalData = array()
61
    ): array {
62
        /** @var array $argumentValues */
63 6
        $argumentValues = array();
64
65 6
        $this->argumentContext->clear();
66 6
        foreach ($additionalData as $key => $value) {
67 3
            $this->argumentContext->set($key, $value);
68
        }
69
70 6
        foreach ($argumentsConfiguration as $key => $argumentConfiguration) {
71
            /** @var array|string $argumentConfiguration */
72
73 5
            $argumentValues[$key] = $this->resolveArgumentConfiguration($argumentConfiguration);
74
        }
75
76 3
        return $argumentValues;
77
    }
78
79 4
    public function buildCallArguments(
80
        ReflectionFunctionAbstract $routineReflection,
81
        array $argumentsConfiguration,
82
        Request $request,
83
        array $predefinedArguments = array(),
84
        array $additionalData = array()
85
    ): array {
86
        /** @var array<int, mixed> $callArguments */
87 4
        $callArguments = array();
88
89 4
        $this->argumentContext->clear();
90 4
        foreach ($additionalData as $key => $value) {
91 3
            $this->argumentContext->set($key, $value);
92
        }
93
94 4
        foreach ($routineReflection->getParameters() as $index => $parameterReflection) {
95
            /** @var ReflectionParameter $parameterReflection */
96
97 3
            if (isset($predefinedArguments[$index])) {
98 2
                $callArguments[$index] = $predefinedArguments[$index];
99 2
                continue;
100
            }
101
102 3
            $callArguments[$index] = $this->resolveParameterReflection(
103 3
                $parameterReflection,
104 3
                $argumentsConfiguration,
105 3
                $index
106
            );
107
        }
108
109 3
        return $callArguments;
110
    }
111
112
    /**
113
     * @param array|string $argumentConfiguration
114
     *
115
     * @return mixed
116
     */
117 7
    private function resolveArgumentConfiguration($argumentConfiguration)
118
    {
119 7
        Assert::true(
120 7
            is_array($argumentConfiguration) || is_string($argumentConfiguration),
121 7
            "Arguments must be defined as string or array!"
122
        );
123
124
        /** @var Argument|null $argument */
125 6
        $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...
126
127 6
        if (is_array($argumentConfiguration)) {
128 2
            Assert::true($this->argumentFactory->understandsArray($argumentConfiguration), sprintf(
129 2
                "Argument '%s' could not be understood!",
130 2
                preg_replace("/\s+/is", "", var_export($argumentConfiguration, true))
131
            ));
132
133 1
            $argument = $this->argumentFactory->createArgumentFromArray($argumentConfiguration);
134
135
        } else {
136 4
            Assert::true($this->argumentFactory->understandsString($argumentConfiguration), sprintf(
137 4
                "Argument '%s' could not be understood!",
138 4
                $argumentConfiguration
139
            ));
140
141 3
            $argument = $this->argumentFactory->createArgumentFromString(trim($argumentConfiguration));
142
        }
143
144 4
        return $argument->resolve();
145
    }
146
147
    /**
148
     * @return mixed
149
     */
150 3
    private function resolveParameterReflection(
151
        ReflectionParameter $parameterReflection,
152
        array $argumentsConfiguration,
153
        int $index
154
    ) {
155
        /** @var string $parameterName */
156 3
        $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...
157
158
        /** @var string|null $parameterTypeName */
159 3
        $parameterTypeName = $this->getTypeNameFromReflectionParameter($parameterReflection);
160
161 3
        if (isset($argumentsConfiguration[$parameterName])) {
162
            return $this->resolveArgumentConfiguration($argumentsConfiguration[$parameterName]);
163
164 3
        } elseif (isset($argumentsConfiguration[$index])) {
165 2
            return $this->resolveArgumentConfiguration($argumentsConfiguration[$index]);
166
167 2
        } elseif ($parameterTypeName === Request::class) {
168 1
            return $this->requestStack->getCurrentRequest();
169
170
        } else {
171 1
            return $this->getDefaultValueFromParameterReflectionSafely($parameterReflection);
172
        }
173
174
        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...
175
    }
176
177
    /**
178
     * @return mixed
179
     */
180 1
    private function getDefaultValueFromParameterReflectionSafely(ReflectionParameter $parameterReflection)
181
    {
182
        try {
183 1
            return $parameterReflection->getDefaultValue();
184
185 1
        } catch (ReflectionException $exception) {
186
            /** @var string $parameterName */
187 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...
188
189
            /** @var ReflectionFunctionAbstract $routineReflection */
190 1
            $routineReflection = $parameterReflection->getDeclaringFunction();
191
192 1
            throw new InvalidArgumentException(sprintf(
193 1
                "Missing argument '%s' for the call to '%s'!",
194 1
                $parameterName,
195 1
                $routineReflection->getName()
196
            ));
197
        }
198
    }
199
200 3
    private function getTypeNameFromReflectionParameter(ReflectionParameter $parameterReflection): ?string
201
    {
202
        /** @var string|null $parameterTypeName */
203 3
        $parameterTypeName = null;
204
205 3
        if ($parameterReflection->hasType()) {
206
            /** @var ReflectionType|null $parameterType */
207 1
            $parameterType = $parameterReflection->getType();
208
209 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...
210 1
                $parameterTypeName = $parameterType->__toString();
211
            }
212
        }
213
214 3
        return $parameterTypeName;
215
    }
216
217
}
218