Test Failed
Pull Request — develop (#13)
by Olivier
03:09
created

Active::checkPathHas()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 7
ccs 0
cts 0
cp 0
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Arcesilas\ActiveState;
4
5
use Request;
6
use Illuminate\Http\Request as HttpRequest;
7
use BadMethodCallException;
8
9
/**
10
 * @method checkNotPathIs(...$patterns) Check whether the path of the url does not match the given patterns
11
 * @method checkNotPathHas(...$patterns) Check whether the path of the url does not contain given strings
12
 * @method checkNotQueryContains($parameters) Check if query does not have the given parameters,
13
 *         with their given values
14
 * @method checkNotQueryHas(...$parameters) Check if query has none of the given parameters,
15
 *         not taking their values into account
16
 * @method checkNotQueryHasOnly(... $parameters) Check if query parameters names are exactly not the ones
17
 *         given in argument
18
 * @method checkNotQueryIs(array ...$parameters) Check that the parameters of the query string are exactly
19
 *         not the ones given in argument
20
 * @method checkNotRouteIn(...$routes) Check whether the current route is none of the given routes
21
 * @method checkNotRouteIs($route, array $routeParameters) Check if the current route name is not the one given
22
 *         and the parameters match the current url
23
 * @method ifPathIs(...$patterns) Returns activeValue or inactiveValue for checkPathIs test
24
 * @method ifPathHas(...$patterns) Returns activeValue or inactiveValue for checkPathHas test
25
 * @method ifQueryContains($parameters) Returns activeValue or inactiveValue for checkQueryContains test
26
 * @method ifQueryHas(...$parameters) Returns activeValue or inactiveValue for checkQueryHas test
27
 * @method ifQueryHasOnly(...$parameters) Returns activeValue or inactiveValue for checkQueryHasOnly test
28
 * @method ifQueryIs(array ...$parameters) Returns activeValue or inactiveValue for checkQuery test
29
 * @method ifRouteIn(...$routes) Returns activeValue or inactiveValue for checkRouteIn test
30
 * @method ifRouteIs($route, array $parameters = []) Returns activeValue or inactiveValue for checkRouteIs test
31
 * @method ifNotPathIs(...$patterns) Returns activeValue or inactiveValue for checkNotPathIs test
32
 * @method ifNotPathHas(...$patterns) Returns activeValue or inactiveValue for checkNotPathHas test
33
 * @method ifNotQueryContains($parameters) Returns activeValue or inactiveValue for checkNotQueryContains test
34
 * @method ifNotQueryHas(...$parameters) Returns activeValue or inactiveValue for checkNotQueryHas test
35
 * @method ifNotQueryHasOnly(...$parameters) Returns activeValue or inactiveValue for checkNotQueryHasOnly test
36
 * @method ifNotQueryIs(array ...$parameters) Returns activeValue or inactiveValue for checkNotQueryIs test
37
 * @method ifNotRouteIn(...$routes) Returns activeValue or inactiveValue for checkNotRouteIn test
38
 * @method ifNotRouteIs($route, array $parameters = []) Returns activeValue or inactiveValue for checkNotRouteIs test
39
 */
0 ignored issues
show
Documentation Bug introduced by
The doc comment ... at position 0 could not be parsed: Unknown type name '...' at position 0 in ....
Loading history...
40
class Active
41
{
42
    /**
43
     * Value returned when state is "active"
44
     * @var string
45 173
     */
46
    protected $activeValue;
47 173
48 173
    /**
49
     * Whether $activeValue should be reset after a check or not
50
     * @var bool
51
     */
52
    protected $activeValuePersistent = false;
53
54
    /**
55 12
     * Value returned when state is "inactive"
56
     * @var string
57 12
     */
58
    protected $inactiveValue;
59
60
    /**
61
     * Whether $inactiveValue should be reset after a check or not
62
     * @var bool
63
     */
64
    protected $inactiveValuePersistent = false;
65 18
66
    /**
67 18
     * The Request instance
68 18
     * @var \Illuminate\Http\Request
69 18
     */
70 18
    protected $request;
71 18
72
    /**
73
     * Obviously: the constructor
74
     * @method __construct
75
     * @param  \Illuminate\Http\Request  $request The HTTP Request handled by Laravel
76
     */
77
    public function __construct(HttpRequest $request)
78
    {
79
        $this->request = $request;
80
    }
81 24
82
    /**
83 24
     * Check whether the path of the url matches the given patterns
84 12
     * @param  string[] $patterns Patterns to match
85
     * @return bool
86 24
     */
87
    public function checkPathIs(...$patterns): bool
88 24
    {
89 18
        return $this->request->is(...$patterns);
90 15
    }
91
92 12
    /**
93
     * Check whether the path of the url contains given strings
94
     * @param  string[]  $patterns
95
     * @return bool
96 9
     */
97
    public function checkPathHas(...$patterns): bool
98
    {
99
        return $this->request->is(array_map(
100
            function ($item) {
101
                return "*{$item}*";
102
            },
103
            $patterns
104
        ));
105 12
    }
106
107 12
    /**
108
     * Check if the current route name is the one given and the parameters match the current url
109
     * @param  string|array  $route           The route name to check
110
     * @param  array         $routeParameters The route parameters, used to build the url
111
     * @return bool
112
     */
113
    public function checkRouteIs($route, array $routeParameters = []): bool
114
    {
115
        if (!is_array($route)) {
116 30
            $route = [$route => $routeParameters];
117
        }
118 30
        foreach ($route as $r => $parameters) {
119 30
            try {
120 18
                $routeUri = route($r, $parameters, true);
121
                if ($this->request->fullUrlIs($routeUri)) {
122
                    return true;
123 12
                }
124
            } catch (\Exception $e) {
125
                // Just ignore the exception: route does not exist
126
            }
127
        }
128
        return false;
129
    }
130
131 27
    /**
132
     * Check whether the current route is one of the given routes
133 27
     * @param  string[]  $routes
134
     * @return bool
135 27
     */
136
    public function checkRouteIn(...$routes): bool
137
    {
138
        return $this->request->routeIs(...$routes);
139
    }
140
141
    /**
142
     * Check that the parameters of the query string are exactly the ones given
143
     * The test returns true if at least one given array matches the query string parameters (keys and values)
144
     * @param  array  $parameters
145 15
     * @return bool
146
     */
147 15
    public function checkQueryIs(array ...$parameters): bool
148 15
    {
149 15
        foreach ($parameters as $params) {
150
            if ($this->request->query->all() == $params) {
151 15
                return true;
152
            }
153
        }
154
        return false;
155
    }
156
157
    /**
158
     * Check if query has all of the given parameters, not taking their values into account
159 12
     * @param  array  $parameters
160
     * @return bool
161
     */
162 12
    public function checkQueryHas(...$parameters): bool
163
    {
164
        $queryKeys = array_keys($this->request->query->all());
165
        return empty(
166
            array_diff($parameters, $queryKeys)
167
        );
168
    }
169
170
    /**
171
     * Check if query parameters names are exactly the ones given in argument
172 18
     * The order of the parameters does not matter
173
     * @param  string[]  $parameters string
174 18
     * @return bool
175
     */
176
    public function checkQueryHasOnly(...$parameters): bool
177
    {
178
        $queryKeys = array_keys($this->request->query->all());
179
        sort($queryKeys);
180
        sort($parameters);
181
182
        return $parameters === $queryKeys;
183 2
    }
184
185 2
    /**
186
     * Check if query has the given parameters, with their given values
187
     * @param  array  $parameters  The parameters to check for
188
     * @return bool
189
     */
190
    public function checkQueryContains($parameters): bool
191
    {
192
        return empty(
193
            array_diff($parameters, $this->request->query->all())
194 2
        );
195
    }
196 2
197
    /**
198
     * Dynamically calls :
199
     *   - `if*` tests
200
     *   - `checkNot*` tests
201
     */
202
    public function __call($calledMethod, array $arguments)
203
    {
204
        if (0 === strpos($calledMethod, 'if')) {
205
            $check = 'check' . substr($calledMethod, 2);
206 4
            return $this->getState($this->$check(...$arguments));
207
        }
208 4
209
        if (0 === strpos($calledMethod, 'checkNot')) {
210
            $method = 'check' . substr($calledMethod, 8);
211
            return ! call_user_func_array([$this, $method], $arguments);
212
        }
213
214
        // @codeCoverageIgnoreStart
215
        throw new BadMethodCallException(sprintf('Method %s::%s does not exist.', static::class, $calledMethod));
216
        // @codeCoverageIgnoreEnd
217 2
    }
218
219 2
    /**
220
     * Returns the active state string depending on the actual state
221
     * @param  bool  $active
222
     * @return string
223
     */
224
    public function getState(bool $active): string
225
    {
226
        return $active ? $this->getActiveValue() : $this->getInactiveValue();
227
    }
228 2
229
    /**
230 2
     * Returns the active state string
231
     * @return string
232
     */
233
    public function getActiveValue(): string
234
    {
235
        $return = $this->activeValue ?? config('active.active_state', 'active');
236
        if (! $this->activeValuePersistent) {
237
            $this->setActiveValue();
238
        }
239 2
        return $return;
240
    }
241 2
242
    /**
243
     * Return the inactive state string
244
     * @return string
245
     */
246
    public function getInactiveValue(): string
247
    {
248
        $return = $this->inactiveValue ?? config('active.inactive_state', '');
249
        if (! $this->inactiveValuePersistent) {
250 2
            $this->setInactiveValue();
251
        }
252 2
        return $return;
253
    }
254
255
    /**
256
     * Set the active state string
257
     * @param  string  $value  The string value
258
     * @param  bool|null  $persistent Whether to reset the value after the next check
259
     */
260
    public function setActiveValue(string $value = null, bool $persistent = null): Active
261 2
    {
262
        $this->activeValue = $value;
263 2
        if (null !== $persistent) {
264
            $this->activeValuePersistent = (bool) $persistent;
265
        }
266
267
        return $this;
268
    }
269
270
    /**
271 1
     * Set the inactive state string
272
     * @param  string  $value      The string value
273 1
     * @param  bool|null  $persistent Whether to reset the value after the next check
274
     */
275
    public function setInactiveValue(string $value = null, bool $persistent = null): Active
276
    {
277
        $this->inactiveValue = $value;
278
        if (null !== $persistent) {
279
            $this->inactiveValuePersistent = (bool) $persistent;
280 4
        }
281
282 4
        return $this;
283 4
    }
284 3
285
    /**
286 4
     * Change active and inactive values at runtime and allow method chaining
287
     * @param  string $activeValue
288
     * @param  string $inactiveValue
289
     * @return Active
290
     */
291
    public function setValues(string $activeValue = null, string $inactiveValue = null): Active
292
    {
293 4
        $activeValue and $this->setActiveValue($activeValue);
294
        $inactiveValue and $this->setInactiveValue($inactiveValue);
295 4
296 4
        return $this;
297 3
    }
298
299 4
    /**
300
     * Reset both active and inactive state strings
301
     */
302
    public function resetValues(): Active
303
    {
304
        $this->activeValue = null;
305
        $this->inactiveValue = null;
306
307 4
        return $this;
308
    }
309 4
310 4
    //--------------------
311 3
    // Deprecated methods
312
    //--------------------
313 4
314
    /**
315
    * @deprecated v4.0
316
    * @see self::ifPathIs()
317
    *
318
    * {@inheritdoc}
319
    */
320 4
    public function ifUrlIs(...$patterns): string
321
    {
322 4
        return $this->ifPathIs(...$patterns);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->ifPathIs($patterns) could return the type boolean which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
Bug introduced by
The method ifPathIs() does not exist on Arcesilas\ActiveState\Active. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

322
        return $this->/** @scrutinizer ignore-call */ ifPathIs(...$patterns);
Loading history...
323 4
    }
324 3
325
    /**
326 4
    * @deprecated v4.0
327
    * @see self::ifPathHas()
328
    *
329
    * {@inheritdoc}
330
    */
331
    public function ifUrlHas(...$patterns): string
332
    {
333
        return $this->ifPathHas(...$patterns);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->ifPathHas($patterns) could return the type boolean which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
Bug introduced by
The method ifPathHas() does not exist on Arcesilas\ActiveState\Active. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

333
        return $this->/** @scrutinizer ignore-call */ ifPathHas(...$patterns);
Loading history...
334 1
    }
335
336 1
    /**
337 1
    * @deprecated v4.0
338 1
    * @see self::checkPathIs()
339
    *
340 1
    * {@inheritdoc}
341
    */
342
    public function checkUrlIs(...$urls): bool
343
    {
344
        return $this->checkPathIs(...$urls);
345
    }
346 1
347
    /**
348 1
    * @deprecated v4.0
349 1
    * @see self::checkPathHas()
350 1
    *
351
    * {@inheritdoc}
352
    */
353
    public function checkUrlHas(...$urls): bool
354
    {
355
        return $this->checkPathHas(...$urls);
356
    }
357
358
    /**
359
     * @deprecated v4.0
360
     * @see self::setValues()
361
     *
362
     * {@inheritdoc}
363
     */
364
    public function state(string $active_state = null, string $inactive_state = null): Active
365
    {
366
        return $this->setValues($active_state, $inactive_state);
367
    }
368
}
369