Completed
Pull Request — master (#68)
by Daniel
03:34 queued 01:26
created

StringFilter::getChoices()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\Grid\Filter;
6
7
use Psi\Component\Grid\FilterDataInterface;
8
use Psi\Component\ObjectAgent\Query\Comparison;
9
use Psi\Component\ObjectAgent\Query\Expression;
10
use Psi\Component\ObjectAgent\Query\Query;
11
use Symfony\Component\Form\Extension\Core\Type\TextType;
12
use Symfony\Component\Form\FormBuilderInterface;
13
use Symfony\Component\Form\FormInterface;
14
use Symfony\Component\OptionsResolver\OptionsResolver;
15
16
class StringFilter extends AbstractComparatorFilter
17
{
18
    const TYPE_EQUAL = 'equal';
19
    const TYPE_EMPTY = 'empty';
20
    const TYPE_NOT_EMPTY = 'not_empty';
21
    const TYPE_CONTAINS = 'contains';
22
    const TYPE_NOT_CONTAINS = 'not_contains';
23
    const TYPE_STARTS_WITH = 'starts_with';
24
    const TYPE_ENDS_WITH = 'ends_with';
25
    const TYPE_IN = 'in';
26
    const TYPE_NOT_IN = 'not_in';
27
28
    private static $comparatorMap = [
29
        self::TYPE_EQUAL => Comparison::EQUALS,
30
        self::TYPE_EMPTY => Comparison::NULL,
31
        self::TYPE_NOT_EMPTY => Comparison::NOT_NULL,
32
        self::TYPE_CONTAINS => Comparison::CONTAINS,
33
        self::TYPE_NOT_CONTAINS => Comparison::NOT_CONTAINS,
34
        self::TYPE_STARTS_WITH => Comparison::CONTAINS,
35
        self::TYPE_ENDS_WITH => Comparison::CONTAINS,
36
        self::TYPE_IN => Comparison::IN,
37
        self::TYPE_NOT_IN => Comparison::NOT_IN,
38
    ];
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function buildForm(FormBuilderInterface $builder, array $options)
44
    {
45
        $this->addComparatorChoice($builder, $options);
46
47
        $builder->add('value', TextType::class, [
48
            'required' => false,
49
        ]);
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function getExpression(string $fieldName, FilterDataInterface $data): Expression
56
    {
57
        $comparator = $data->getComparator() ?: self::TYPE_EQUAL;
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psi\Component\Grid\FilterDataInterface as the method getComparator() does only exist in the following implementations of said interface: Psi\Component\Grid\Filter\DateFilterData, Psi\Component\Grid\Filter\NumberFilterData, Psi\Component\Grid\Filter\StringFilterData.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
58
59
        return Query::comparison(
60
            self::$comparatorMap[$comparator],
61
            $fieldName,
62
            $this->getValue($comparator, $data->getValue())
63
        );
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function configureOptions(OptionsResolver $options)
70
    {
71
        $options->setDefault('comparators', array_keys(self::$comparatorMap));
72
        $options->setDefault('data_class', StringFilterData::class);
73
        $options->setDefault('empty_data', function (FormInterface $form) {
74
            return new StringFilterData(
75
                $form->get('comparator')->getData(),
76
                $form->get('value')->getData()
77
            );
78
        });
79
    }
80
81
    protected function getComparatorMap(): array
82
    {
83
        return self::$comparatorMap;
84
    }
85
86
    private function getValue($comparator, $value)
87
    {
88
        switch ($comparator) {
89
            case self::TYPE_EQUAL:
90
                return $value;
91
            case self::TYPE_EMPTY:
92
                return;
93
            case self::TYPE_NOT_EMPTY:
94
                return;
95
            case self::TYPE_CONTAINS:
96
                return '%' . $value . '%';
97
            case self::TYPE_NOT_CONTAINS:
98
                return '%' . $value . '%';
99
            case self::TYPE_STARTS_WITH:
100
                return $value . '%';
101
            case self::TYPE_ENDS_WITH:
102
                return '%' . $value;
103
            case self::TYPE_IN:
104
                return array_map('trim', explode(',', $value));
105
            case self::TYPE_NOT_IN:
106
                return array_map('trim', explode(',', $value));
107
        }
108
109
        throw new \InvalidArgumentException(sprintf('Could not determine value for comparator "%s"', $comparator));
110
    }
111
}
112