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

HashIdTrait::decodeHashedIdsBeforeValidation()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace App\Ship\Engine\Traits;
4
5
use App\Ship\Features\Exceptions\IncorrectIdException;
6
use Illuminate\Support\Facades\Config;
7
use Route;
8
use Vinkla\Hashids\Facades\Hashids;
9
10
/**
11
 * Class HashIdTrait.
12
 *
13
 * @author  Mahmoud Zalt <[email protected]>
14
 */
15
trait HashIdTrait
16
{
17
18
    /**
19
     * endpoint to be skipped from decoding their ID's (example for external ID's)
20
     * @var  array
21
     */
22
    private $skippedEndpoints = [
23
//        'orders/{id}/external',
24
    ];
25
26
    /**
27
     * All ID's passed with all endpoints will be decoded before entering the Application
28
     */
29
    public function runHashedIdsDecoder()
30
    {
31
        if (Config::get('hello.hash-id')) {
32
            Route::bind('id', function ($id, $route) {
33
                // skip decoding some endpoints
34
                if (!in_array($route->uri(), $this->skippedEndpoints)) {
35
36
                    // decode the ID in the URL
37
                    $decoded = $this->decoder($id);
38
39
                    if (empty($decoded)) {
40
                        throw new IncorrectIdException('ID (' . $id . ') is incorrect, consider using the hashed ID 
41
                        instead of the numeric ID.');
42
                    }
43
44
                    return $decoded[0];
45
                }
46
            });
47
        }
48
    }
49
50
    /**
51
     * Will be used by the Eloquent Models (since it's used as trait there).
52
     *
53
     * @param null $key
54
     *
55
     * @return  mixed
56
     */
57
    public function getHashedKey($key = null)
58
    {
59
        // hash the ID only if hash-id enabled in the config
60
        if (Config::get('hello.hash-id')) {
61
            return $this->encoder(($key) ? : $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...
62
        }
63
64
        return $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...
65
    }
66
67
    /**
68
     * without decoding the encoded ID's you won't be able to use
69
     * validation features like `exists:table,id`
70
     *
71
     * @param array $requestData
72
     *
73
     * @return  array
74
     */
75
    protected function decodeHashedIdsBeforeValidation(Array $requestData)
76
    {
77
        // the hash ID feature must be enabled to use this decoder feature.
78
        if (Config::get('hello.hash-id') && isset($this->decode) && !empty($this->decode)) {
79
            // iterate over each key (ID that needs to be decoded) and call keys locator to decode them
80
            foreach ($this->decode as $key) {
0 ignored issues
show
Bug introduced by
The property decode 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...
81
                $requestData = $this->locateAndDecodeIds($requestData, $key);
82
            }
83
        }
84
85
        return $requestData;
86
    }
87
88
    /**
89
     * Expected Keys formats:
90
     *
91
     * Type 1:
92
     *   A
93
     * Type 2:
94
     *   A.*.B
95
     *   A.*.B.*.C
96
     * Type 3:
97
     *   A.*
98
     *   A.*.B.*
99
     *
100
     * @param $requestData
101
     * @param $key
102
     *
103
     * @return  mixed
104
     */
105
    private function locateAndDecodeIds($requestData, $key)
106
    {
107
        if ($this->stringEndsWithChars('.*', $key)) {
108
            // if the key of Type 3:
109
            $this->decodeType3Key($requestData, $key);
110
        } elseif (str_contains($key, '.*.')) {
111
            // if the key of Type 2:
112
            $this->decodeType2Key($requestData, $key);
113
        } else {
114
            // if the key of Type 1:
115
            $this->decodeType1Key($requestData, $key);
116
        }
117
118
        return $requestData;
119
    }
120
121
    /**
122
     * @param $requestData
123
     * @param $key
124
     */
125
    private function decodeType1Key(&$requestData, $key)
126
    {
127
        // decode single key
128
        if (isset($requestData[$key])) {
129
            $requestData[$key] = $this->decode($requestData[$key]);
130
        }
131
    }
132
133
    /**
134
     * @param $requestData
135
     * @param $key
136
     */
137
    private function decodeType2Key(&$requestData, $key)
138
    {
139
        // get the last part of the key, which should be the ID that needs decoding
140
        $idToDecode = substr($key, strrpos($key, '.*.') + 3);
141
142
        array_walk_recursive($requestData, function (&$value, $key) use ($idToDecode) {
143
144
            if ($key == $idToDecode) {
145
146
                $value = $this->decode($value);
147
            }
148
149
        });
150
    }
151
152
    /**
153
     * @param $requestData
154
     * @param $key
155
     */
156
    private function decodeType3Key(&$requestData, $key)
157
    {
158
        $idToDecode = $this->removeLastOccurrenceFromString($key, '.*');
159
160
        $this->findKeyAndReturnValue($requestData, $idToDecode, function ($ids) {
161
162
            if (!is_array($ids)) {
163
                throw new IncorrectIdException('Expected ID\'s to be in array. Please wrap your ID\'s in an Array and send them back.');
164
            }
165
166
            $decodedIds = [];
167
168
            foreach ($ids as $id) {
169
                $decodedIds[] = $this->decode($id);
170
            }
171
172
            // callback return
173
            return $decodedIds;
174
        });
175
    }
176
177
    /**
178
     * @param $subject
179
     * @param $findKey
180
     * @param $callback
181
     *
182
     * @return  array
183
     */
184
    public function findKeyAndReturnValue(&$subject, $findKey, $callback)
185
    {
186
        // if the value is not an array, then you have reached the deepest point of the branch, so return the value.
187
        if (!is_array($subject)) {
188
            return $subject;
189
        }
190
191
        foreach ($subject as $key => $value) {
192
193
            if ($key == $findKey && isset($subject[$findKey])) {
194
                $subject[$key] = $callback($subject[$findKey]);
195
                break;
196
            }
197
198
            // add the value with the recursive call
199
            $this->findKeyAndReturnValue($value, $findKey, $callback);
200
        }
201
    }
202
203
    /**
204
     * @param $search
205
     * @param $subject
206
     *
207
     * @return  mixed
208
     */
209
    private function removeLastOccurrenceFromString($subject, $search)
210
    {
211
        $replace = '';
212
213
        $pos = strrpos($subject, $search);
214
215
        if ($pos !== false) {
216
            $subject = substr_replace($subject, $replace, $pos, strlen($search));
217
        }
218
219
        return $subject;
220
    }
221
222
    /**
223
     * @param $needle
224
     * @param $haystack
225
     *
226
     * @return  int
227
     */
228
    private function stringEndsWithChars($needle, $haystack)
229
    {
230
        return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack);
231
    }
232
233
    /**
234
     * @param array $ids
235
     *
236
     * @return  array
237
     */
238
    public function decodeArray(array $ids)
239
    {
240
        $result = [];
241
        foreach ($ids as $id) {
242
            $result[] = $this->decode($id);
243
        }
244
245
        return $result;
246
    }
247
248
    /**
249
     * @param $id
250
     *
251
     * @return  mixed
252
     */
253
    public function decode($id)
254
    {
255
        if (is_int($id)) {
256
            throw new IncorrectIdException('Only Hashed ID\'s allowed.');
257
        }
258
259
        return empty($this->decoder($id)) ? [] : $this->decoder($id)[0];
260
    }
261
262
    /**
263
     * @param $id
264
     *
265
     * @return  mixed
266
     */
267
    public function encode($id)
268
    {
269
        return $this->encoder($id);
270
    }
271
272
    /**
273
     * @param $id
274
     *
275
     * @return  mixed
276
     */
277
    private function decoder($id)
278
    {
279
        return Hashids::decode($id);
280
    }
281
282
    /**
283
     * @param $id
284
     *
285
     * @return  mixed
286
     */
287
    public function encoder($id)
288
    {
289
        return Hashids::encode($id);
290
    }
291
292
}
293