VersionableTrait   A
last analyzed

Complexity

Total Complexity 27

Size/Duplication

Total Lines 195
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
wmc 27
lcom 2
cbo 2
dl 0
loc 195
rs 10
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A enableVersioning() 0 5 1
A disableVersioning() 0 5 1
A setReasonAttribute() 0 4 1
A bootVersionableTrait() 0 11 1
A versions() 0 4 1
A currentVersion() 0 4 1
A previousVersion() 0 4 1
A getVersionModel() 0 8 2
A versionablePreSave() 0 7 2
B versionablePostSave() 0 23 7
A isValidForVersioning() 0 11 3
A getAuthUserId() 0 15 6
1
<?php
2
namespace Mpociot\Versionable;
3
4
use Exception;
5
use Illuminate\Support\Facades\Auth;
6
use Illuminate\Database\Eloquent\Relations\MorphMany;
7
8
/**
9
 * Class VersionableTrait
10
 * @package Mpociot\Versionable
11
 */
12
trait VersionableTrait
13
{
14
15
    /**
16
     * Private variable to detect if this is an update
17
     * or an insert
18
     * @var bool
19
     */
20
    private $updating;
21
22
    /**
23
     * Contains all dirty data that is valid for versioning
24
     *
25
     * @var array
26
     */
27
    private $versionableDirtyData;
28
29
    /**
30
     * Optional reason, why this version was created
31
     * @var string
32
     */
33
    private $reason;
34
35
    /**
36
     * Flag that determines if the model allows versioning at all
37
     * @var bool
38
     */
39
    protected $versioningEnabled = true;
40
41
    /**
42
     * @return $this
43
     */
44
    public function enableVersioning()
45
    {
46
        $this->versioningEnabled = true;
47
        return $this;
48
    }
49
50
    /**
51
     * @return $this
52
     */
53
    public function disableVersioning()
54
    {
55
        $this->versioningEnabled = false;
56
        return $this;
57
    }
58
59
    /**
60
     * Attribute mutator for "reason"
61
     * Prevent "reason" to become a database attribute of model
62
     *
63
     * @param string $value
64
     */
65
    public function setReasonAttribute($value)
66
    {
67
        $this->reason = $value;
68
    }
69
70
    /**
71
     * Initialize model events
72
     */
73
    public static function bootVersionableTrait()
74
    {
75
        static::saving(function ($model) {
76
            $model->versionablePreSave();
77
        });
78
79
        static::saved(function ($model) {
80
            $model->versionablePostSave();
81
        });
82
83
    }
84
85
    /**
86
     * Return all versions of the model
87
     * @return MorphMany
88
     */
89
    public function versions()
90
    {
91
        return $this->morphMany(Version::class, 'versionable');
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...
92
    }
93
94
    /**
95
     * Returns the latest version available
96
     * @return Version
97
     */
98
    public function currentVersion()
99
    {
100
        return $this->versions()->orderBy(Version::CREATED_AT, 'DESC')->first();
101
    }
102
103
    /**
104
     * Returns the previous version
105
     * @return Version
106
     */
107
    public function previousVersion()
108
    {
109
        return $this->versions()->orderBy(Version::CREATED_AT, 'DESC')->limit(1)->offset(1)->first();
110
    }
111
112
    /**
113
     * Get a model based on the version id
114
     *
115
     * @param $version_id
116
     *
117
     * @return $this|null
118
     */
119
    public function getVersionModel($version_id)
120
    {
121
        $version = $this->versions()->where("version_id", "=", $version_id)->first();
122
        if (!is_null($version)) {
123
            return $version->getModel();
124
        }
125
        return null;
126
    }
127
128
    /**
129
     * Pre save hook to determine if versioning is enabled and if we're updating
130
     * the model
131
     * @return void
132
     */
133
    protected function versionablePreSave()
134
    {
135
        if ($this->versioningEnabled === true) {
136
            $this->versionableDirtyData = $this->getDirty();
0 ignored issues
show
Bug introduced by
It seems like getDirty() 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...
137
            $this->updating             = $this->exists;
0 ignored issues
show
Bug introduced by
The property exists 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...
138
        }
139
    }
140
141
    /**
142
     * Save a new version.
143
     * @return void
144
     */
145
    protected function versionablePostSave()
146
    {
147
        /**
148
         * We'll save new versions on updating and first creation
149
         */
150
        if (
151
            ( $this->versioningEnabled === true && $this->updating && $this->isValidForVersioning() ) ||
152
            ( $this->versioningEnabled === true && !$this->updating )
153
        ) {
154
            // Save a new version
155
            $version                   = new Version();
156
            $version->versionable_id   = $this->getKey();
0 ignored issues
show
Bug introduced by
It seems like getKey() 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...
Documentation introduced by
The property versionable_id does not exist on object<Mpociot\Versionable\Version>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
157
            $version->versionable_type = get_class($this);
0 ignored issues
show
Documentation introduced by
The property versionable_type does not exist on object<Mpociot\Versionable\Version>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
158
            $version->user_id          = $this->getAuthUserId();
0 ignored issues
show
Documentation introduced by
The property user_id does not exist on object<Mpociot\Versionable\Version>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
159
            $version->model_data       = serialize($this->getAttributes());
0 ignored issues
show
Bug introduced by
It seems like getAttributes() 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...
Documentation introduced by
The property model_data does not exist on object<Mpociot\Versionable\Version>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
160
161
            if (!empty( $this->reason )) {
162
                $version->reason = $this->reason;
0 ignored issues
show
Documentation introduced by
The property reason does not exist on object<Mpociot\Versionable\Version>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
163
            }
164
165
            $version->save();
166
        }
167
    }
168
169
    /**
170
     * Determine if a new version should be created for this model.
171
     *
172
     * @return bool
173
     */
174
    private function isValidForVersioning()
175
    {
176
        $dontVersionFields = isset( $this->dontVersionFields ) ? $this->dontVersionFields : [];
0 ignored issues
show
Bug introduced by
The property dontVersionFields 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...
177
        $removeableKeys    = array_merge($dontVersionFields, [$this->getUpdatedAtColumn()]);
0 ignored issues
show
Bug introduced by
It seems like getUpdatedAtColumn() 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...
178
179
        if (method_exists($this, 'getDeletedAtColumn')) {
180
            $removeableKeys[] = $this->getDeletedAtColumn();
0 ignored issues
show
Bug introduced by
It seems like getDeletedAtColumn() 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...
181
        }
182
183
        return ( count(array_diff_key($this->versionableDirtyData, array_flip($removeableKeys))) > 0 );
184
    }
185
186
    /**
187
     * @return int|null
188
     */
189
    protected function getAuthUserId()
190
    {
191
        try {
192
            if (class_exists($class = '\Cartalyst\Sentry\Facades\Laravel\Sentry')
193
                || class_exists($class = '\Cartalyst\Sentinel\Laravel\Facades\Sentinel')
194
            ) {
195
                return ($class::check()) ? $class::getUser()->id : null;
196
            } elseif (Auth::check()) {
197
                return Auth::id();
198
            }
199
        } catch (Exception $e) {
200
            return null;
201
        }
202
        return null;
203
    }
204
205
206
}
207