Completed
Pull Request — master (#1)
by Tyler
03:00
created

AutoValidate::getValidationRules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Tylercd100\Database\Eloquent\Traits;
4
5
use Tylercd100\Database\Eloquent\Exceptions\ValidationException;
6
use Illuminate\Support\Facades\Validator;
7
8
trait AutoValidate
9
{
10
    /**
11
     * An array of validation rules
12
     * @var array
13
     */
14
    protected $rules = [];
15
16
    /**
17
     * An array of validation messages
18
     * @var array
19
     */
20
    protected $messages = [];
21
22
    /**
23
     * A method best used to register Eloquent events when the model boots up
24
     * @return void
25
     */
26
    protected static function boot()
27
    {
28
        self::saving(function ($model) {
29
            if (!$model->validate()) {
30
                return false;
31
            }
32
        });
33
    }
34
35
    /**
36
     * Validates the Model
37
     * @return boolean Whether or not the input is valid
38
     */
39
    public function validate()
40
    {
41
        $data = $this->toArray();
0 ignored issues
show
Bug introduced by
It seems like toArray() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
42
        $rules = $this->getValidationRules();
43
        $messages = $this->getValidationMessages();
44
45
        $validator = Validator::make($data, $rules, $messages);
46
        
47
        if ($validator->fails()) {
48
            throw new ValidationException($validator->errors()->first());
49
        } else {
50
            return true;
51
        }
52
    }
53
54
    /**
55
     * Returns an array of validation rules
56
     * @return array An Array of validation rules
57
     */
58
    protected function getValidationRules()
59
    {
60
        return $this->rules;
61
    }
62
63
    /**
64
     * Returns an array of validation messages
65
     * @return array An Array of validation messages
66
     */
67
    protected function getValidationMessages()
68
    {
69
        return $this->messages;
70
    }
71
}
72