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

InputAttributeIterator::__invoke()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
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
use function count;
12
13
/**
14
 * Iterator for parameters with Input attribute
15
 */
16
final class InputAttributeIterator
17
{
18
    /**
19
     * Yield parameters that have Input attribute
20
     *
21
     * @param ReflectionMethod $method
22
     *
23
     * @return Generator<string, ReflectionParameter>
24
     */
25
    public function __invoke(ReflectionMethod $method): Generator
26
    {
27
        foreach ($method->getParameters() as $parameter) {
28
            $attributes = $parameter->getAttributes(Input::class);
29
            if (count($attributes) <= 0) {
30
                continue;
31
            }
32
33
            yield $parameter->getName() => $parameter;
34
        }
35
    }
36
37
    /**
38
     * Get Input attribute instance from parameter
39
     *
40
     * @param ReflectionParameter $parameter
41
     *
42
     * @return Input|null
43
     */
44
    public function getInputAttribute(ReflectionParameter $parameter): Input|null
45
    {
46
        $attributes = $parameter->getAttributes(Input::class);
47
        if (count($attributes) === 0) {
48
            return null;
49
        }
50
51
        return $attributes[0]->newInstance();
52
    }
53
54
    /**
55
     * Check if method has any Input attribute parameters
56
     *
57
     * @param ReflectionMethod $method
58
     *
59
     * @return bool
60
     */
61
    public function hasInputParameters(ReflectionMethod $method): bool
62
    {
63
        foreach ($method->getParameters() as $parameter) {
64
            $attributes = $parameter->getAttributes(Input::class);
65
            if (count($attributes) > 0) {
66
                return true;
67
            }
68
        }
69
70
        return false;
71
    }
72
}
73