Completed
Push — master ( e214ab...401ef4 )
by yuuki
02:09
created

TransactionInvoker   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 3
dl 0
loc 47
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B __invoke() 0 23 4
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-2017 Yuuki Takezawa
16
 *
17
 */
18
19
namespace Ytake\LaravelAspect\Transaction;
20
21
use Illuminate\Database\DatabaseManager;
22
use Illuminate\Database\QueryException;
23
24
/**
25
 * Class TransactionInvoker
26
 */
27
class TransactionInvoker implements Runnable
28
{
29
    /** @var string */
30
    protected $connection;
31
32
    /**
33
     * TransactionInvoker constructor.
34
     *
35
     * @param string $connection
36
     */
37
    public function __construct($connection)
38
    {
39
        $this->connection = $connection;
40
    }
41
42
    /**
43
     * @param DatabaseManager $databaseManager
44
     * @param string          $exceptionName
45
     * @param callable        $invoker
46
     *
47
     * @return mixed
48
     * @throws \Exception
49
     */
50
    public function __invoke(DatabaseManager $databaseManager, $exceptionName, callable $invoker)
51
    {
52
        $database = $databaseManager->connection($this->connection);
53
        $database->beginTransaction();
54
        try {
55
            $result = $invoker($databaseManager, $exceptionName);
56
            $database->commit();
57
        } catch (\Exception $exception) {
58
            // for default Exception
59
            if ($exception instanceof QueryException) {
60
                $database->rollBack();
61
                throw $exception;
62
            }
63
            if ($exception instanceof $exceptionName) {
64
                $database->rollBack();
65
                throw $exception;
66
            }
67
            $database->rollBack();
68
            throw $exception;
69
        }
70
71
        return $result;
72
    }
73
}
74