AbstractFilterableRepository::resetFilters()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DevMakerLab\LaravelFilters;
6
7
use Illuminate\Database\Query\Builder;
8
9
abstract class AbstractFilterableRepository
10
{
11
    protected array $filters = [];
12
13
    protected ?int $limit = null;
14
15
    /**
16
     * @throws FilterClassNotFound
17
     * @throws IncorrectFilterException
18
     */
19 5
    public function addFilter(string $filter): self
20
    {
21 5
        if (! class_exists($filter)) {
22 1
            throw new FilterClassNotFound();
23
        }
24
25 4
        if (! is_subclass_of($filter, AbstractFilter::class)) {
26 1
            throw new IncorrectFilterException($filter);
27
        }
28
29 3
        $this->filters[] = $filter;
30
31 3
        return $this;
32
    }
33
34 2
    public function resetFilters(): self
35
    {
36 2
        $this->filters = [];
37
38 2
        return $this;
39
    }
40
41 3
    public function limit(int $limit): self
42
    {
43 3
        $this->limit = $limit;
44
45 3
        return $this;
46
    }
47
48 2
    public function resetLimit(): self
49
    {
50 2
        $this->limit = null;
51
52 2
        return $this;
53
    }
54
55 1
    public function applyFilters(Builder &$builder, array $args): self
56
    {
57 1
        foreach ($this->filters as $filter) {
58 1
            $neededArgs = $this->extractNeededArgs($filter, $args);
59
60 1
            if ($filter::isApplicable($neededArgs)) {
61 1
                $filterInstance = new $filter($neededArgs);
62 1
                $filterInstance->apply($builder);
63
            }
64
        }
65
66 1
        if ($this->limit) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->limit of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
67 1
            $builder->limit($this->limit);
68
        }
69
70 1
        $this->resetFilters();
71 1
        $this->resetLimit();
72
73 1
        return $this;
74
    }
75
76 1
    private function extractNeededArgs(string $class, array $args): array
77
    {
78 1
        return array_intersect_key($args, array_flip(array_keys(get_class_vars($class))));
79
    }
80
}
81