1 | <?php |
||
28 | class RetryOnFailureInterceptor implements MethodInterceptor |
||
29 | { |
||
30 | use AnnotationReaderTrait; |
||
31 | |||
32 | /** @var array|null */ |
||
33 | private static $attempt = null; |
||
34 | |||
35 | /** |
||
36 | * @param MethodInvocation $invocation |
||
37 | * |
||
38 | * @return object |
||
39 | * @throws \Exception |
||
40 | */ |
||
41 | public function invoke(MethodInvocation $invocation) |
||
42 | { |
||
43 | /** @var RetryOnFailure $annotation */ |
||
44 | $annotation = $invocation->getMethod()->getAnnotation($this->annotation); |
||
45 | $key = $this->keyName($invocation); |
||
46 | |||
47 | if (isset(self::$attempt[$key]) === false) { |
||
48 | self::$attempt[$key] = $annotation->attempts; |
||
49 | } |
||
50 | |||
51 | try { |
||
52 | self::$attempt[$key]--; |
||
53 | |||
54 | return $invocation->proceed(); |
||
55 | } catch (\Exception $e) { |
||
56 | if (ltrim($annotation->ignore, '\\') === get_class($e)) { |
||
57 | self::$attempt[$key] = null; |
||
58 | throw $e; |
||
59 | } |
||
60 | |||
61 | $pass = array_filter($annotation->types, function ($values) use ($e) { |
||
62 | return ltrim($values, '\\') === get_class($e); |
||
63 | }); |
||
64 | if ($pass !== false) { |
||
65 | if (self::$attempt[$key] > 0) { |
||
66 | sleep($annotation->delay); |
||
67 | |||
68 | return $invocation->proceed(); |
||
69 | } |
||
70 | } |
||
71 | self::$attempt[$key] = null; |
||
72 | throw $e; |
||
73 | } |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * @param MethodInvocation $invocation |
||
78 | * |
||
79 | * @return string |
||
80 | */ |
||
81 | protected function keyName(MethodInvocation $invocation) |
||
85 | } |
||
86 |