|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|
5
|
|
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|
6
|
|
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|
7
|
|
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|
8
|
|
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|
9
|
|
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
|
10
|
|
|
* THE SOFTWARE. |
|
11
|
|
|
* |
|
12
|
|
|
* This software consists of voluntary contributions made by many individuals |
|
13
|
|
|
* and is licensed under the MIT license. |
|
14
|
|
|
* |
|
15
|
|
|
* Copyright (c) 2015-2016 Yuuki Takezawa |
|
16
|
|
|
* |
|
17
|
|
|
*/ |
|
18
|
|
|
namespace Ytake\LaravelAspect\Interceptor; |
|
19
|
|
|
|
|
20
|
|
|
use Ray\Aop\MethodInvocation; |
|
21
|
|
|
use Ray\Aop\MethodInterceptor; |
|
22
|
|
|
use Ytake\LaravelAspect\Annotation\RetryOnFailure; |
|
23
|
|
|
use Ytake\LaravelAspect\Annotation\AnnotationReaderTrait; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Class RetryOnFailureInterceptor |
|
27
|
|
|
*/ |
|
28
|
|
|
class RetryOnFailureInterceptor implements MethodInterceptor |
|
29
|
|
|
{ |
|
30
|
|
|
use AnnotationReaderTrait; |
|
31
|
|
|
|
|
32
|
|
|
/** @var int|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
|
|
|
if (self::$attempt === null) { |
|
46
|
|
|
self::$attempt = $annotation->attempts; |
|
47
|
|
|
} |
|
48
|
|
|
try { |
|
49
|
|
|
self::$attempt--; |
|
50
|
|
|
|
|
51
|
|
|
return $invocation->proceed(); |
|
52
|
|
|
} catch (\Exception $e) { |
|
53
|
|
|
if (ltrim($annotation->ignore, '\\') === get_class($e)) { |
|
54
|
|
|
self::$attempt = null; |
|
55
|
|
|
throw $e; |
|
56
|
|
|
} |
|
57
|
|
|
$pass = array_filter($annotation->types, function ($values) use ($e) { |
|
58
|
|
|
return ltrim($values, '\\') === get_class($e); |
|
59
|
|
|
}); |
|
60
|
|
|
if ($pass !== false) { |
|
61
|
|
|
if (self::$attempt > 0) { |
|
62
|
|
|
sleep($annotation->delay); |
|
63
|
|
|
|
|
64
|
|
|
return $invocation->proceed(); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
self::$attempt = null; |
|
68
|
|
|
throw $e; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|