Completed
Push — master ( d7caaf...048f0c )
by Mahmoud
04:10
created

RequestTrait::failedValidation()   A

Complexity

Conditions 1
Paths 1

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 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace App\Ship\Parents\Requests;
4
5
use App\Containers\Authorization\Traits\AuthorizationTrait;
6
use App\Ship\Engine\Traits\HashIdTrait;
7
use App\Ship\Features\Exceptions\ValidationFailedException;
8
use Illuminate\Contracts\Validation\Validator;
9
use Illuminate\Foundation\Http\FormRequest as LaravelFormRequest;
10
11
/**
12
 * Class RequestTrait
13
 *
14
 * @author  Mahmoud Zalt  <[email protected]>
15
 */
16
trait RequestTrait
17
{
18
19
    /**
20
     * Overriding this function to modify the any user input before
21
     * applying the validation rules.
22
     *
23
     * @return  array
24
     */
25
    public function all()
26
    {
27
        $requestData = parent::all();
28
29
        $requestData = $this->applyValidationRulesToUrlParams($requestData);
30
31
        $requestData = $this->decodeHashedIdsBeforeApplyingValidationRules($requestData);
0 ignored issues
show
Bug introduced by
It seems like decodeHashedIdsBeforeApplyingValidationRules() 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...
32
33
        return $requestData;
34
    }
35
36
    /**
37
     * Overriding this function to throw a custom
38
     * exception instead of the default Laravel exception.
39
     *
40
     * @param \Illuminate\Contracts\Validation\Validator $validator
41
     *
42
     * @return mixed|void
43
     */
44
    public function failedValidation(Validator $validator)
45
    {
46
        throw new ValidationFailedException($validator->getMessageBag());
47
    }
48
49
50
    /**
51
     * Used from the `authorize` function if the Request class.
52
     * To call functions and compare their bool responses to determine
53
     * if the user can proceed with the request or not.
54
     *
55
     * @param array $functions
56
     *
57
     * @return  bool
58
     */
59
    protected function check(array $functions)
60
    {
61
        $orIndicator = '|';
62
        $returns = [];
63
64
        // iterate all functions in the array
65
        foreach ($functions as $function) {
66
67
            // in case the value doesn't contains a separator (single function per key)
68
            if (!strpos($function, $orIndicator)) {
69
                // simply call the single function and store the response.
70
                $returns[] = $this->{$function}();
71
            } else {
72
                // in case the value contains a separator (multiple functions per key)
73
                $orReturns = [];
74
75
                // iterate over each function in the key
76
                foreach (explode($orIndicator, $function) as $orFunction) {
77
                    // dynamically call each function
78
                    $orReturns[] = $this->{$orFunction}();
79
                }
80
81
                // if in_array returned `true` means at least one function returned `true` thus return `true` to allow access.
82
                // if in_array returned `false` means no function returned `true` thus return `false` to prevent access.
83
                // return single boolean for all the functions found inside the same key.
84
                $returns[] = in_array(true, $orReturns) ? true : false;
85
            }
86
        }
87
88
        // if in_array returned `true` means a function returned `false` thus return `false` to prevent access.
89
        // if in_array returned `false` means all functions returned `true` thus return `true` to allow access.
90
        // return the final boolean
91
        return in_array(false, $returns) ? false : true;
92
    }
93
94
    /**
95
     * apply validation rules to the ID's in the URL, since Laravel
96
     * doesn't validate them by default!
97
     *
98
     * Now you can use validation riles like this: `'id' => 'required|integer|exists:items,id'`
99
     *
100
     * @param array $requestData
101
     *
102
     * @return  array
103
     */
104
    private function applyValidationRulesToUrlParams(Array $requestData)
105
    {
106
        if (isset($this->urlParameters) && !empty($this->urlParameters)) {
107
            foreach ($this->urlParameters as $param) {
0 ignored issues
show
Bug introduced by
The property urlParameters 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...
108
                $requestData[$param] = $this->route($param);
0 ignored issues
show
Bug introduced by
It seems like route() 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...
109
            }
110
        }
111
112
        return $requestData;
113
    }
114
115
    /**
116
     * @param $user
117
     *
118
     * @return  array
119
     */
120 View Code Duplication
    private function hasAnyPermissionAccess($user)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
121
    {
122
        if (!array_key_exists('permissions', $this->access) || !$this->access['permissions']) {
0 ignored issues
show
Bug introduced by
The property access 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...
123
            return [];
124
        }
125
126
        $permissions = explode('|', $this->access['permissions']);
127
128
        $hasAccess = array_map(function ($permission) use ($user) {
129
            // Note: internal return
130
            return $user->hasPermissionTo($permission);
131
        }, $permissions);
132
133
        return $hasAccess;
134
    }
135
136
    /**
137
     * @param $user
138
     *
139
     * @return  array
140
     */
141 View Code Duplication
    private function hasAnyRoleAccess($user)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
142
    {
143
        if (!array_key_exists('roles', $this->access) || !$this->access['roles']) {
144
            return [];
145
        }
146
147
        $roles = explode('|', $this->access['roles']);
148
149
        $hasAccess = array_map(function ($role) use ($user) {
150
            // Note: internal return
151
            return $user->hasRole($role);
152
        }, $roles);
153
154
        return $hasAccess;
155
    }
156
}
157