Issues (20)

src/Active.php (3 issues)

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
     */
46
    protected $activeValue;
47
48
    /**
49
     * Whether $activeValue should be reset after a check or not
50
     * @var bool
51
     */
52
    protected $activeValuePersistent = false;
53
54
    /**
55
     * Value returned when state is "inactive"
56
     * @var string
57
     */
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
66
    /**
67
     * The Request instance
68
     * @var \Illuminate\Http\Request
69
     */
70
    protected $request;
71
72
    /**
73
     * Obviously: the constructor
74
     * @method __construct
75
     * @param  \Illuminate\Http\Request  $request The HTTP Request handled by Laravel
76
     */
77 140
    public function __construct(HttpRequest $request)
78
    {
79 140
        $this->request = $request;
80 140
    }
81
82
    /**
83
     * Check whether the path of the url matches the given patterns
84
     * @param  string[] $patterns Patterns to match
85
     * @return bool
86
     */
87 24
    public function checkPathIs(...$patterns): bool
88
    {
89 24
        return $this->request->is(...$patterns);
90
    }
91
92
    /**
93
     * Check whether the path of the url contains given strings
94
     * @param  string[]  $patterns
95
     * @return bool
96
     */
97 36
    public function checkPathHas(...$patterns): bool
98
    {
99 36
        return $this->request->is(array_map(
100
            function ($item) {
101 36
                return "*{$item}*";
102 36
            },
103
            $patterns
104
        ));
105
    }
106
107
    /**
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 32
    public function checkRouteIs($route, array $routeParameters = []): bool
114
    {
115 32
        if (!is_array($route)) {
116 16
            $route = [$route => $routeParameters];
117
        }
118 32
        foreach ($route as $r => $parameters) {
119
            try {
120 32
                $routeUri = route($r, $parameters, true);
121 24
                if ($this->request->fullUrlIs($routeUri)) {
122 24
                    return true;
123
                }
124 16
            } catch (\Exception $e) {
125
                // Just ignore the exception: route does not exist
126
            }
127
        }
128 12
        return false;
129
    }
130
131
    /**
132
     * Check whether the current route is one of the given routes
133
     * @param  string[]  $routes
134
     * @return bool
135
     */
136 16
    public function checkRouteIn(...$routes): bool
