Completed
Pull Request — master (#68)
by Daniel
02:22
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\Grid\FilterInterface;
9
use Psi\Component\ObjectAgent\Capabilities;
10
use Psi\Component\ObjectAgent\Query\Comparison;
11
use Psi\Component\ObjectAgent\Query\Expression;
12
use Psi\Component\ObjectAgent\Query\Query;
13
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
14
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
15
use Symfony\Component\Form\Extension\Core\Type\TextType;
16
use Symfony\Component\Form\FormBuilderInterface;
17
use Symfony\Component\Form\FormInterface;
18
use Symfony\Component\OptionsResolver\OptionsResolver;
19
20
class StringFilter extends AbstractComparatorFilter
21
{
22
    const TYPE_EQUAL = 'equal';
23
    const TYPE_EMPTY = 'empty';
24
    const TYPE_NOT_EMPTY = 'not_empty';
25
    const TYPE_CONTAINS = 'contains';
26
    const TYPE_NOT_CONTAINS = 'not_contains';
27
    const TYPE_STARTS_WITH = 'starts_with';
28
    const TYPE_ENDS_WITH = 'ends_with';
29
    const TYPE_IN = 'in';
30
    const TYPE_NOT_IN = 'not_in';
31
32
    private static $comparatorMap = [
33
        self::TYPE_EQUAL => Comparison::EQUALS,
34
        self::TYPE_EMPTY => Comparison::NULL,
35
        self::TYPE_NOT_EMPTY => Comparison::NOT_NULL,
36
        self::TYPE_CONTAINS => Comparison::CONTAINS,
37
        self::TYPE_NOT_CONTAINS => Comparison::NOT_CONTAINS,
38
        self::TYPE_STARTS_WITH => Comparison::CONTAINS,
39
        self::TYPE_ENDS_WITH => Comparison::CONTAINS,
40
        self::TYPE_IN => Comparison::IN,
41
        self::TYPE_NOT_IN => Comparison::NOT_IN,
42
    ];
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function buildForm(FormBuilderInterface $builder, array $options)
48
    {
49
        $this->addComparatorChoice($builder, $options);
50
51
        $builder->add('value', TextType::class, [
52
            'required' => false,
53
        ]);
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 View Code Duplication
    public function getExpression(string $fieldName, FilterDataInterface $data): Expression
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
60
    {
61
        $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...
62
63
        return Query::comparison(
64
            self::$comparatorMap[$comparator],
65
            $fieldName,
66
            $this->getValue($comparator, $data->getValue())
67
        );
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73 View Code Duplication
    public function configureOptions(OptionsResolver $options)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
74
    {
75
        $options->setDefault('comparators', array_keys(self::$comparatorMap));
76
        $options->setDefault('data_class', StringFilterData::class);
77
        $options->setDefault('empty_data', function (FormInterface $form) {
78
            return new StringFilterData(
79
                $form->get('comparator')->getData(),
80
                $form->get('value')->getData()
81
            );
82
        });
83
    }
84
85
    protected function getComparatorMap(): array
86
    {
87
        return self::$comparatorMap;
88
    }
89
90
    private function getValue($comparator, $value)
91
    {
92
        switch ($comparator) {
93
            case self::TYPE_EQUAL:
94
                return $value;
95
            case self::TYPE_EMPTY:
96
                return;
97
            case self::TYPE_NOT_EMPTY:
98
                return;
99
            case self::TYPE_CONTAINS:
100
                return '%' . $value . '%';
101
            case self::TYPE_NOT_CONTAINS:
102
                return '%' . $value . '%';
103
            case self::TYPE_STARTS_WITH:
104
                return $value . '%';
105
            case self::TYPE_ENDS_WITH:
106
                return '%' . $value;
107
            case self::TYPE_IN:
108
                return array_map('trim', explode(',', $value));
109
            case self::TYPE_NOT_IN:
110
                return array_map('trim', explode(',', $value));
111
        }
112
113
        throw new \InvalidArgumentException(sprintf('Could not determine value for comparator "%s"', $comparator));
114
    }
115
}
116