Passed
Push — master ( e7f764...357f89 )
by Konstantinos
01:39
created

Evaluator::guessNamespaceFromPath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 2
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpNsFixer\Fixer;
6
7
use Spatie\Regex\Regex;
8
use Spatie\Regex\RegexFailed;
9
use Symfony\Component\Finder\SplFileInfo;
10
11
final class Evaluator
12
{
13
    /**
14
     * Check if the file's namespace is valid.
15
     *
16
     * @param SplFileInfo $file
17
     * @param string $prefix
18
     * @param bool $skipEmpty
19
     * @return Result
20
     */
21 19
    public function check(SplFileInfo $file, string $prefix = '', bool $skipEmpty = false): Result
22
    {
23 19
        $expectedNamespace = $this->guessNamespaceFromPath($file, $prefix);
24 19
        $actualNamespace = $this->parseNamespaceFromFile($file);
25
26 19
        if ($skipEmpty && $actualNamespace === '') {
27 3
            return new Result($file, true, '', '');
28
        }
29
30 17
        return new Result($file, $actualNamespace === $expectedNamespace, $actualNamespace, $expectedNamespace);
31
    }
32
33
    /**
34
     * Generate the namespace based on file's path.
35
     *
36
     * @param SplFileInfo $file
37
     * @param string $prefix
38
     * @return string
39
     */
40 19
    private function guessNamespaceFromPath(SplFileInfo $file, string $prefix = ''): string
41
    {
42 19
        $namespace = strval(Regex::replace('/\//', '\\', $file->getRelativePath())->result());
43
44 19
        if (mb_strlen($prefix) !== 0) {
45 18
            $namespace = mb_strlen($namespace) !== 0 ? $prefix . '\\' . $namespace : $prefix;
46
        }
47
48 19
        return $namespace;
49
    }
50
51
    /**
52
     * Extract the namespace from a file.
53
     *
54
     * @param SplFileInfo $file
55
     * @return string
56
     */
57 19
    private function parseNamespaceFromFile(SplFileInfo $file): string
58
    {
59 19
        $regex = Regex::matchAll('/namespace (.*?)(;|{|$)/', $file->getContents());
60
61 19
        if (!$regex->hasMatch()) {
62 5
            return '';
63
        }
64
65
        try {
66 15
            return trim($regex->results()[0]->group(1));
67
        } catch (RegexFailed $exception) {
68
            return '';
69
        }
70
    }
71
}
72