Completed
Push — master ( 1e60c5...8c1e01 )
by Valentin
18s queued 16s
created

PostgresQueryWriter::fetchValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Spiral Framework. Data Grid Bridge.
5
 *
6
 * @license MIT
7
 * @author  Anton Tsitou (Wolfy-J)
8
 * @author  Valentin Vintsukevich (vvval)
9
 */
10
11
declare(strict_types=1);
12
13
namespace Spiral\DataGrid\Writer;
14
15
use Cycle\ORM\Select;
16
use Spiral\Database\Driver\Postgres\PostgresDriver;
17
use Spiral\Database\Query\SelectQuery;
18
use Spiral\DataGrid\Compiler;
19
use Spiral\DataGrid\Exception\CompilerException;
20
use Spiral\DataGrid\Specification;
21
use Spiral\DataGrid\SpecificationInterface;
22
use Spiral\DataGrid\WriterInterface;
23
24
/**
25
 * Provides the ability to write into spiral/database SelectQuery and cycle/orm Select.
26
 */
27
class PostgresQueryWriter implements WriterInterface
28
{
29
    /**
30
     * @inheritDoc
31
     */
32
    public function write($source, SpecificationInterface $specification, Compiler $compiler)
33
    {
34
        if (!$this->targetAcceptable($source)) {
35
            return null;
36
        }
37
38
        if ($specification instanceof Specification\Filter\Postgres\ILike) {
39
            return $source->where(
40
                $specification->getExpression(),
41
                'ILIKE',
42
                sprintf($specification->getPattern(), $this->fetchValue($specification->getValue()))
43
            );
44
        }
45
46
        return null;
47
    }
48
49
    /**
50
     * @param mixed $target
51
     * @return bool
52
     */
53
    protected function targetAcceptable($target): bool
54
    {
55
        if (
56
            class_exists(SelectQuery::class)
57
            && $target instanceof SelectQuery
58
            && $target->getDriver() instanceof PostgresDriver
59
        ) {
60
            return true;
61
        }
62
63
        if (
64
            class_exists(Select::class)
65
            && $target instanceof Select
66
            && $target->buildQuery()->getDriver() instanceof PostgresDriver
67
        ) {
68
            return true;
69
        }
70
71
        return false;
72
    }
73
74
    /**
75
     * Fetch and assert that filter value is not expecting any user input.
76
     *
77
     * @param Specification\ValueInterface|mixed $value
78
     * @return mixed
79
     */
80
    protected function fetchValue($value)
81
    {
82
        if ($value instanceof Specification\ValueInterface) {
83
            throw new CompilerException('Value expects user input, none given');
84
        }
85
86
        return $value;
87
    }
88
}
89