Histroiable::saveChanges()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/**************************************************************************
3
 * Copyright (C) iFeras93, Inc - All Rights Reserved
4
 *
5
 *
6
 * @file        BeHistroiable.php
7
 * @author      Firas
8
 * @project     HistoriableModel
9
 * @date        2/16/2020
10
 */
11
12
namespace Iferas93\HistoriableModel\Traits\History;
13
14
use Illuminate\Database\Eloquent\Model;
15
use Illuminate\Support\Arr;
16
17
trait Histroiable
18
{
19
    public static function bootHistroiable()
20
    {
21
        static::updated(function (Model $model) {
22
            $columns = $model->getChangedColumns($model);
23
            collect($columns)->each(function ($column) use ($model) {
24
                $model->saveChanges($column);
25
            });
26
        });
27
    }
28
29
    private function getChangedColumns(Model $model)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
30
    {
31
        $original = $model->getOriginal();
32
33
        return collect(Arr::except($model->getChanges(), $this->ignoredColumns()))->map(function ($change, $column) use ($original) {
34
            return new ColumnChanges($column, Arr::get($original, $column), $change);
35
        });
36
    }
37
38
    protected function ignoredColumns()
39
    {
40
        return [
41
            'updated_at',
42
        ];
43
    }
44
45
    private function saveChanges(ColumnChanges $column)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
46
    {
47
        $this->history()->create([
48
            'changed_column' => $column->column,
49
            'value_from' => $column->from,
50
            'value_to' => $column->to,
51
        ]);
52
    }
53
54
    public function history()
55
    {
56
        return $this->morphMany(config('historiable.model'), 'Historiable');
0 ignored issues
show
Bug introduced by
It seems like morphMany() 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...
57
    }
58
}
59