1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace ApiClients\Tools\Installer\Operation; |
4
|
|
|
|
5
|
|
|
use ApiClients\Tools\Installer\Filesystem; |
6
|
|
|
use ApiClients\Tools\Installer\OperationInterface; |
7
|
|
|
use PhpParser\Node; |
8
|
|
|
use PhpParser\ParserFactory; |
9
|
|
|
use PhpParser\PrettyPrinter\Standard; |
10
|
|
|
use Symfony\Component\Console\Style\SymfonyStyle; |
11
|
|
|
|
12
|
|
|
final class UpdateNamespaces implements OperationInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var Filesystem |
16
|
|
|
*/ |
17
|
|
|
private $filesystem; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @internal |
21
|
|
|
* @param Filesystem $filesystem |
22
|
|
|
*/ |
23
|
|
|
public function __construct(Filesystem $filesystem) |
24
|
|
|
{ |
25
|
|
|
$this->filesystem = $filesystem; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public static function create(): OperationInterface |
29
|
|
|
{ |
30
|
|
|
return new self(new Filesystem()); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function operate(array $replacements, array $environment, SymfonyStyle $style) |
34
|
|
|
{ |
35
|
|
|
foreach ([ |
36
|
|
|
'path_src' => ['ns_vendor', 'current_ns'], |
37
|
|
|
'path_tests' => ['ns_tests_vendor', 'current_ns_tests'], |
38
|
|
|
] as $dirIndex => list($namespaceIndex, $currentNamespace)) { |
39
|
|
|
$namespace = $replacements[$namespaceIndex] . '\\' . $replacements['ns_project']; |
40
|
|
|
foreach ($this->filesystem->ls($replacements[$dirIndex]) as $fileName) { |
41
|
|
|
$style->text(' * Updating ' . $fileName); |
42
|
|
|
$this->updateNamespaces($fileName, $namespace, $environment[$currentNamespace] ?? ''); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$style->success('Namespaces updated'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function updateNamespaces(string $fileName, string $namespace, string $currentNamespace) |
50
|
|
|
{ |
51
|
|
|
$stmts = $this->parseFile($fileName); |
52
|
|
|
if ($stmts === null) { |
53
|
|
|
return; |
54
|
|
|
} |
55
|
|
|
foreach ($stmts as $index => $node) { |
56
|
|
|
if (!($node instanceof Node\Stmt\Namespace_)) { |
57
|
|
|
continue; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$suffix = str_replace($currentNamespace, '', (string)$node->name); |
61
|
|
|
|
62
|
|
|
$stmts[$index] = new Node\Stmt\Namespace_( |
63
|
|
|
new Node\Name( |
64
|
|
|
$namespace . $suffix |
65
|
|
|
), |
66
|
|
|
$node->stmts, |
67
|
|
|
$node->getAttributes() |
68
|
|
|
); |
69
|
|
|
|
70
|
|
|
break; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$this->filesystem->write($fileName, (new Standard())->prettyPrintFile($stmts) . PHP_EOL); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
private function parseFile(string $fileName) |
77
|
|
|
{ |
78
|
|
|
return (new ParserFactory())->create(ParserFactory::ONLY_PHP7)->parse($this->filesystem->read($fileName)); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|