Completed
Push — master ( d54c31...1808a2 )
by Razon
02:09
created

SafeActionTrait::run()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 2
nc 2
nop 2
1
<?php
2
namespace App\Http\Rest;
3
4
use App\Helper\DbHelper;
5
use yii\db\ActiveRecord;
6
use yii\db\Connection;
7
8
/**
9
 * @property string $modelClass
10
 */
11
trait SafeActionTrait
12
{
13
    public $enableTransaction = true;
14
15
    public function run($id = null, callable $callback = null)
16
    {
17
        $run = $callback ?? [$this, 'parent::run'];
18
        $args = array_filter([$id]);
19
        
20
        if (!$this->enableTransaction) {
21
            return call_user_func_array($run, $args);
22
        }
23
24
        return DbHelper::transaction($run, $args, $this->getDb());
25
    }
26
27
    public function getDb(): Connection
28
    {
29
        /** @var ActiveRecord $modelClass */
30
        $modelClass = $this->modelClass;
31
        /** @var Connection $db */
32
        return $modelClass::getDb();
33
    }
34
}
35