QueryAdapter::formatValue()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php namespace Nord\Lumen\Search\Adapters;
2
3
use Doctrine\ORM\QueryBuilder;
4
use Nord\Lumen\Search\Formatter\Factory;
5
use Nord\Lumen\Search\Pagination;
6
use Nord\Lumen\Search\Result;
7
use Nord\Lumen\Search\Contracts\SearchAdapter as SearchAdapterContract;
8
use Pagerfanta\Adapter\DoctrineORMAdapter;
9
10
class QueryAdapter implements SearchAdapterContract
11
{
12
13
    /**
14
     * @var QueryBuilder
15
     */
16
    private $queryBuilder;
17
18
    /**
19
     * @var string
20
     */
21
    private $tableAlias;
22
23
24
    /**
25
     * QueryAdapter constructor.
26
     *
27
     * @param QueryBuilder $queryBuilder
28
     * @param string       $tableAlias
29
     * @param Factory      $formatter
30
     */
31
    public function __construct(QueryBuilder $queryBuilder, $tableAlias, Factory $formatter)
32
    {
33
        $this->queryBuilder = $queryBuilder;
34
        $this->tableAlias   = $tableAlias;
35
        $this->formatter    = $formatter;
0 ignored issues
show
Bug introduced by
The property formatter does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
36
    }
37
38
39
    /**
40
     * @param string $format
41
     * @param mixed  $value
42
     *
43
     * @return mixed
44
     */
45
    public function formatValue($format, $value)
46
    {
47
        return $this->formatter->create($format)->format($value);
48
    }
49
50
51
    /**
52
     * @param string $property
53
     * @param mixed  $from
54
     * @param mixed  $to
55
     */
56
    public function applyBetweenFilter($property, $from, $to)
57
    {
58
        $this->queryBuilder
59
            ->andWhere("$this->tableAlias.$property BETWEEN :{$property}_from AND :{$property}_to")
60
            ->setParameters(["{$property}_from" => $from, "{$property}_to" => $to]);
61
    }
62
63
64
    /**
65
     * @param string $property
66
     * @param mixed  $value
67
     */
68
    public function applyNotEqualsFilter($property, $value)
69
    {
70
        $this->queryBuilder
71
            ->andWhere("$this->tableAlias.$property != :$property")
72
            ->setParameter($property, "%$value%");
73
    }
74
75
76
    /**
77
     * @param string $property
78
     * @param mixed  $value
79
     */
80
    public function applyGreaterThanFilter($property, $value)
81
    {
82
        $this->queryBuilder
83
            ->andWhere("$this->tableAlias.$property > :$property")
84
            ->setParameter($property, $value);
85
    }
86
87
88
    /**
89
     * @param string $property
90
     * @param mixed  $value
91
     */
92
    public function applyLessThanFilter($property, $value)
93
    {
94
        $this->queryBuilder
95
            ->andWhere("$this->tableAlias.$property < :$property")
96
            ->setParameter($property, $value);
97
    }
98
99
100
    /**
101
     * @param string $property
102
     * @param mixed  $value
103
     */
104
    public function applyGreaterThanOrEqualsFilter($property, $value)
105
    {
106
        $this->queryBuilder
107
            ->andWhere("$this->tableAlias.$property >= :$property")
108
            ->setParameter($property, $value);
109
    }
110
111
112
    /**
113
     * @param string $property
114
     * @param mixed  $value
115
     */
116
    public function applyLessThanOrEqualsFilter($property, $value)
117
    {
118
        $this->queryBuilder
119
            ->andWhere("$this->tableAlias.$property <= :$property")
120
            ->setParameter($property, $value);
121
    }
122
123
124
    /**
125
     * @inheritdoc
126
     */
127
    public function applyBeginsWithFilter($property, $value)
128
    {
129
        $this->queryBuilder
130
            ->andWhere("$this->tableAlias.$property LIKE :$property")
131
            ->setParameter($property, "%$value");
132
    }
133
134
135
    /**
136
     * @inheritdoc
137
     */
138
    public function applyEndsWithFilter($property, $value)
139
    {
140
        $this->queryBuilder
141
            ->andWhere("$this->tableAlias.$property LIKE :$property")
142
            ->setParameter($property, "$value%");
143
    }
144
145
146
    /**
147
     * @param string $property
148
     * @param mixed  $value
149
     */
150
    public function applyFreeTextFilter($property, $value)
151
    {
152
        $this->queryBuilder
153
            ->andWhere("$this->tableAlias.$property LIKE :$property")
154
            ->setParameter($property, "%$value%");
155
    }
156
157
158
    /**
159
     * @param string $property
160
     * @param mixed  $value
161
     */
162
    public function applyEqualsFilter($property, $value)
163
    {
164
        $this->queryBuilder
165
            ->andWhere("$this->tableAlias.$property = :$property")
166
            ->setParameter($property, $value);
167
    }
168
169
170
    /**
171
     * @inheritdoc
172
     */
173
    public function applySort($property, $direction)
174
    {
175
        $this->queryBuilder
176
            ->addOrderBy("$this->tableAlias.$property", $direction);
177
    }
178
179
180
    /**
181
     * @inheritdoc
182
     */
183
    public function getResult()
184
    {
185
        return new Result($this->queryBuilder->getQuery()->getResult());
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Nord\Lumen\S...tQuery()->getResult()); (Nord\Lumen\Search\Result) is incompatible with the return type declared by the interface Nord\Lumen\Search\Contra...earchAdapter::getResult of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
186
    }
187
188
189
    /**
190
     * @inheritdoc
191
     */
192
    public function getPartialResult(Pagination $pagination)
193
    {
194
        $pager = new DoctrineORMAdapter($this->queryBuilder);
195
196
        $pageSize = $pagination->getPageSize();
197
198
        return new Result(
199
            $pager->getSlice($pagination->calculateOffset(), $pageSize)->getArrayCopy(),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Traversable as the method getArrayCopy() does only exist in the following implementations of said interface: ArrayIterator, ArrayObject, RecursiveArrayIterator.

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...
200
            $pager->getNbResults(),
201
            $pagination->getPageNumber(),
202
            $pageSize
203
        );
204
    }
205
}
206