Passed
Push — main ( e1a72d...629a58 )
by Chema
01:28
created

DocBlockParser::getClassFromMethod()   B

Complexity

Conditions 8
Paths 13

Size

Total Lines 42
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 8.0877

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 22
dl 0
loc 42
ccs 8
cts 9
cp 0.8889
rs 8.4444
c 2
b 0
f 0
cc 8
nc 13
nop 2
crap 8.0877
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\ClassResolver\DocBlockService;
6
7
use Gacela\Framework\AbstractConfig;
8
use Gacela\Framework\AbstractFactory;
9 27
10
final class DocBlockParser
11 27
{
12 1
    public function getClassFromMethod(string $docBlock, string $method): string
13
    {
14
        if ($docBlock === '') {
15 26
            return '';
16
        }
17
18
        if (strcasecmp(substr(PHP_OS, 0, 3), 'WIN') === 0) {
19 26
            $docBlock = str_replace("\n", PHP_EOL, $docBlock);
20 26
        }
21 26
22 26
        $lines = array_filter(
23
            explode(PHP_EOL, $docBlock),
24 26
            static fn (string $l): bool => str_contains($l, $method),
25
        );
26 26
27
        /** @var array<int, string> $lineSplit */
28
        $lineSplit = explode(' ', (string)reset($lines));
29
30
        $classFromMethod = $lineSplit[3] ?? '';
31
        if ($classFromMethod !== '') {
32
            return $classFromMethod;
33
        }
34
35
        if ($method === 'getFactory') {
36
            $factoryType = $this->parseFacadeTemplate($docBlock);
37
            if ($factoryType !== '') {
38
                return $factoryType;
39
            }
40
41
            return AbstractFactory::class;
42
        }
43
44
        if ($method === 'getConfig') {
45
            $configType = $this->parseFactoryTemplate($docBlock);
46
            if ($configType !== '') {
47
                return $configType;
48
            }
49
50
            return AbstractConfig::class;
51
        }
52
53
        return '';
54
    }
55
56
    private function parseFacadeTemplate(string $docBlock): string
57
    {
58
        if (preg_match('/@extends\s+[^<]*AbstractFacade<\s*([^>\s]+)\s*>/i', $docBlock, $matches) === 1) {
59
            return $matches[1];
60
        }
61
62
        return '';
63
    }
64
65
    private function parseFactoryTemplate(string $docBlock): string
66
    {
67
        if (preg_match('/@extends\s+[^<]*AbstractFactory<\s*([^>\s]+)\s*>/i', $docBlock, $matches) === 1) {
68
            return $matches[1];
69
        }
70
71
        return '';
72
    }
73
}
74