Completed
Push — master ( 6a0d35...e50528 )
by Mahmoud
14:11
created

HashIdTrait   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 142
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 22
c 0
b 0
f 0
lcom 1
cbo 2
dl 0
loc 142
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A runEndpointsHashedIdsDecoder() 0 20 4
A getHashedKey() 0 9 3
C decodeHashedIdsBeforeApplyingValidationRules() 0 22 8
A decodeArray() 0 9 2
A decode() 0 6 2
A encode() 0 4 1
A decoder() 0 4 1
A encoder() 0 4 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 runEndpointsHashedIdsDecoder()
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
    /**
69
     * without decoding the encoded ID's you won't be able to use
70
     * validation features like `exists:table,id`
71
     *
72
     * @param array $requestData
73
     *
74
     * @return  array
75
     */
76
    protected function decodeHashedIdsBeforeApplyingValidationRules(Array $requestData)
77
    {
78
        // the hash ID feature must be enabled to use this decoder feature.
79
        if (Config::get('hello.hash-id') && isset($this->decode) && !empty($this->decode)) {
80
81
            foreach ($this->decode as $id) {
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...
82
83
                if (isset($requestData[$id])) {
84
                    // validate the user is not trying to pass real ID
85
                    if (is_numeric($requestData[$id])) {
86
                        throw new IncorrectIdException('Only Hashed ID\'s allowed to be passed.');
87
                    }
88
89
                    $requestData[$id] = is_array($requestData[$id]) ?
90
                        $this->decodeArray($requestData[$id]) : $this->decode($requestData[$id]);
91
92
                } // do nothing if the input is incorrect, because what if it's not required!
93
            }
94
        }
95
96
        return $requestData;
97
    }
98
99
    /**
100
     * @param array $ids
101
     *
102
     * @return  array
103
     */
104
    public function decodeArray(array $ids)
105
    {
106
        $result = [];
107
        foreach ($ids as $id) {
108
            $result[] = $this->decode($id);
109
        }
110
111
        return $result;
112
    }
113
114
    /**
115
     * @param $id
116
     *
117
     * @return  mixed
118
     */
119
    public function decode($id)
120
    {
121
        $decoded = $this->decoder($id);
122
123
        return is_array($decoded) ? $decoded[0] : $decoded;
124
    }
125
126
    /**
127
     * @param $id
128
     *
129
     * @return  mixed
130
     */
131
    public function encode($id)
132
    {
133
        return $this->encoder($id);
134
    }
135
136
    /**
137
     * @param $id
138
     *
139
     * @return  mixed
140
     */
141
    private function decoder($id)
142
    {
143
        return Hashids::decode($id);
144
    }
145
146
    /**
147
     * @param $id
148
     *
149
     * @return  mixed
150
     */
151
    public function encoder($id)
152
    {
153
        return Hashids::encode($id);
154
    }
155
156
}
157