|
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
|
|
|
|
|
39
|
|
|
private array $args; |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* `??` is a reserved string in code, as it used to resolve missing values. |
|
43
|
|
|
* |
|
44
|
|
|
* @param string $value Should be a php code excluding `<?php` |
|
45
|
|
|
* @param array<int,mixed> $args |
|
46
|
|
|
*/ |
|
47
|
|
|
public function __construct(string $value, array $args = []) |
|
48
|
|
|
{ |
|
49
|
|
|
$this->args = $args; |
|
50
|
|
|
$this->value = $value; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function resolve(\Rade\DI\Resolver $resolver) |
|
54
|
|
|
{ |
|
55
|
|
|
return (function () use ($resolver) { |
|
56
|
|
|
$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); |
|
57
|
|
|
$astCode = $parser->parse("<?php\n" . $this->value); |
|
58
|
|
|
|
|
59
|
|
|
if ([] !== $this->args) { |
|
60
|
|
|
$traverser = new NodeTraverser(); |
|
61
|
|
|
$traverser->addVisitor(new PhpLiteralVisitor($resolver->resolveArguments($this->args))); |
|
62
|
|
|
|
|
63
|
|
|
$astCode = $traverser->traverse($astCode); |
|
|
|
|
|
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $astCode; |
|
67
|
|
|
})(); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|