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\Traits; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* This trait adds global config support as parameters. |
22
|
|
|
* |
23
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
24
|
|
|
*/ |
25
|
|
|
trait ParameterTrait |
26
|
|
|
{ |
27
|
|
|
/** @var array<string,mixed> For handling a global config around services */ |
28
|
|
|
public array $parameters = []; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Replaces "%value%" from container's parameters whose value is scalar. |
32
|
|
|
* |
33
|
|
|
* Example of usage: |
34
|
|
|
* |
35
|
|
|
* ```php |
36
|
|
|
* $container->parameters['greet'] = 'Hello'; |
37
|
|
|
* $container->parameters['name'] = 'Divine'; |
38
|
|
|
* |
39
|
|
|
* $value = $container->parameter('%greet% how are you %name%'); |
40
|
|
|
* // Expected value is "Hello how are you Divine" |
41
|
|
|
* ``` |
42
|
|
|
* |
43
|
|
|
* @return string or mixed value if $value is supported |
44
|
|
|
*/ |
45
|
|
|
public function parameter(string $value) |
46
|
|
|
{ |
47
|
|
|
$res = []; |
48
|
|
|
$parts = \preg_split('#(%[^%\s]+%)#i', $value, -1, \PREG_SPLIT_DELIM_CAPTURE); |
49
|
|
|
|
50
|
|
|
if (false === $parts || (1 === \count($parts) && $value === $parts[0])) { |
51
|
|
|
return $value; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$partsN = \count($parts = \array_filter($parts)); |
55
|
|
|
|
56
|
|
|
foreach ($parts as $part) { |
57
|
|
|
if ('' !== $part && '%' === $part[0]) { |
58
|
|
|
$val = \substr($part, 1, -1); |
59
|
|
|
|
60
|
|
|
if (!\array_key_exists($val, $this->parameters)) { |
61
|
|
|
throw new \InvalidArgumentException(\sprintf('You have requested a non-existent parameter "%s".', $val)); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$part = $this->parameters[$val]; |
65
|
|
|
|
66
|
|
|
if ($partsN > 1 && !\is_scalar($part)) { |
67
|
|
|
throw new \InvalidArgumentException(\sprintf('Unable to concatenate non-scalar parameter "%s" into %s.', $val, $value)); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
$res[] = $part; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return [] === $res ? $value : (1 === \count($res) ? $res[0] : \implode('', $res)); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|