| 1 | <?php |
||
| 21 | */ |
||
| 22 | class LazyAdvisorAccessor |
||
| 23 | { |
||
| 24 | /** |
||
| 25 | * Instance of aspect container |
||
| 26 | */ |
||
| 27 | protected AspectContainer $container; |
||
|
|
|||
| 28 | |||
| 29 | /** |
||
| 30 | * Aspect loader instance |
||
| 31 | */ |
||
| 32 | protected AspectLoader $loader; |
||
| 33 | |||
| 34 | /** |
||
| 35 | * Accessor constructor |
||
| 36 | 1 | */ |
|
| 37 | public function __construct(AspectContainer $container, AspectLoader $loader) |
||
| 38 | 1 | { |
|
| 39 | 1 | $this->container = $container; |
|
| 40 | 1 | $this->loader = $loader; |
|
| 41 | } |
||
| 42 | |||
| 43 | /** |
||
| 44 | * Magic advice accessor |
||
| 45 | * |
||
| 46 | * @throws InvalidArgumentException if referenced value is not an advisor |
||
| 47 | 1 | */ |
|
| 48 | public function __get(string $name): Advice |
||
| 49 | 1 | { |
|
| 50 | 1 | if ($this->container->has($name)) { |
|
| 51 | $advisor = $this->container->get($name); |
||
| 52 | } else { |
||
| 53 | list(, $advisorName) = explode('.', $name); |
||
| 54 | list($aspect) = explode('->', $advisorName); |
||
| 55 | $aspectInstance = $this->container->getAspect($aspect); |
||
| 56 | $this->loader->loadAndRegister($aspectInstance); |
||
| 57 | |||
| 58 | $advisor = $this->container->get($name); |
||
| 59 | } |
||
| 60 | 1 | ||
| 61 | if (!$advisor instanceof Advisor) { |
||
| 62 | throw new InvalidArgumentException("Reference {$name} is not an advisor"); |
||
| 63 | 1 | } |
|
| 64 | $this->$name = $advisor->getAdvice(); |
||
| 65 | 1 | ||
| 66 | return $this->$name; |
||
| 67 | } |
||
| 68 | } |
||
| 69 |