GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( bbff05...e10ea1 )
by Victor
04:06
created

Approvable::currentUserCanApprove()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 0
1
<?php
2
3
namespace Victorlap\Approvable;
4
5
use Illuminate\Database\Eloquent\Relations\MorphMany;
6
use Illuminate\Support\Facades\Auth;
7
use Illuminate\Support\Facades\DB;
8
9
/**
10
 * Class Approvable
11
 * @package Victorlap\Approvable
12
 */
13
trait Approvable
14
{
15
16
    /**
17
     * @var array
18
     */
19
    protected $approveOf = array();
20
21
    /**
22
     * @var array
23
     */
24
    protected $dontApproveOf = array();
25
26
    /**
27
     * Create the event listeners for the saving event
28
     * This lets us save approvals whenever a save is made, no matter the
29
     * http method
30
     */
31
    public static function bootApprovable()
32
    {
33
        static::saving(function ($model) {
34
            return $model->preSave();
35
        });
36
    }
37
38
    /**
39
     * @return MorphMany
40
     */
41
    public function approvals()
42
    {
43
        return $this->morphMany(Approval::class, 'approvable');
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...
44
    }
45
46
    /**
47
     * Check if this model has pending changes,
48
     * If an attribute is provided, check if the attribute has pending changes.
49
     *
50
     * @param null $attribute
51
     * @return bool
52
     */
53
    public function isPendingApproval($attribute = null)
54
    {
55
        return $this->approvals()
56
                ->when($attribute !== null, function ($query) use ($attribute) {
57
                    $query->where('key', $attribute);
58
                })
59
                ->where('approved', false)
60
                ->count() > 0;
61
    }
62
63
    /**
64
     * Generates a list of the last $limit approvals to any objects of the class it is being called from.
65
     * @param int $limit
66
     * @param string $order
67
     * @return mixed
68
     */
69
    public function classApprovals($limit = 100, $order = 'desc')
70
    {
71
        return Approval::where('approvable_type', get_called_class())
72
            ->orderBy('updated_at', $order)->limit($limit)->get();
73
    }
74
75
    /**
76
     * Invoked before a model is saved. Return false to abort the operation.
77
     * @return bool
78
     */
79
    public function preSave()
80
    {
81
        if ($this->currentUserCanApprove()) {
82
            // If the user is able to approve edits, do nothing.
83
            return true;
84
        }
85
86
        if (!$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...
87
            // There is currently no way (implemented) to enable this for new models.
88
            return true;
89
        }
90
91
        $changes_to_record = $this->changedApprovableFields();
92
93
        $approvals = array();
94
        foreach ($changes_to_record as $key => $change) {
95
            $approvals[] = array(
96
                'approvable_type' => $this->getMorphClass(),
0 ignored issues
show
Bug introduced by
It seems like getMorphClass() 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...
97
                'approvable_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...
98
                'key' => $key,
99
                'value' => $this->attributes[$key],
0 ignored issues
show
Bug introduced by
The property attributes 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...
100
                'user_id' => $this->getSystemUserId(),
101
                'created_at' => new \DateTime(),
102
                'updated_at' => new \DateTime(),
103
            );
104
        }
105
106
        if (count($approvals) > 0) {
107
            $approval = new Approval();
108
            DB::table($approval->getTable())->insert($approvals);
109
        }
110
111
        return true;
112
    }
113
114
    /**
115
     * Get all of the changes that have been made, that are also supposed
116
     * to be approved.
117
     *
118
     * @return array fields with new data, that should be recorded
119
     */
120
    private function changedApprovableFields()
121
    {
122
        $dirty = $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...
123
        $changes_to_record = array();
124
125
        foreach ($dirty as $key => $value) {
126
            if ($this->isApprovable($key)) {
127
                if (!isset($this->original[$key]) || $this->original[$key] != $this->attributes[$key]) {
128
                    $changes_to_record[$key] = $value;
129
130
                    // Reset changes that we want to approve
131
                    if (!isset($this->original[$key])) {
132
                        unset($this->attributes[$key]);
133
                    } else {
134
                        $this->attributes[$key] = $this->original[$key];
0 ignored issues
show
Bug introduced by
The property original 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...
135
                    }
136
                }
137
            }
138
        }
139
140
        return $changes_to_record;
141
    }
142
143
    /**
144
     * @param $key
145
     * @return bool
146
     */
147
    private function isApprovable($key)
148
    {
149
        if (isset($this->approveOf) && in_array($key, $this->approveOf)) {
150
            return true;
151
        }
152
        if (isset($this->dontApproveOf) && in_array($key, $this->dontApproveOf)) {
153
            return false;
154
        }
155
156
        return empty($this->approveOf);
157
    }
158
159
    /**
160
     * @return mixed|null
161
     */
162
    protected function getSystemUserId()
163
    {
164
        if (Auth::check()) {
165
            return Auth::user()->getAuthIdentifier();
166
        }
167
        return null;
168
    }
169
170
    /**
171
     * @return bool
172
     */
173
    protected function currentUserCanApprove()
174
    {
175
        return Auth::check() && Auth::user()->can('approve', $this);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Auth\Authenticatable as the method can() does only exist in the following implementations of said interface: Illuminate\Foundation\Auth\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
176
    }
177
}
178