Completed
Push — return-no-cache-when-server-do... ( 8f8df4...c2373e )
by Akihito
05:28
created

CacheInterceptor::errorLog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\QueryRepository\Exception\LogicException;
8
use BEAR\QueryRepository\Exception\RuntimeException;
9
use BEAR\Resource\ResourceObject;
10
use Ray\Aop\MethodInterceptor;
11
use Ray\Aop\MethodInvocation;
12
13
class CacheInterceptor implements MethodInterceptor
14
{
15
    /**
16
     * @var QueryRepositoryInterface
17
     */
18
    private $repository;
19
20
    public function __construct(
21
        QueryRepositoryInterface $repository
22
    ) {
23
        $this->repository = $repository;
24
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public function invoke(MethodInvocation $invocation)
30
    {
31
        /** @var ResourceObject $ro */
32
        $ro = $invocation->getThis();
33
        try {
34
            $stored = $this->repository->get($ro->uri);
35
        } catch (LogicException|RuntimeException $e) {
36
            throw $e;
37
        } catch (\Exception $e) {
38
            $this->errorLog($e);
39
40
            return $invocation->proceed();
41
        }
42
        if ($stored) {
43
            list($ro->uri, $ro->code, $ro->headers, $ro->body, $ro->view) = $stored;
44
45
            return $ro;
46
        }
47
        try {
48
            $ro = $invocation->proceed();
49
            $ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri);
50
        } catch (LogicException|RuntimeException $e) {
51
            throw $e;
52
        } catch (\Exception $e) {
53
            $this->errorLog($e);
54
        }
55
56
        return $ro;
57
    }
58
59
    private function errorLog(\Exception $e) : void
60
    {
61
        $message = sprintf('%s: %s in %s:%s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine());
62
        syslog(LOG_CRIT, $message);
63
    }
64
}
65