UseStatements::existing()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 10
cc 4
nc 3
nop 0
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cerbero\Enum\Services;
6
7
use ArrayIterator;
8
use IteratorAggregate;
9
use Traversable;
10
11
use function Cerbero\Enum\className;
12
use function Cerbero\Enum\yieldLines;
13
14
/**
15
 * The use statements collector.
16
 *
17
 * @implements IteratorAggregate<string, class-string>
18
 */
19
class UseStatements implements IteratorAggregate
20
{
21
    /**
22
     * The regular expression to extract the use statements already present on the enum.
23
     *
24
     * @var string
25
     */
26
    public const RE_STATEMENT = '~^use\s+([^\s;]+)(?:\s+as\s+([^;]+))?~i';
27
28
    /**
29
     * Instantiate the class.
30
     *
31
     * @param Inspector<\UnitEnum> $inspector
32
     */
33 4
    public function __construct(
34
        protected Inspector $inspector,
35
        protected bool $includeExisting,
36 4
    ) {}
37
38
    /**
39
     * Retrieve the sorted, iterable use statements.
40
     *
41
     * @return ArrayIterator<string, class-string>
42
     */
43 4
    public function getIterator(): Traversable
44
    {
45 4
        $useStatements = $this->all();
46
47 4
        asort($useStatements);
48
49 4
        return new ArrayIterator($useStatements);
50
    }
51
52
    /**
53
     * Retrieve all the use statements.
54
     *
55
     * @return array<string, class-string>
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string, class-string> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<string, class-string>.
Loading history...
56
     */
57 4
    public function all(): array
58
    {
59 4
        return $this->existing();
60
    }
61
62
    /**
63
     * Retrieve the use statements already present on the enum.
64
     *
65
     * @return array<string, class-string>
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string, class-string> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<string, class-string>.
Loading history...
66
     */
67 4
    public function existing(): array
68
    {
69 4
        $useStatements = [];
70
71 4
        foreach (yieldLines($this->inspector->filename()) as $line) {
72 4
            if (strpos($line, 'enum') === 0) {
73 4
                break;
74
            }
75
76 4
            if (preg_match(static::RE_STATEMENT, $line, $matches)) {
77 4
                $useStatements[$matches[2] ?? className($matches[1])] = $matches[1];
78
            }
79
        }
80
81
        /** @var array<string, class-string> */
82 4
        return $useStatements;
83
    }
84
}
85