Completed
Pull Request — master (#5)
by Daniel
08:08 queued 06:02
created

StringFilter::getExpression()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
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\TextType;
15
use Symfony\Component\Form\FormBuilderInterface;
16
use Symfony\Component\Form\FormInterface;
17
use Symfony\Component\OptionsResolver\OptionsResolver;
18
19
class StringFilter implements FilterInterface
20
{
21
    const TYPE_EQUAL = 'equal';
22
    const TYPE_EMPTY = 'empty';
23
    const TYPE_NOT_EMPTY = 'not_empty';
24
    const TYPE_CONTAINS = 'contains';
25
    const TYPE_NOT_CONTAINS = 'not_contains';
26
    const TYPE_STARTS_WITH = 'starts_with';
27
    const TYPE_ENDS_WITH = 'ends_with';
28
    const TYPE_IN = 'in';
29
    const TYPE_NOT_IN = 'not_in';
30
31
    private static $comparatorMap = [
32
        self::TYPE_EQUAL => Comparison::EQUALS,
33
        self::TYPE_EMPTY => Comparison::NULL,
34
        self::TYPE_NOT_EMPTY => Comparison::NOT_NULL,
35
        self::TYPE_CONTAINS => Comparison::CONTAINS,
36
        self::TYPE_NOT_CONTAINS => Comparison::NOT_CONTAINS,
37
        self::TYPE_STARTS_WITH => Comparison::CONTAINS,
38
        self::TYPE_ENDS_WITH => Comparison::CONTAINS,
39
        self::TYPE_IN => Comparison::IN,
40
        self::TYPE_NOT_IN => Comparison::NOT_IN,
41
    ];
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 View Code Duplication
    public function buildForm(FormBuilderInterface $builder, array $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...
47
    {
48
        $builder->add('comparator', ChoiceType::class, [
49
            'choices' => $this->getChoices(
50
                $options['capabilities']->getSupportedComparators(),
51
                $options['comparators']
52
            ),
53
        ]);
54
        $builder->add('value', TextType::class);
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function getExpression(string $fieldName, FilterDataInterface $data): Expression
61
    {
62
        return Query::comparison(
63
            self::$comparatorMap[$data->getComparator()],
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\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...
64
            $fieldName,
65
            $this->getValue($data->getComparator(), $data->getValue())
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\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...
66
        );
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 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...
73
    {
74
        $options->setDefault('comparators', array_keys(self::$comparatorMap));
75
        $options->setDefault('data_class', StringFilterData::class);
76
        $options->setDefault('empty_data', function (FormInterface $form) {
77
            return new StringFilterData(
78
                $form->get('comparator')->getData(),
79
                $form->get('value')->getData()
80
            );
81
        });
82
    }
83
84
    private function getChoices(array $supportedComparators, array $enabledComparators)
85
    {
86
        $supported = array_keys(array_filter(self::$comparatorMap, function ($comparator) use ($supportedComparators) {
87
            return in_array($comparator, $supportedComparators);
88
        }));
89
90
        $supported = array_filter($supported, function ($comparator) use ($enabledComparators) {
91
            return in_array($comparator, $enabledComparators);
92
        });
93
94
        return array_combine($supported, $supported);
95
    }
96
97
    private function getValue($comparator, $value)
98
    {
99
        switch ($comparator) {
100
            case self::TYPE_EQUAL:
101
                return $value;
102
            case self::TYPE_EMPTY:
103
                return;
104
            case self::TYPE_NOT_EMPTY:
105
                return;
106
            case self::TYPE_CONTAINS:
107
                return '%' . $value . '%';
108
            case self::TYPE_NOT_CONTAINS:
109
                return '%' . $value . '%';
110
            case self::TYPE_STARTS_WITH:
111
                return $value . '%';
112
            case self::TYPE_ENDS_WITH:
113
                return '%' . $value;
114
            case self::TYPE_IN:
115
                return array_map('trim', explode(',', $value));
116
            case self::TYPE_NOT_IN:
117
                return array_map('trim', explode(',', $value));
118
        }
119
120
        throw new \InvalidArgumentException(sprintf('Could not determine value for comparator', $comparator));
121
    }
122
}
123