UpdateTrait::addNonRequiredAttribute()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
namespace IanOlson\Support\Traits;
4
5
use Illuminate\Support\Arr;
6
7
trait UpdateTrait
8
{
9
    /**
10
     * Non-required attributes.
11
     *
12
     * @var array
13
     */
14
    protected $nonRequiredAttributes = [];
15
16
    /**
17
     * Add a non-required attribute.
18
     *
19
     * This method is used for adding attributes that can be left null or blank and should update the model
20
     * accordingly. For example a 'subscribedToNewsletter' column has a boolean. If this returns false then it will be
21
     * missed on the empty($value) check inside updateAttributes() method. This allows this to be set.
22
     *
23
     * @param string $attribute
24
     *
25
     * @return array
26
     */
27 6
    protected function addNonRequiredAttribute($attribute)
28
    {
29 6
        $this->nonRequiredAttributes = Arr::add($this->nonRequiredAttributes, $attribute, $attribute);
30
31 6
        return $this->nonRequiredAttributes;
32
    }
33
34
    /**
35
     * Remove a non-required attribute.
36
     *
37
     * @param string $attribute
38
     *
39
     * @return array
40
     */
41 2
    protected function removeNonRequiredAttribute($attribute)
42
    {
43 2
        Arr::forget($this->nonRequiredAttributes, $attribute);
44
45 2
        return $this->nonRequiredAttributes;
46
    }
47
48
    /**
49
     * Get non-required attributes.
50
     *
51
     * @return array
52
     */
53 20
    protected function getNonRequiredAttributes()
54
    {
55 20
        return $this->nonRequiredAttributes;
56
    }
57
58
    /**
59
     * Update attributes.
60
     *
61
     * @param $model
62
     * @param array $data
63
     */
64 18
    protected function updateAttributes(&$model, array &$data)
65
    {
66 18
        if (empty($data)) {
67 2
            return;
68
        }
69
70 16
        $massAssign = $model->getFillable();
71
72 16
        foreach ($data as $attribute => $value) {
73 16
            if (!in_array($attribute, $massAssign)) {
74 2
                continue;
75
            }
76
77 14
            if (in_array($attribute, $this->getNonRequiredAttributes())) {
78 2
                $model->$attribute = $value;
79 1
            }
80
81 14
            if (empty($value)) {
82 6
                continue;
83
            }
84
85 12
            if ($attribute == 'password') {
86 2
                $value = password_hash($value, PASSWORD_DEFAULT);
87 1
            }
88
89 12
            $model->$attribute = $value;
90 8
        }
91
92 16
        return;
93
    }
94
}
95