MigrationNamespaceChangeRector::isOldNs()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
namespace Sserbin\DoctrineMigrations2Upgrade;
4
5
use PhpParser\Node;
6
use PhpParser\Node\Name;
7
use Rector\Rector\AbstractRector;
8
use Rector\RectorDefinition\CodeSample;
9
use Rector\RectorDefinition\RectorDefinition;
10
11
class MigrationNamespaceChangeRector extends AbstractRector
12
{
13
    private const NAMESPACE_1X = 'Doctrine\DBAL\Migrations';
14
    private const NAMESPACE_2X = 'Doctrine\Migrations';
15
16
    public function getDefinition(): RectorDefinition
17
    {
18
        return new RectorDefinition("Changes namespace Doctrine\DBAL\Migrations to Doctrine\Migrations", [
19
            new CodeSample(
20
                <<<'CODE_SAMPLE'
21
use Doctrine\DBAL\Migrations\AbstractMigration;
22
class Version20180101150000 extends AbstractMigration
23
{
24
}
25
CODE_SAMPLE
26
                ,
27
                <<<'CODE_SAMPLE'
28
use Doctrine\Migrations\AbstractMigration;
29
class Version20180101150000 extends AbstractMigration
30
{
31
}
32
CODE_SAMPLE
33
            )
34
        ]);
35
    }
36
37
    /**
38
     * @inheritDoc
39
     */
40 1
    public function getNodeTypes(): array
41
    {
42 1
        return [Name::class];
43
    }
44
45 1
    public function refactor(Node $node): ?Node
46
    {
47 1
        assert($node instanceof Name);
48
49 1
        if (!$node->isQualified()) { // short circuit unqualified names
50 1
            return null;
51
        }
52
53 1
        if ($this->isOldNs($node)) {
54 1
            $node->parts = $this->makeNewNs($node);
55 1
            return $node;
56
        }
57
58 1
        return null;
59
    }
60
61 1
    private function isOldNs(Name $node): bool
62
    {
63 1
        $nsParts = explode('\\', self::NAMESPACE_1X);
64
65 1
        $matches = array_intersect($node->parts, $nsParts);
66 1
        return count($matches) === count($nsParts);
67
    }
68
69
    /**
70
     * @return string[]
71
     */
72 1
    private function makeNewNs(Name $node): array
73
    {
74 1
        $parts = explode('\\', self::NAMESPACE_2X);
75
76 1
        $remaining = array_diff($node->parts, explode('\\', self::NAMESPACE_1X));
77
78 1
        return array_merge($parts, $remaining);
79
    }
80
}
81