bearsunday /
BEAR.QueryRepository
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace BEAR\QueryRepository; |
||
| 6 | |||
| 7 | use BEAR\QueryRepository\Exception\LogicException; |
||
| 8 | use BEAR\Resource\ResourceObject; |
||
| 9 | use Override; |
||
| 10 | use Ray\Aop\MethodInterceptor; |
||
| 11 | use Ray\Aop\MethodInvocation; |
||
| 12 | use Throwable; |
||
| 13 | |||
| 14 | use function assert; |
||
| 15 | use function sprintf; |
||
| 16 | use function trigger_error; |
||
| 17 | |||
| 18 | use const E_USER_WARNING; |
||
| 19 | |||
| 20 | final readonly class CacheInterceptor implements MethodInterceptor |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 21 | { |
||
| 22 | public function __construct( |
||
| 23 | private QueryRepositoryInterface $repository, |
||
| 24 | ) { |
||
| 25 | } |
||
| 26 | |||
| 27 | /** |
||
| 28 | * {@inheritDoc} |
||
| 29 | */ |
||
| 30 | #[Override] |
||
| 31 | public function invoke(MethodInvocation $invocation) |
||
| 32 | { |
||
| 33 | $ro = $invocation->getThis(); |
||
| 34 | assert($ro instanceof ResourceObject); |
||
| 35 | try { |
||
| 36 | $state = $this->repository->get($ro->uri); |
||
| 37 | } catch (Throwable $e) { |
||
| 38 | $this->triggerWarning($e); |
||
| 39 | |||
| 40 | return $invocation->proceed(); // @codeCoverageIgnore |
||
| 41 | } |
||
| 42 | |||
| 43 | if ($state instanceof ResourceState) { |
||
| 44 | $state->visit($ro); |
||
| 45 | |||
| 46 | return $ro; |
||
| 47 | } |
||
| 48 | |||
| 49 | /** @psalm-suppress MixedAssignment */ |
||
| 50 | $ro = $invocation->proceed(); |
||
| 51 | assert($ro instanceof ResourceObject); |
||
| 52 | try { |
||
| 53 | $ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri); |
||
| 54 | } catch (LogicException $e) { |
||
| 55 | throw $e; |
||
| 56 | } catch (Throwable $e) { // @codeCoverageIgnore |
||
| 57 | $this->triggerWarning($e); // @codeCoverageIgnore |
||
| 58 | } |
||
| 59 | |||
| 60 | return $ro; |
||
| 61 | } |
||
| 62 | |||
| 63 | /** |
||
| 64 | * Trigger warning |
||
| 65 | * |
||
| 66 | * When the cache server is down, it will issue a warning rather than an exception to continue service. |
||
| 67 | * |
||
| 68 | * @codeCoverageIgnore |
||
| 69 | */ |
||
| 70 | private function triggerWarning(Throwable $e): void |
||
| 71 | { |
||
| 72 | $message = sprintf('%s: %s in %s:%s', $e::class, $e->getMessage(), $e->getFile(), $e->getLine()); |
||
| 73 | trigger_error($message, E_USER_WARNING); |
||
| 74 | } |
||
| 75 | } |
||
| 76 |