| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace WPDeveloper\BetterDocs\Dependencies\DI\Annotation; |
| 6 |
|
| 7 |
use WPDeveloper\BetterDocs\Dependencies\DI\Definition\Exception\InvalidAnnotation; |
| 8 |
|
| 9 |
/** |
| 10 |
* "Inject" annotation. |
| 11 |
* |
| 12 |
* Marks a property or method as an injection point |
| 13 |
* |
| 14 |
* @api |
| 15 |
* |
| 16 |
* @Annotation |
| 17 |
* @Target({"METHOD","PROPERTY"}) |
| 18 |
* |
| 19 |
* @author Matthieu Napoli <matthieu@mnapoli.fr> |
| 20 |
*/ |
| 21 |
final class Inject |
| 22 |
{ |
| 23 |
/** |
| 24 |
* Entry name. |
| 25 |
* @var string |
| 26 |
*/ |
| 27 |
private $name; |
| 28 |
|
| 29 |
/** |
| 30 |
* Parameters, indexed by the parameter number (index) or name. |
| 31 |
* |
| 32 |
* Used if the annotation is set on a method |
| 33 |
* @var array |
| 34 |
*/ |
| 35 |
private $parameters = []; |
| 36 |
|
| 37 |
/** |
| 38 |
* @throws InvalidAnnotation |
| 39 |
*/ |
| 40 |
public function __construct(array $values) |
| 41 |
{ |
| 42 |
// Process the parameters as a list AND as a parameter array (we don't know on what the annotation is) |
| 43 |
|
| 44 |
// @Inject(name="foo") |
| 45 |
if (isset($values['name']) && is_string($values['name'])) { |
| 46 |
$this->name = $values['name']; |
| 47 |
|
| 48 |
return; |
| 49 |
} |
| 50 |
|
| 51 |
// @Inject |
| 52 |
if (! isset($values['value'])) { |
| 53 |
return; |
| 54 |
} |
| 55 |
|
| 56 |
$values = $values['value']; |
| 57 |
|
| 58 |
// @Inject("foo") |
| 59 |
if (is_string($values)) { |
| 60 |
$this->name = $values; |
| 61 |
} |
| 62 |
|
| 63 |
// @Inject({...}) on a method |
| 64 |
if (is_array($values)) { |
| 65 |
foreach ($values as $key => $value) { |
| 66 |
if (! is_string($value)) { |
| 67 |
throw new InvalidAnnotation(sprintf( |
| 68 |
'@Inject({"param" = "value"}) expects "value" to be a string, %s given.', |
| 69 |
json_encode($value) |
| 70 |
)); |
| 71 |
} |
| 72 |
|
| 73 |
$this->parameters[$key] = $value; |
| 74 |
} |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* @return string|null Name of the entry to inject |
| 80 |
*/ |
| 81 |
public function getName() |
| 82 |
{ |
| 83 |
return $this->name; |
| 84 |
} |
| 85 |
|
| 86 |
/** |
| 87 |
* @return array Parameters, indexed by the parameter number (index) or name |
| 88 |
*/ |
| 89 |
public function getParameters() : array |
| 90 |
{ |
| 91 |
return $this->parameters; |
| 92 |
} |
| 93 |
} |
| 94 |
|