Passed
Pull Request — master (#506)
by Théo
03:11
created

StringNodePrefixer::prefixStringValue()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 11
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 19
rs 9.9
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;
16
17
use Humbug\PhpScoper\Scoper;
18
use Humbug\PhpScoper\Whitelist;
19
use PhpParser\Error as PhpParserError;
20
use PhpParser\Node\Scalar\String_;
21
use function Safe\substr;
22
23
/**
24
 * @private
25
 */
26
final class StringNodePrefixer
27
{
28
    private Scoper $scoper;
29
    private string $prefix;
30
    private Whitelist $whitelist;
31
32
    public function __construct(Scoper $scoper, string $prefix, Whitelist $whitelist)
33
    {
34
        $this->scoper = $scoper;
35
        $this->prefix = $prefix;
36
        $this->whitelist = $whitelist;
37
    }
38
39
    public function prefixStringValue(String_ $node): void
40
    {
41
        try {
42
            $lastChar = substr($node->value, -1);
43
44
            $newValue = $this->scoper->scope(
45
                '',
46
                $node->value,
47
                $this->prefix,
48
                [],
49
                $this->whitelist,
50
            );
51
52
            if ("\n" !== $lastChar) {
53
                $newValue = substr($newValue, 0, -1);
54
            }
55
56
            $node->value = $newValue;
57
        } catch (PhpParserError $error) {
58
            // Continue without scoping the heredoc which for some reasons contains invalid PHP code
59
        }
60
    }
61
}
62