Validatable   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 92.31%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 1
dl 0
loc 52
ccs 12
cts 13
cp 0.9231
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
getRules() 0 1 ?
A validate() 0 10 2
A getValidator() 0 4 1
A bootValidatable() 0 12 1
1
<?php
2
3
namespace Moo\FlashCard\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Validator;
7
8
/**
9
 * Trait Validatable execute validation rules before creating or updating model attributes
10
 */
11
trait Validatable
12
{
13
    /**
14
     * Boot the trait.
15
     */
16 15
    protected static function bootValidatable()
17
    {
18
        // Hook to execute before creating
19
        static::creating(function (Model $model) {
20 15
            $model->validate();
21 15
        });
22
23
        // Hook to execute before updating
24
        static::updating(function (Model $model) {
25
            $model->validate();
26 15
        });
27 15
    }
28
29
    /**
30
     * Validates current attributes against rules
31
     *
32
     * @return bool
33
     * @throws \DomainException
34
     */
35 15
    public function validate()
36
    {
37 15
        $validator = $this->getValidator();
38
39 15
        if ($validator->fails()) {
40 2
            throw new \InvalidArgumentException($validator->errors()->first());
41
        }
42
43 14
        return true;
44
    }
45
46
    /**
47
     * Get instance of validator
48
     *
49
     * @return \Illuminate\Validation\Validator
50
     */
51 15
    public function getValidator(): \Illuminate\Validation\Validator
52
    {
53 15
        return Validator::make($this->attributes, $this->getRules());
0 ignored issues
show
Bug introduced by
The property attributes does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
54
    }
55
56
    /**
57
     * Required method that provide collection or rules
58
     *
59
     * @return array
60
     */
61
    abstract protected function getRules(): array;
62
}
63