Completed
Push — master ( 2975e7...46c3ee )
by Rafael
07:49
created

StringFilter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
dl 0
loc 30
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B __invoke() 0 25 8
1
<?php
2
/*******************************************************************************
3
 *  This file is part of the GraphQL Bundle package.
4
 *
5
 *  (c) YnloUltratech <[email protected]>
6
 *
7
 *  For the full copyright and license information, please view the LICENSE
8
 *  file that was distributed with this source code.
9
 ******************************************************************************/
10
11
namespace Ynlo\GraphQLBundle\Filter\Common;
12
13
use Doctrine\ORM\QueryBuilder;
14
use Ynlo\GraphQLBundle\Filter\FilterContext;
15
use Ynlo\GraphQLBundle\Filter\FilterInterface;
16
use Ynlo\GraphQLBundle\Model\Filter\StringComparisonExpression;
17
use Ynlo\GraphQLBundle\Type\StringComparisonOperatorType;
18
19
/**
20
 * string filter to compare strings and filter by them
21
 */
22
class StringFilter implements FilterInterface
23
{
24
    /**
25
     * @inheritDoc
26
     */
27 7
    public function __invoke(FilterContext $context, QueryBuilder $qb, $condition)
28
    {
29 7
        if (!$condition instanceof StringComparisonExpression) {
30 1
            throw new \RuntimeException('Invalid filter condition');
31
        }
32
33 6
        if (!$context->getField() || !$context->getField()->getName()) {
34 1
            throw new \RuntimeException('There are not valid field related to this filter.');
35
        }
36
37 5
        $alias = $qb->getRootAliases()[0];
38 5
        $column = $context->getField()->getOriginName();
39 5
        switch ($condition->getOp()) {
40 5
            case StringComparisonOperatorType::EQUAL:
41 2
                $qb->andWhere("{$alias}.{$column} = '{$condition->getValue()}'");
42 2
                break;
43 3
            case StringComparisonOperatorType::CONTAINS:
44 1
                $qb->andWhere("{$alias}.{$column} LIKE '%{$condition->getValue()}%'");
45 1
                break;
46 2
            case StringComparisonOperatorType::STARTS_WITH:
47 1
                $qb->andWhere("{$alias}.{$column} LIKE '{$condition->getValue()}%'");
48 1
                break;
49 1
            case StringComparisonOperatorType::ENDS_WITH:
50 1
                $qb->andWhere("{$alias}.{$column} LIKE '%{$condition->getValue()}'");
51 1
                break;
52
        }
53 5
    }
54
}
55