Version   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 118
Duplicated Lines 6.78 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 84.09%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 6
dl 8
loc 118
rs 10
c 0
b 0
f 0
ccs 37
cts 44
cp 0.8409

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A boot() 0 13 2
A user() 0 7 1
A versionable() 0 4 1
A createForModel() 5 21 2
A revert() 0 4 1
A diff() 3 16 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * CalamandreiLorenzo\LaravelVersionable
4
 *
5
 * This file is part of the overtrue/laravel-versionable.
6
 * ------------------------------------------------------
7
 * (c) overtrue <[email protected]>
8
 * This source file is subject to the MIT license that is bundled.
9
 */
10
11
namespace CalamandreiLorenzo\LaravelVersionable;
12
13
use CalamandreiLorenzo\LaravelVersionable\Exceptions\NotVersionableModel;
14
use Illuminate\Database\Eloquent\Model;
15
use Illuminate\Database\Eloquent\Relations\BelongsTo;
16
use Illuminate\Database\Eloquent\Relations\MorphTo;
17
use Illuminate\Database\Eloquent\SoftDeletes;
18
use Illuminate\Support\Arr;
19
use Illuminate\Support\Str;
20
use SebastianBergmann\Diff\Differ;
21
use function array_keys;
22
use function auth;
23
use function class_uses;
24
use function config;
25
use function in_array;
26
27
/**
28
 * Class Version.
29
 *
30
 * @property $id
31
 * @property Model $versionable
32
 * @property array $contents
33
 * @property int $version_number
34
 * @property $versionable_id
35
 * @property $versionable_type
36
 */
37
class Version extends Model
38
{
39
    use SoftDeletes;
40
41
    /**
42
     * @var string[] $casts
43
     */
44
    protected $casts = [
45
        'contents' => 'array',
46
    ];
47
48 8
    public function __construct(array $attributes = [])
49
    {
50
        if (
51 8
            config('versionable.key_type', VersionPrimaryKey::UUID)
52 8
            === VersionPrimaryKey::UUID
53
        ) {
54 8
            $this->keyType = "string";
55
        }
56 8
        parent::__construct($attributes);
57 8
    }
58
59
    /**
60
     * boot
61
     */
62 8
    protected static function boot(): void
63
    {
64 8
        parent::boot();
65
66
        self::creating(static function (Version $version) {
67
            if (
68 8
                config('versionable.key_type', VersionPrimaryKey::UUID)
69 8
                    === VersionPrimaryKey::UUID
70
            ) {
71 8
                $version->id = Str::uuid();
72
            }
73 8
        });
74 8
    }
75
76
    /**
77
     * @return BelongsTo
78
     */
79
    public function user(): BelongsTo
80
    {
81
        return $this->belongsTo(
82
            config('versionable.user_model'),
83
            config('versionable.user_foreign_key')
84
        );
85
    }
86
87
    /**
88
     * @return MorphTo
89
     */
90 2
    public function versionable(): MorphTo
91
    {
92 2
        return $this->morphTo('versionable');
93
    }
94
95
    /**
96
     * createForModel
97
     * @param Versionable|Model $model
0 ignored issues
show
Documentation introduced by
Consider making the type for parameter $model a bit more specific; maybe use Model.
Loading history...
98
     * @return Version
99
     * @throws NotVersionableModel
100
     */
101 8
    public static function createForModel(Model $model): Version
102
    {
103 8 View Code Duplication
        if (!in_array(Versionable::class, class_uses($model), true)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
            throw new NotVersionableModel(
105
                "{$model} not use Versionable " . config('versionable.version_model')
106
            );
107
        }
108 8
        $versionClass = $model->getVersionModel();
109
        /** @var Version $version */
110 8
        $version = new $versionClass();
111 8
        $version->version_number = ((int) $versionClass::where('versionable_id', $model->getKey())
112 8
            ->where('versionable_type', $model->getMorphClass())
113 8
            ->max('version_number')) + 1;
114 8
        $version->versionable_id = $model->getKey();
115 8
        $version->versionable_type = $model->getMorphClass();
116 8
        $version->{config('versionable.user_foreign_key')} = auth()->id();
0 ignored issues
show
Bug introduced by
The method id does only exist in Illuminate\Contracts\Auth\Guard, but not in Illuminate\Contracts\Auth\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
117 8
        $version->contents = $model->getVersionableAttributes();
118
119 8
        $version->save();
120 8
        return $version;
121
    }
122
123
    /**
124
     * @return bool
125
     */
126 1
    public function revert(): bool
127
    {
128 1
        return $this->versionable->fill($this->contents)->save();
129
    }
130
131
    /**
132
     * diff
133
     * @param Versionable|Model|null $model
0 ignored issues
show
Documentation introduced by
Consider making the type for parameter $model a bit more specific; maybe use null|Model.
Loading history...
134
     *
135
     * @return string
136
     * @throws NotVersionableModel
137
     */
138 1
    public function diff(Model $model = null): string
139
    {
140 1
        $model || $model = $this->versionable;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $model. This often makes code more readable.
Loading history...
141
142 1
        if ($model instanceof self) {
143 1
            $source = $model->contents;
144
        } else {
145 1 View Code Duplication
            if (!in_array(Versionable::class, class_uses($model), true)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
146
                throw new NotVersionableModel("{$model} is not versionable");
147
            }
148
149 1
            $source = $model->versionableFromArray($this->versionable->toArray());
0 ignored issues
show
Bug introduced by
The method versionableFromArray cannot be called on $model (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
150
        }
151
152 1
        return (new Differ())->diff(Arr::only($source, array_keys($this->contents)), $this->contents);
153
    }
154
}
155