Passed
Pull Request — master (#571)
by Théo
02:20
created

MultiConstStmtReplacer   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
A enterNode() 0 23 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 Humbug\PhpScoper\PhpParser\NodeVisitor\Resolver\IdentifierResolver;
18
use Humbug\PhpScoper\Reflector;
19
use Humbug\PhpScoper\Whitelist;
20
use PhpParser\Node;
21
use PhpParser\Node\Arg;
22
use PhpParser\Node\Expr;
23
use PhpParser\Node\Expr\ConstFetch;
24
use PhpParser\Node\Expr\FuncCall;
25
use PhpParser\Node\Name;
26
use PhpParser\Node\Name\FullyQualified;
27
use PhpParser\Node\Scalar\String_;
28
use PhpParser\Node\Stmt\Const_;
29
use PhpParser\Node\Stmt\Expression;
30
use PhpParser\Node\Stmt\If_;
31
use PhpParser\NodeVisitorAbstract;
32
use UnexpectedValueException;
33
use function array_map;
34
use function count;
35
36
/**
37
 * Replaces multi-constants declarations into multiple single-constant
38
 * declarations.
39
 * This is to allow ConstStmtReplacer to do its job without having to worry
40
 * about this multi-constant declaration case which it cannot handle.
41
 *
42
 * ```
43
 * const FOO = 'foo', BAR = 'bar';
44
 * ```
45
 *
46
 * =>
47
 *
48
 * ```
49
 * const FOO = 'foo';
50
 * const BAR = 'bar';
51
 * ```
52
 *
53
 * @private
54
 */
55
final class MultiConstStmtReplacer extends NodeVisitorAbstract
56
{
57
    public function enterNode(Node $node): Node
58
    {
59
        if (!$node instanceof Const_) {
60
            return $node;
61
        }
62
63
        if (count($node->consts) <= 1) {
64
            return $node;
65
        }
66
67
        $newStatements = array_map(
68
            static function (Node\Const_ $const) use ($node): Const_ {
69
                $newConstNode = clone $node;
70
                $newConstNode->consts = [$const];
71
72
                return $newConstNode;
73
            },
74
            $node->consts,
75
        );
76
77
        return new If_(
78
            new ConstFetch(new Name('true')),
79
            ['stmts' => $newStatements]
80
        );
81
    }
82
}
83