Passed
Push — master ( b3d4b4...d7be03 )
by Alexander
01:50
created

ModelExceptionTrait::saveOrThrow()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
ccs 0
cts 7
cp 0
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
crap 12
1
<?php
2
3
4
namespace Horat1us\Yii\Traits;
5
6
7
use yii\base\Model;
8
use yii\db\ActiveRecord;
9
use yii\db\ActiveRecordInterface;
10
11
/**
12
 * Class ModelExceptionTrait
13
 * @package Horat1us\Yii\Traits
14
 * @see \Exception
15
 */
16
trait ModelExceptionTrait
17
{
18
    /** @var Model */
19
    protected $model;
20
21
    /**
22
     * ModelExceptionTrait constructor.
23
     * @param Model $model
24
     * @param int $code
25
     * @param \Throwable $previous
26
     */
27
    public function __construct(Model $model, int $code = 0, \Throwable $previous = null)
28
    {
29
        $message = get_class($model) . " validation errors";
30
        parent::__construct($message, $code, $previous);
31
32
        $this->model = $model;
33
    }
34
35
    /**
36
     * @return Model
37
     */
38
    public function getModel(): Model
39
    {
40
        return $this->model;
41
    }
42
43
44
    /**
45
     * @param Model $model
46
     * @return Model
47
     */
48
    public static function validateOrThrow(Model $model): Model
49
    {
50
        if (!$model->validate()) {
51
            throw new static($model);
52
        }
53
        return $model;
54
    }
55
56
    /**
57
     * @param ActiveRecordInterface $record
58
     * @return ActiveRecordInterface|ActiveRecord
59
     */
60
    public static function saveOrThrow(ActiveRecordInterface $record): ActiveRecordInterface
61
    {
62
        if (!$record->save() && $record instanceof Model) {
63
            throw new static($record);
64
        }
65
        return $record;
66
    }
67
68
    /**
69
     * @param string $attribute
70
     * @param string $error
71
     * @param Model $model
72
     */
73
    public static function addAndThrow(string $attribute, string $error, Model $model)
74
    {
75
        $model->addError($attribute, $error);
76
        throw new static($model);
77
    }
78
}