Passed
Push — feature/legacy-method-qualifie... ( 284fc0...d9953a )
by Akihito
01:23
created

Name::setName()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 7
c 2
b 0
f 0
dl 0
loc 21
rs 10
cc 4
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\Di;
6
7
use Ray\Di\Di\Named;
8
use Ray\Di\Di\Qualifier;
9
use ReflectionAttribute;
10
use ReflectionClass;
11
use ReflectionException;
12
use ReflectionMethod;
13
use ReflectionParameter;
14
15
use function class_exists;
16
use function is_string;
17
use function preg_match;
18
19
/**
20
 * @psalm-import-type ParameterNameMapping from Types
21
 */
22
final class Name
23
{
24
    /**
25
     * 'Unnamed' name
26
     */
27
    public const ANY = '';
28
29
    private string $name = '';
30
31
    /**
32
     * Named database
33
     *
34
     * format: array<varName, NamedName>
35
     *
36
     * @var ParameterNameMapping
0 ignored issues
show
Bug introduced by
The type Ray\Di\ParameterNameMapping was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
37
     */
38
    private array $names = [];
39
40
    /**
41
     * @param string|ParameterNameMapping $name
42
     */
43
    public function __construct(string|array $name)
44
    {
45
        if (is_string($name)) {
0 ignored issues
show
introduced by
The condition is_string($name) is always false.
Loading history...
46
            $this->setName($name);
47
48
            return;
49
        }
50
51
        $this->names = $name;
0 ignored issues
show
Documentation Bug introduced by
It seems like $name of type array is incompatible with the declared type Ray\Di\ParameterNameMapping of property $names.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
52
    }
53
54
    /**
55
     * Create instance from PHP8 attributes
56
     *
57
     * psalm does not know ReflectionAttribute?? PHPStan produces no type error here.
58
     */
59
    public static function withAttributes(ReflectionMethod $method): ?self
60
    {
61
        $params = $method->getParameters();
62
        $names = [];
63
        foreach ($params as $param) {
64
            /** @var array<ReflectionAttribute> $attributes */
65
            $attributes = $param->getAttributes();
66
            if ($attributes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $attributes of type ReflectionAttribute[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
67
                $name = self::getName($attributes);
68
                $names[$param->name] = $name;
69
            }
70
        }
71
72
        // Legacy: Infer qualifier from method-level attribute for single-parameter methods
73
        if ($names === []) {
74
            /** @psalm-suppress DeprecatedClass */
75
            $names = LegacyMethodQualifierInference::inferNames($method);
76
        }
77
78
        if ($names !== []) {
79
            return new self($names);
80
        }
81
82
        return null;
83
    }
84
85
    /**
86
     * @param non-empty-array<ReflectionAttribute> $attributes
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-array<ReflectionAttribute> at position 0 could not be parsed: Unknown type name 'non-empty-array' at position 0 in non-empty-array<ReflectionAttribute>.
Loading history...
87
     *
88
     * @throws ReflectionException
89
     *
90
     * @psalm-suppress MixedAssignment
91
     * @psalm-suppress MixedArgument
92
     */
93
    private static function getName(array $attributes): string
94
    {
95
        $refAttribute = $attributes[0];
96
        $attribute = $refAttribute->newInstance();
97
        if ($attribute instanceof Named) {
98
            return $attribute->value;
99
        }
100
101
        $isQualifier = (bool) (new ReflectionClass($attribute))->getAttributes(Qualifier::class);
102
        if ($isQualifier) {
103
            return $attribute::class;
104
        }
105
106
        return '';
107
    }
108
109
    public function __invoke(ReflectionParameter $parameter): string
110
    {
111
        // single variable named binding
112
        if ($this->name) {
113
            return $this->name;
114
        }
115
116
        $parameterName = $parameter->name;
117
118
        // multiple variable named binding
119
        return $this->names[$parameterName] ?? $this->names[self::ANY] ?? self::ANY;
120
    }
121
122
    private function setName(string $name): void
123
    {
124
        // annotation
125
        if (class_exists($name, false)) {
126
            $this->name = $name;
127
128
            return;
129
        }
130
131
        // single name
132
        // @Named(name)
133
        if ($name === self::ANY || preg_match('/^\w+$/', $name)) {
134
            $this->name = $name;
135
136
            return;
137
        }
138
139
        // name list (backward compatibility)
140
        // @Named(varName1=name1, varName2=name2) or toConstructor string format
141
        /** @psalm-suppress DeprecatedClass */
142
        $this->names = LegacyStringParser::parse($name);
0 ignored issues
show
Documentation Bug introduced by
It seems like Ray\Di\LegacyStringParser::parse($name) of type array or array is incompatible with the declared type Ray\Di\ParameterNameMapping of property $names.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
143
    }
144
}
145