MultiConstStmtReplacer   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 13
c 2
b 0
f 0
dl 0
loc 27
rs 10
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A enterNode() 0 25 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the humbug/php-scoper package.
7
 *
8
 * Copyright (c) 2017 Théo FIDRY <[email protected]>,
9
 *                    Pádraic Brady <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Humbug\PhpScoper\PhpParser\NodeVisitor;
16
17
use PhpParser\Node;
18
use PhpParser\Node\Expr\ConstFetch;
19
use PhpParser\Node\Name;
20
use PhpParser\Node\Stmt\Const_;
21
use PhpParser\Node\Stmt\If_;
22
use PhpParser\NodeVisitorAbstract;
23
use function array_map;
24
use function count;
25
26
/**
27
 * Replaces multi-constants declarations into multiple single-constant
28
 * declarations.
29
 * This is to allow ConstStmtReplacer to do its job without having to worry
30
 * about this multi-constant declaration case which it cannot handle.
31
 *
32
 * ```
33
 * const FOO = 'foo', BAR = 'bar';
34
 * ```
35
 *
36
 * =>
37
 *
38
 * ```
39
 * const FOO = 'foo';
40
 * const BAR = 'bar';
41
 * ```
42
 *
43
 * @private
44
 */
45
final class MultiConstStmtReplacer extends NodeVisitorAbstract
46
{
47
    public function enterNode(Node $node): Node
48
    {
49
        if (!$node instanceof Const_) {
50
            return $node;
51
        }
52
53
        if (count($node->consts) <= 1) {
54
            return $node;
55
        }
56
57
        $newStatements = array_map(
58
            static function (Node\Const_ $const) use ($node): Const_ {
59
                $newConstNode = clone $node;
60
                $newConstNode->consts = [$const];
61
62
                return $newConstNode;
63
            },
64
            $node->consts,
65
        );
66
67
        // Workaround to replace the statement.
68
        // See https://github.com/nikic/PHP-Parser/issues/507
69
        return new If_(
70
            new ConstFetch(new Name('true')),
71
            ['stmts' => $newStatements],
72
        );
73
    }
74
}
75