Passed
Push — master ( 55fca5...85d75f )
by Kirill
04:44 queued 10s
created

NamedArgumentsInstantiator   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 110
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 43
dl 0
loc 110
rs 10
c 1
b 0
f 0
wmc 13

4 Methods

Rating   Name   Duplication   Size   Complexity  
A instantiate() 0 18 4
A resolveParameter() 0 28 4
A resolveParameters() 0 18 4
A isNamedArgumentsSupported() 0 3 1
1
<?php
2
3
/**
4
 * This file is part of Attributes package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Attributes\Internal\Instantiator;
13
14
use Spiral\Attributes\Internal\Exception;
15
16
/**
17
 * @internal NamedArgumentsInstantiator is an internal library class, please do not use it in your code.
18
 * @psalm-internal Spiral\Attributes
19
 */
20
final class NamedArgumentsInstantiator extends Instantiator
21
{
22
    /**
23
     * @var string
24
     */
25
    private const ERROR_ARGUMENT_NOT_PASSED = '%s::__construct(): Argument #%d ($%s) not passed';
26
27
    /**
28
     * @var string
29
     */
30
    private const ERROR_UNKNOWN_ARGUMENT = 'Unknown named parameter $%s';
31
32
    /**
33
     * @param \ReflectionClass $attr
34
     * @param array $arguments
35
     * @param string $context
36
     * @return object
37
     * @throws \Throwable
38
     */
39
    public function instantiate(\ReflectionClass $attr, array $arguments, string $context): object
40
    {
41
        if ($this->isNamedArgumentsSupported()) {
42
            try {
43
                return $attr->newInstanceArgs($arguments);
44
            } catch (\Throwable $e) {
45
                throw Exception::withLocation($e, $attr->getFileName(), $attr->getStartLine());
46
            }
47
        }
48
49
        $constructor = $this->getConstructor($attr);
50
51
        if ($constructor === null) {
52
            return $attr->newInstanceWithoutConstructor();
53
        }
54
55
        return $attr->newInstanceArgs(
56
            $this->resolveParameters($attr, $constructor, $arguments)
57
        );
58
    }
59
60
    /**
61
     * @return bool
62
     */
63
    private function isNamedArgumentsSupported(): bool
64
    {
65
        return \version_compare(\PHP_VERSION, '8.0') >= 0;
66
    }
67
68
    /**
69
     * @param \ReflectionClass $ctx
70
     * @param \ReflectionMethod $constructor
71
     * @param array $arguments
72
     * @return array
73
     * @throws \Throwable
74
     */
75
    private function resolveParameters(\ReflectionClass $ctx, \ReflectionMethod $constructor, array $arguments): array
76
    {
77
        $passed = [];
78
79
        try {
80
            foreach ($constructor->getParameters() as $parameter) {
81
                $passed[] = $this->resolveParameter($ctx, $parameter, $arguments);
82
            }
83
84
            if (\count($arguments)) {
85
                $message = \sprintf(self::ERROR_UNKNOWN_ARGUMENT, \array_key_first($arguments));
86
                throw new \BadMethodCallException($message);
87
            }
88
        } catch (\Throwable $e) {
89
            throw Exception::withLocation($e, $constructor->getFileName(), $constructor->getStartLine());
90
        }
91
92
        return $passed;
93
    }
94
95
    /**
96
     * @param \ReflectionClass $ctx
97
     * @param \ReflectionParameter $param
98
     * @param array $arguments
99
     * @return mixed
100
     * @throws \Throwable
101
     */
102
    private function resolveParameter(\ReflectionClass $ctx, \ReflectionParameter $param, array &$arguments)
103
    {
104
        switch (true) {
105
            case \array_key_exists($param->getName(), $arguments):
106
                try {
107
                    return $arguments[$param->getName()];
108
                } finally {
109
                    unset($arguments[$param->getName()]);
110
                }
111
112
            case \array_key_exists($param->getPosition(), $arguments):
113
                try {
114
                    return $arguments[$param->getPosition()];
115
                } finally {
116
                    unset($arguments[$param->getPosition()]);
117
                }
118
119
            case $param->isDefaultValueAvailable():
120
                return $param->getDefaultValue();
121
122
            default:
123
                $message = \vsprintf(self::ERROR_ARGUMENT_NOT_PASSED, [
124
                    $ctx->getName(),
125
                    $param->getPosition() + 1,
126
                    $param->getName(),
127
                ]);
128
129
                throw new \ArgumentCountError($message);
130
        }
131
    }
132
}