Test Failed
Pull Request — master (#37)
by Divine Niiquaye
02:55
created

PhpLiteral   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A resolve() 0 14 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of DivineNii opensource projects.
7
 *
8
 * PHP version 7.4 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2021 DivineNii (https://divinenii.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace Rade\DI\Builder;
19
20
use PhpParser\{NodeTraverser, ParserFactory};
21
use Rade\DI\NodeVisitor\PhpLiteralVisitor;
22
23
/**
24
 * PHP literal value.
25
 *
26
 * Example:
27
 *
28
 * ```php
29
 * $literal = new PhpLiteral("$hello = ['%?' => '%?'];", ['Hello', '344']);
30
 * // Expected output when resolved is: $hello => ['Hello' => 344];
31
 * ```
32
 *
33
 * @author Divine Niiquaye Ibok <[email protected]>
34
 */
35
class PhpLiteral
36
{
37
    private string $value;
38
    private array $args;
39
40
    /**
41
     * `??` is a reserved string in code, as it used to resolve missing values.
42
     *
43
     * @param string $value Should be a php code excluding `<?php`
44
     * @param array<int,mixed> $args
45
     */
46
    public function __construct(string $value, array $args = [])
47
    {
48
        $this->args = $args;
49
        $this->value = $value;
50
    }
51
52
    public function resolve(\Rade\DI\Resolver $resolver)
53
    {
54
        return (function () use ($resolver) {
55
            $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
56
            $astCode = $parser->parse("<?php\n" . $this->value);
57
58
            if ([] !== $this->args) {
59
                $traverser = new NodeTraverser();
60
                $traverser->addVisitor(new PhpLiteralVisitor($resolver->resolveArguments($this->args)));
61
62
                $astCode = $traverser->traverse($astCode);
0 ignored issues
show
Bug introduced by
It seems like $astCode can also be of type null; however, parameter $nodes of PhpParser\NodeTraverser::traverse() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

62
                $astCode = $traverser->traverse(/** @scrutinizer ignore-type */ $astCode);
Loading history...
63
            }
64
65
            return $astCode;
66
        })();
67
    }
68
}
69