TransactionInvoker::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 7

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
cc 4
nc 7
nop 3
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
6
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
7
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
8
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
9
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
11
 * THE SOFTWARE.
12
 *
13
 * This software consists of voluntary contributions made by many individuals
14
 * and is licensed under the MIT license.
15
 *
16
 * Copyright (c) 2015-2020 Yuuki Takezawa
17
 *
18
 */
19
20
namespace Ytake\LaravelAspect\Transaction;
21
22
use Illuminate\Database\DatabaseManager;
23
use Illuminate\Database\QueryException;
24
25
/**
26
 * Class TransactionInvoker
27
 */
28
class TransactionInvoker implements Runnable
29
{
30
    /** @var string */
31
    protected $connection;
32
33
    /**
34
     * TransactionInvoker constructor.
35
     *
36
     * @param string|null $connection
37
     */
38
    public function __construct($connection)
39
    {
40
        $this->connection = $connection;
41
    }
42
43
    /**
44
     * @param DatabaseManager $databaseManager
45
     * @param string          $exceptionName
46
     * @param callable        $invoker
47
     *
48
     * @return mixed
49
     * @throws \Exception
50
     */
51
    public function __invoke(DatabaseManager $databaseManager, string $exceptionName, callable $invoker)
52
    {
53
        $database = $databaseManager->connection($this->connection);
54
        $database->beginTransaction();
55
        try {
56
            $result = $invoker($databaseManager, $exceptionName);
57
            $database->commit();
58
        } catch (\Exception $exception) {
59
            // for default Exception
60
            if ($exception instanceof QueryException) {
61
                $database->rollBack();
62
                throw $exception;
63
            }
64
            if ($exception instanceof $exceptionName) {
65
                $database->rollBack();
66
                throw $exception;
67
            }
68
            $database->rollBack();
69
            throw $exception;
70
        }
71
72
        return $result;
73
    }
74
}
75