ServiceResolver::findServices()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 20
cts 20
cp 1
rs 9.0168
c 0
b 0
f 0
cc 5
nc 5
nop 1
crap 5
1
<?php
2
/*
3
 * Copyright (c) Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
7
declare(strict_types=1);
8
9
namespace Tebru\Retrofit\Finder;
10
11
use RecursiveDirectoryIterator;
12
use RecursiveIteratorIterator;
13
use RecursiveRegexIterator;
14
use RegexIterator;
15
16
/**
17
 * Class ServiceResolver
18
 *
19
 * @author Nate Brunette <[email protected]>
20
 */
21
class ServiceResolver
22
{
23
    private const ANNOTATION_REGEX = '/Tebru\\\\Retrofit\\\\Annotation/';
24
    private const FILE_REGEX = '/^.+\.php$/i';
25
    private const INTERFACE_REGEX = '/^interface\s+([\w\\\\]+)[\s{\n]?/m';
26
    private const NAMESPACE_REGEX = '/^namespace\s+([\w\\\\]+)/m';
27
    
28
    /**
29
     * Find all services given a source directory
30
     *
31
     * @param string $srcDir
32
     * @return string[]
33
     */
34 1
    public function findServices(string $srcDir): array
35
    {
36 1
        $directory = new RecursiveDirectoryIterator($srcDir);
37 1
        $iterator = new RecursiveIteratorIterator($directory);
38 1
        $files = new RegexIterator($iterator, self::FILE_REGEX, RecursiveRegexIterator::GET_MATCH);
39
40 1
        $services = [];
41 1
        foreach ($files as $file) {
42 1
            $fileString = file_get_contents($file[0]);
43
            
44 1
            $annotationMatchesFound = preg_match(self::ANNOTATION_REGEX, $fileString);
45
46 1
            if (!$annotationMatchesFound) {
47 1
                continue;
48
            }
49
50 1
            $interfaceMatchesFound = preg_match(self::INTERFACE_REGEX, $fileString, $interfaceMatches);
51
52 1
            if (!$interfaceMatchesFound) {
53 1
                continue;
54
            }
55
            
56 1
            $namespaceMatchesFound = preg_match(self::NAMESPACE_REGEX, $fileString, $namespaceMatches);
57
58 1
            $className = '';
59
60 1
            if ($namespaceMatchesFound) {
61 1
                $className .= $namespaceMatches[1];
62
            }
63
64 1
            $className .= '\\' . $interfaceMatches[1];
65
66 1
            $services[] = $className;
67
        }
68
69 1
        return $services;
70
    }
71
}
72