-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClassExtends.php
More file actions
73 lines (60 loc) · 2.05 KB
/
Copy pathClassExtends.php
File metadata and controls
73 lines (60 loc) · 2.05 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
<?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 OpenCodeModeling\CodeAst\Exception\LogicException;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\NodeVisitorAbstract;
final class ClassExtends extends NodeVisitorAbstract
{
/**
* @var string
*/
private $extends;
public function __construct(string $extends)
{
$this->extends = $extends;
}
public function afterTraverse(array $nodes): ?array
{
$newNodes = [];
foreach ($nodes as $node) {
$newNodes[] = $node;
if ($node instanceof Namespace_) {
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Stmt\Class_) {
if ($this->checkExtendsExists($stmt)) {
return null;
}
$stmt->extends = new Name($this->extends);
}
}
} elseif ($node instanceof Stmt\Class_) {
if ($this->checkExtendsExists($node)) {
return null;
}
$node->extends = new Name($this->extends);
}
}
return $newNodes;
}
private function checkExtendsExists(Stmt\Class_ $node): bool
{
$exists = $this->extends === (string) $node->extends;
if (false === $exists && null !== $node->extends) {
throw new LogicException(\sprintf(
'Class "%s" extends already from class "%s". Could not add extends from class "%s"',
$node->name->name,
(string) $node->extends,
$this->extends
));
}
return $exists;
}
}