-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClassNamespace.php
More file actions
75 lines (59 loc) · 1.76 KB
/
ClassNamespace.php
File metadata and controls
75 lines (59 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* @see https://github.com/open-code-modeling/php-code-ast for the canonical source repository
* @copyright https://github.com/open-code-modeling/php-code-ast/blob/master/COPYRIGHT.md
* @license https://github.com/open-code-modeling/php-code-ast/blob/master/LICENSE.md MIT License
*/
declare(strict_types=1);
namespace OpenCodeModeling\CodeAst\NodeVisitor;
use PhpParser\BuilderFactory;
use PhpParser\Node\Stmt;
use PhpParser\NodeVisitorAbstract;
class ClassNamespace extends NodeVisitorAbstract
{
/**
* @var string
*/
private $namespace;
/**
* @var BuilderFactory
**/
private $builderFactory;
public function __construct(string $namespace)
{
$this->namespace = $namespace;
$this->builderFactory = new BuilderFactory();
}
public static function fromNode(Stmt\Namespace_ $node): self
{
return new self($node->name->toString());
}
public function afterTraverse(array $nodes): ?array
{
if ($this->hasNamespace($nodes)) {
return null;
}
$newNodes = [];
foreach ($nodes as $node) {
$newNodes[] = $node;
if ($this->isNodeStrictType($node)) {
$newNodes[] = $this->builderFactory->namespace($this->namespace)->getNode();
}
}
return $newNodes;
}
private function isNodeStrictType(Stmt $node): bool
{
return $node instanceof Stmt\Declare_
&& \strtolower($node->declares[0]->key->name) === 'strict_types';
}
private function hasNamespace(array $nodes): bool
{
foreach ($nodes as $node) {
if ($node instanceof Stmt\Namespace_) {
return true;
}
}
return false;
}
}