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); |
|
|
|
|
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $astCode; |
66
|
|
|
})(); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|