137
    {
138 16
        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
     * @return bool
146
     */
147 40
    public function checkQueryIs(array ...$parameters): bool
148
    {
149 40
        foreach ($parameters as $params) {
150 40
            if ($this->request->query->all() == $params) {
151 24
                return true;
152
            }
153
        }
154 16
        return false;
155
    }
156
157
    /**
158
     * Check if query has all of the given parameters, not taking their values into account
159
     * @param  array  $parameters
160
     * @return bool
161
     */
162 36
    public function checkQueryHas(...$parameters): bool
163
    {
164 36
        $queryKeys = array_keys($this->request->query->all());
165
        return empty(
166 36
            array_diff($parameters, $queryKeys)
167
        );
168
    }
169
170
    /**
171
     * Check if query parameters names are exactly the ones given in argument
172
     * The order of the parameters does not matter
173
     * @param  string[]  $parameters string
174
     * @return bool
175
     */
176 20
    public function checkQueryHasOnly(...$parameters): bool
177
    {
178 20
        $queryKeys = array_keys($this->request->query->all());
179 20
        sort($queryKeys);
180 20
        sort($parameters);
181
182 20
        return $parameters === $queryKeys;
183
    }
184
185
    /**
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 16
    public function checkQueryContains($parameters): bool
191
    {
192
        return empty(
193 16
            array_diff($parameters, $this->request->query->all())
194
        );
195
    }
196
197
    /**
198
     * Dynamically calls :
199
     *   - `if*` tests
200
     *   - `checkNot*` tests
201
     */
202 66
    public function __call($calledMethod, array $arguments)
203
    {
204 66
        if (0 === strpos($calledMethod, 'if')) {
205 16
            $check = 'check' . substr($calledMethod, 2);
206 16
            return $this->getState($this->$check(...$arguments));
207
        }
208
209 50
        if (0 === strpos($calledMethod, 'checkNot')) {
210 50
            $method = 'check' . substr($calledMethod, 8);
211 50
            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
    }
218
219
    /**
220
     * Returns the active state string depending on the actual state
221
     * @param  bool  $active
222
     * @return string
223
     */
224 1
    public function getState(bool $active): string
225
    {
226 1
        return $active ? $this->getActiveValue() : $this->getInactiveValue();
227
    }
228
229
    /**
230
     * Returns the active state string
231
     * @return string
232
     */
233 3
    public function getActiveValue(): string
234
    {
235 3
        $return = $this->activeValue ?? config('active.active_state', 'active');
236 3
        if (! $this->activeValuePersistent) {
237 3
            $this->setActiveValue();
238
        }
239 3
        return $return;
240
    }
241
242
    /**
243
     * Return the inactive state string
244
     * @return string
245
     */
246 3
    public function getInactiveValue(): string
247
    {
248 3
        $return = $this->inactiveValue ?? config('active.inactive_state', '');
249 3
        if (! $this->inactiveValuePersistent) {
250 3
            $this->setInactiveValue();
251
        }
252 3
        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 3
    public function setActiveValue(string $value = null, bool $persistent = null): Active
261
    {
262 3
        $this->activeValue = $value;
263 3
        if (null !== $persistent) {
264 1
            $this->activeValuePersistent = (bool) $persistent;
265
        }
266
267 3
        return $this;
268
    }
269
270
    /**
271
     * Set the inactive state string
272
     * @param  string  $value      The string value
273
     * @param  bool|null  $persistent Whether to reset the value after the next check
274
     */
275 3
    public function setInactiveValue(string $value = null, bool $persistent = null): Active
276
    {
277 3
        $this->inactiveValue = $value;
278 3
        if (null !== $persistent) {
279 1
            $this->inactiveValuePersistent = (bool) $persistent;
280
        }
281
282 3
        return $this;
283
    }
284
285
    /**
286
     * Change active and inactive values at runtime and allow method chaining
287
     * @param  string $activeValue
288
     * @param  string $inactiveValue
289
     * @return Active
290
     */
291 2
    public function setValues(string $activeValue = null, string $inactiveValue = null): Active
292
    {
293 2
        $activeValue and $this->setActiveValue($activeValue);
294 2
        $inactiveValue and $this->setInactiveValue($inactiveValue);
295
296 2
        return $this;
297
    }
298
299
    /**
300
     * Reset both active and inactive state strings
301
     */
302 1
    public function resetValues(): Active
303
    {
304 1
        $this->activeValue = null;
305 1
        $this->inactiveValue = null;
306
307 1
        return $this;
308
    }
309
310
    //--------------------
311
    // Deprecated methods
312
    //--------------------
313
314
    /**
315
    * @deprecated v4.0
316
    * @see self::ifPathIs()
317
    *
318
    * {@inheritdoc}
319
    */
320 1
    public function ifUrlIs(...$patterns): string
321
    {
322 1
        return $this->ifPathIs(...$patterns);
0 ignored issues
show
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
    }
324
325
    /**
326
    * @deprecated v4.0
327
    * @see self::ifPathHas()
328
    *
329
    * {@inheritdoc}
330
    */
331 1
    public function ifUrlHas(...$patterns): string
332
    {
333 1
        return $this->ifPathHas(...$patterns);
0 ignored issues
show
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
    }
335
336
    /**
337
    * @deprecated v4.0
338
    * @see self::checkPathIs()
339
    *
340
    * {@inheritdoc}
341
    */
342 9
    public function checkUrlIs(...$urls): bool
343
    {
344 9
        return $this->checkPathIs(...$urls);
345
    }
346
347
    /**
348
    * @deprecated v4.0
349
    * @see self::checkPathHas()
350
    *
351
    * {@inheritdoc}
352
    */
353 13
    public function checkUrlHas(...$urls): bool
354
    {
355 13
        return $this->checkPathHas(...$urls);
356
    }
357
358
    /**
359
     * @deprecated v4.0
360
     * @see self::setValues()
361
     *
362
     * {@inheritdoc}
363
     */
364 1
    public function state(string $active_state = null, string $inactive_state = null): Active
365
    {
366 1
        return $this->setValues($active_state, $inactive_state);
367
    }
368
}
369