|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Cubex\Routing; |
| 4 | + |
| 5 | +use Cubex\Attributes\PreCondition; |
| 6 | +use Cubex\Attributes\SkipCondition; |
| 7 | +use Cubex\Cubex; |
| 8 | +use Cubex\CubexAwareTrait; |
| 9 | +use Packaged\Context\ContextAwareTrait; |
| 10 | +use Packaged\DiContainer\AttributeWatcher; |
| 11 | +use Packaged\DiContainer\ReflectionInterrupt; |
| 12 | +use Packaged\DiContainer\ReflectionObserver; |
| 13 | + |
| 14 | +class ConditionProcessor extends AttributeWatcher implements ReflectionInterrupt, ReflectionObserver |
| 15 | +{ |
| 16 | + use ContextAwareTrait; |
| 17 | + use CubexAwareTrait; |
| 18 | + |
| 19 | + public function __construct(Cubex $cubex) |
| 20 | + { |
| 21 | + $this->setCubex($cubex); |
| 22 | + $this->setContext($cubex->getContext()); |
| 23 | + $this->clear(); |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * @var \Cubex\Attributes\PreCondition[] |
| 28 | + */ |
| 29 | + protected array $_conditions = []; |
| 30 | + protected bool $_processed = false; |
| 31 | + |
| 32 | + protected mixed $_handled = null; |
| 33 | + |
| 34 | + protected function _processAttributes() |
| 35 | + { |
| 36 | + if($this->_processed) |
| 37 | + { |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + $skipClasses = []; |
| 42 | + $this->_conditions = []; |
| 43 | + foreach($this->attributes() as $attribute) |
| 44 | + { |
| 45 | + if($attribute->getName() === SkipCondition::class) |
| 46 | + { |
| 47 | + $skipClasses[] = $attribute->newInstance()->getClass(); |
| 48 | + } |
| 49 | + if($attribute->getName() === PreCondition::class) |
| 50 | + { |
| 51 | + /** @var \Cubex\Attributes\AbstractConditionAttribute $condition */ |
| 52 | + $condition = $attribute->newInstance(); |
| 53 | + $this->_conditions[$condition->getClass()] = $condition; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + foreach($skipClasses as $skipClass) |
| 58 | + { |
| 59 | + if(isset($this->_conditions[$skipClass])) |
| 60 | + { |
| 61 | + unset($this->_conditions[$skipClass]); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + $this->_processed = true; |
| 66 | + } |
| 67 | + |
| 68 | + public function shouldInterruptMethod(): bool |
| 69 | + { |
| 70 | + $this->_processAttributes(); |
| 71 | + if(empty($this->_conditions)) |
| 72 | + { |
| 73 | + return false; |
| 74 | + } |
| 75 | + |
| 76 | + foreach($this->_conditions as $condition) |
| 77 | + { |
| 78 | + $inst = $condition->result($this->getCubex()); |
| 79 | + $res = $inst->process($this->getContext()); |
| 80 | + if($res !== null) |
| 81 | + { |
| 82 | + $this->_handled = $res; |
| 83 | + return true; |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return false; |
| 88 | + } |
| 89 | + |
| 90 | + public function interruptMethod(): mixed |
| 91 | + { |
| 92 | + return $this->_handled; |
| 93 | + } |
| 94 | +} |
0 commit comments