Completed
Push — master ( 203a68...d4d7bc )
by yuuki
15s queued 10s
created

TransactionalInterceptor::invoke()   B

Complexity

Conditions 4
Paths 7

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 2
Metric Value
c 4
b 1
f 2
dl 0
loc 27
rs 8.5806
cc 4
eloc 18
nc 7
nop 1
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 Illuminate\Database\QueryException;
23
use Illuminate\Database\DatabaseManager;
24
use Ytake\LaravelAspect\Annotation\AnnotationReaderTrait;
25
26
/**
27
 * Class TransactionalInterceptor
28
 */
29
class TransactionalInterceptor implements MethodInterceptor
30
{
31
    use AnnotationReaderTrait;
32
33
    /** @var DatabaseManager  */
34
    protected static $databaseManager;
35
36
    /**
37
     * @param MethodInvocation $invocation
38
     * @return object
39
     * @throws \Exception
40
     */
41
    public function invoke(MethodInvocation $invocation)
42
    {
43
        $annotation = $this->reader
44
            ->getMethodAnnotation($invocation->getMethod(), $this->annotation);
45
46
        $connection = $annotation->value;
47
        /** @var \Illuminate\Database\ConnectionInterface $database */
48
        $database = self::$databaseManager->connection($connection);
49
        $database->beginTransaction();
50
        try {
51
            $result = $invocation->proceed();
52
            $database->commit();
53
54
            return $result;
55
        } catch (\Exception $exception) {
56
            // for default Exception
57
            if ($exception instanceof QueryException) {
58
                $database->rollBack();
59
                throw $exception;
60
            }
61
            if ($exception instanceof $annotation->expect) {
62
                $database->rollBack();
63
                throw $exception;
64
            }
65
            throw $exception;
66
        }
67
    }
68
69
    /**
70
     * @param DatabaseManager $databaseManager
71
     */
72
    public function setDatabaseManager(DatabaseManager $databaseManager)
73
    {
74
        self::$databaseManager = $databaseManager;
75
    }
76
}
77