Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace DI\Attribute;
6
 
7
use Attribute;
8
use DI\Definition\Exception\InvalidAttribute;
9
 
10
/**
11
 * #[Inject] attribute.
12
 *
13
 * Marks a property or method as an injection point
14
 *
15
 * @api
16
 *
17
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
18
 */
19
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_METHOD | Attribute::TARGET_PARAMETER)]
20
final class Inject
21
{
22
    /**
23
     * Entry name.
24
     */
25
    private ?string $name = null;
26
 
27
    /**
28
     * Parameters, indexed by the parameter number (index) or name.
29
     *
30
     * Used if the attribute is set on a method
31
     */
32
    private array $parameters = [];
33
 
34
    /**
35
     * @throws InvalidAttribute
36
     */
37
    public function __construct(string|array|null $name = null)
38
    {
39
        // #[Inject('foo')] or #[Inject(name: 'foo')]
40
        if (is_string($name)) {
41
            $this->name = $name;
42
        }
43
 
44
        // #[Inject([...])] on a method
45
        if (is_array($name)) {
46
            foreach ($name as $key => $value) {
47
                if (! is_string($value)) {
48
                    throw new InvalidAttribute(sprintf(
49
                        "#[Inject(['param' => 'value'])] expects \"value\" to be a string, %s given.",
50
                        json_encode($value, \JSON_THROW_ON_ERROR)
51
                    ));
52
                }
53
 
54
                $this->parameters[$key] = $value;
55
            }
56
        }
57
    }
58
 
59
    /**
60
     * @return string|null Name of the entry to inject
61
     */
62
    public function getName() : string|null
63
    {
64
        return $this->name;
65
    }
66
 
67
    /**
68
     * @return array Parameters, indexed by the parameter number (index) or name
69
     */
70
    public function getParameters() : array
71
    {
72
        return $this->parameters;
73
    }
74
}