AnonymousClassFeature::fix()   B
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 17
cts 17
cp 1
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 18
nc 6
nop 1
crap 4
1
<?php
2
declare (strict_types = 1);
3
4
namespace JanPiet\PhpTranspiler\Feature;
5
6
use JanPiet\PhpTranspiler\NodeSearch;
7
use JanPiet\PhpTranspiler\ParentNotFoundException;
8
use PhpParser\Node;
9
10
class AnonymousClassFeature implements FeatureInterface
11
{
12
    private $cnt = 0;
13
14
    /**
15
     * @param NodeSearch $nodeSearch
16
     * @return bool
17
     */
18 3
    public function fix(NodeSearch $nodeSearch): bool
19
    {
20 3
        $found = false;
21 3
        foreach ($nodeSearch->eachType(Node\Expr\New_::class) as $node) {
22 3
            if (!$node->class instanceof Node\Stmt\Class_) {
23 3
                continue;
24
            }
25 3
            $found = true;
26
27 3
            $className = 'mine' . sha1((string) $this->cnt++);
28 3
            $statementName = $className;
29
30 3
            $newClass = $node->class;
31 3
            $newClass->name = $className;
32
33
            try {
34
                /** @var Node\Stmt\Namespace_ $namespaceNode */
35 3
                $namespaceNode = $nodeSearch->findParent(Node\Stmt\Namespace_::class, $node);
36 2
                $namespaceNode->stmts[] = $newClass;
37 2
                $statementName = implode('\\', $namespaceNode->name->parts) . '\\' . $className;
38 2
            } catch (ParentNotFoundException $e) {
39 2
                $nodeSearch->appendToRoot($newClass);
40
            }
41
42 3
            $node->class = new Node\Name\FullyQualified($statementName);
43
        }
44
45 3
        return $found;
46
    }
47
}
48