|
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
|
21 |
|
public function check(SplFileInfo $file, string $prefix = '', bool $skipEmpty = false): Result |
|
22
|
|
|
{ |
|
23
|
21 |
|
$expectedNamespace = $this->guessNamespaceFromPath($file, $prefix); |
|
24
|
21 |
|
$actualNamespace = $this->parseNamespaceFromFile($file); |
|
25
|
|
|
|
|
26
|
21 |
|
if ($skipEmpty && $actualNamespace === '') { |
|
27
|
3 |
|
return new Result($file, true, '', ''); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
19 |
|
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
|
21 |
|
private function guessNamespaceFromPath(SplFileInfo $file, string $prefix = ''): string |
|
41
|
|
|
{ |
|
42
|
21 |
|
$namespace = strval(Regex::replace('/\//', '\\', $file->getRelativePath())->result()); |
|
43
|
|
|
|
|
44
|
21 |
|
if (mb_strlen($prefix) !== 0) { |
|
45
|
20 |
|
$namespace = mb_strlen($namespace) !== 0 ? $prefix . '\\' . $namespace : $prefix; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
21 |
|
return $namespace; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Extract the namespace from a file. |
|
53
|
|
|
* |
|
54
|
|
|
* @param SplFileInfo $file |
|
55
|
|
|
* @return string |
|
56
|
|
|
*/ |
|
57
|
21 |
|
private function parseNamespaceFromFile(SplFileInfo $file): string |
|
58
|
|
|
{ |
|
59
|
21 |
|
$regex = Regex::matchAll('/namespace (.*?)(;|{|$)/', $file->getContents()); |
|
60
|
|
|
|
|
61
|
21 |
|
if (!$regex->hasMatch()) { |
|
62
|
5 |
|
return ''; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
try { |
|
66
|
17 |
|
return trim($regex->results()[0]->group(1)); |
|
67
|
|
|
} catch (RegexFailed $exception) { |
|
68
|
|
|
return ''; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|