Completed
Push — master ( f7b0df...8b6295 )
by Mahmoud
03:35
created

RequestTrait::applyValidationRulesToUrlParams()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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