Passed
Pull Request — 1.x (#321)
by Akihito
02:42
created

InputAttributeIterator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 55
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getInputAttribute() 0 8 2
A hasInputParameters() 0 10 3
A __invoke() 0 9 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource\Input;
6
7
use BEAR\Resource\Annotation\Input;
8
use Generator;
9
use ReflectionMethod;
10
use ReflectionParameter;
11
12
use function count;
13
14
/**
15
 * Iterator for parameters with Input attribute
16
 */
17
final class InputAttributeIterator
18
{
19
    /**
20
     * Yield parameters that have Input attribute
21
     *
22
     * @param ReflectionMethod $method
23
     *
24
     * @return Generator<string, ReflectionParameter>
25
     */
26
    public function __invoke(ReflectionMethod $method): Generator
27
    {
28
        foreach ($method->getParameters() as $parameter) {
29
            $attributes = $parameter->getAttributes(Input::class);
30
            if (count($attributes) <= 0) {
31
                continue;
32
            }
33
34
            yield $parameter->getName() => $parameter;
35
        }
36
    }
37
38
    /**
39
     * Get Input attribute instance from parameter
40
     *
41
     * @param ReflectionParameter $parameter
42
     *
43
     * @return Input|null
44
     */
45
    public function getInputAttribute(ReflectionParameter $parameter): Input|null
46
    {
47
        $attributes = $parameter->getAttributes(Input::class);
48
        if (count($attributes) === 0) {
49
            return null;
50
        }
51
52
        return $attributes[0]->newInstance();
53
    }
54
55
    /**
56
     * Check if method has any Input attribute parameters
57
     *
58
     * @param ReflectionMethod $method
59
     *
60
     * @return bool
61
     */
62
    public function hasInputParameters(ReflectionMethod $method): bool
63
    {
64
        foreach ($method->getParameters() as $parameter) {
65
            $attributes = $parameter->getAttributes(Input::class);
66
            if (count($attributes) > 0) {
67
                return true;
68
            }
69
        }
70
71
        return false;
72
    }
73
}
74