Completed
Pull Request — master (#375)
by Dalibor
02:34
created

DibiFluentDataSource   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 313
Duplicated Lines 5.75 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 0
Metric Value
wmc 34
lcom 1
cbo 14
dl 18
loc 313
rs 9.2
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getCount() 0 4 1
A getData() 0 4 2
A filterOne() 0 6 1
A applyFilterDate() 8 8 1
A applyFilterDateRange() 0 21 3
B applyFilterRange() 0 15 5
C applyFilterText() 10 41 7
B applyFilterMultiSelect() 0 26 4
A applyFilterSelect() 0 4 1
A limit() 0 6 1
B sort() 0 35 4
A addAggregationColumn() 0 4 1
A getAggregationData() 0 8 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * @copyright   Copyright (c) 2015 ublaboo <[email protected]>
5
 * @author      Pavel Janda <[email protected]>
6
 * @package     Ublaboo
7
 */
8
9
namespace Ublaboo\DataGrid\DataSource;
10
11
use Dibi;
12
use DibiFluent;
13
use Nette\Utils\Strings;
14
use Ublaboo\DataGrid\Filter;
15
use Ublaboo\DataGrid\Utils\DateTimeHelper;
16
use Ublaboo\DataGrid\Utils\Sorting;
17
18
class DibiFluentDataSource extends FilterableDataSource implements IDataSource
19
{
20
21
	/**
22
	 * @var Dibi\Fluent
23
	 */
24
	protected $data_source;
25
26
	/**
27
	 * @var Dibi\Fluent
28
	 */
29
	protected $aggregation_data_source;
30
31
	/**
32
	 * @var array
33
	 */
34
	protected $data = [];
35
36
	/**
37
	 * @var string
38
	 */
39
	protected $primary_key;
40
41
	/**
42
	 * @var bool
43
	 */
44
	protected $hasAggregationFunctions = FALSE;
45
46
47
	/**
48
	 * @param Dibi\Fluent $data_source
49
	 * @param string $primary_key
50
	 */
51
	public function __construct(Dibi\Fluent $data_source, $primary_key)
52
	{
53
		$this->data_source = $data_source;
54
		$this->aggregation_data_source = $data_source->getConnection();
0 ignored issues
show
Documentation Bug introduced by
It seems like $data_source->getConnection() of type object<Dibi\Connection> is incompatible with the declared type object<Dibi\Fluent> of property $aggregation_data_source.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
55
		$this->primary_key = $primary_key;
56
	}
57
58
59
	/********************************************************************************
60
	 *                          IDataSource implementation                          *
61
	 ********************************************************************************/
62
63
64
	/**
65
	 * Get count of data
66
	 * @return int
67
	 */
68
	public function getCount()
69
	{
70
		return $this->data_source->count();
71
	}
72
73
74
	/**
75
	 * Get the data
76
	 * @return array
77
	 */
78
	public function getData()
79
	{
80
		return $this->data ?: $this->data_source->fetchAll();
81
	}
82
83
84
	/**
85
	 * Filter data - get one row
86
	 * @param array $condition
87
	 * @return static
88
	 */
89
	public function filterOne(array $condition)
90
	{
91
		$this->data_source->where($condition)->limit(1);
92
93
		return $this;
94
	}
95
96
97
	/**
98
	 * Filter by date
99
	 * @param  Filter\FilterDate $filter
100
	 * @return void
101
	 */
102 View Code Duplication
	public function applyFilterDate(Filter\FilterDate $filter)
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...
103
	{
104
		$conditions = $filter->getCondition();
105
106
		$date = DateTimeHelper::tryConvertToDateTime($conditions[$filter->getColumn()], [$filter->getPhpFormat()]);
107
108
		$this->data_source->where('DATE(%n) = ?', $filter->getColumn(), $date->format('Y-m-d'));
0 ignored issues
show
Unused Code introduced by
The call to Fluent::where() has too many arguments starting with $filter->getColumn().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
109
	}
110
111
112
	/**
113
	 * Filter by date range
114
	 * @param  Filter\FilterDateRange $filter
115
	 * @return void
116
	 */
117
	public function applyFilterDateRange(Filter\FilterDateRange $filter)
118
	{
119
		$conditions = $filter->getCondition();
120
121
		$value_from = $conditions[$filter->getColumn()]['from'];
122
		$value_to   = $conditions[$filter->getColumn()]['to'];
123
124
		if ($value_from) {
125
			$date_from = DateTimeHelper::tryConvertToDateTime($value_from, [$filter->getPhpFormat()]);
126
			$date_from->setTime(0, 0, 0);
127
128
			$this->data_source->where('DATE(%n) >= ?', $filter->getColumn(), $date_from);
0 ignored issues
show
Unused Code introduced by
The call to Fluent::where() has too many arguments starting with $filter->getColumn().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
129
		}
130
131
		if ($value_to) {
132
			$date_to = DateTimeHelper::tryConvertToDateTime($value_to, [$filter->getPhpFormat()]);
133
			$date_to->setTime(23, 59, 59);
134
135
			$this->data_source->where('DATE(%n) <= ?', $filter->getColumn(), $date_to);
0 ignored issues
show
Unused Code introduced by
The call to Fluent::where() has too many arguments starting with $filter->getColumn().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
136
		}
137
	}
138
139
140
	/**
141
	 * Filter by range
142
	 * @param  Filter\FilterRange $filter
143
	 * @return void
144
	 */
145
	public function applyFilterRange(Filter\FilterRange $filter)
146
	{
147
		$conditions = $filter->getCondition();
148
149
		$value_from = $conditions[$filter->getColumn()]['from'];
150
		$value_to   = $conditions[$filter->getColumn()]['to'];
151
152
		if ($value_from || $value_from != '') {
153
			$this->data_source->where('%n >= ?', $filter->getColumn(), $value_from);
0 ignored issues
show
Unused Code introduced by
The call to Fluent::where() has too many arguments starting with $filter->getColumn().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
154
		}
155
156
		if ($value_to || $value_to != '') {
157
			$this->data_source->where('%n <= ?', $filter->getColumn(), $value_to);
0 ignored issues
show
Unused Code introduced by
The call to Fluent::where() has too many arguments starting with $filter->getColumn().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
158
		}
159
	}
160
161
162
	/**
163
	 * Filter by keyword
164
	 * @param  Filter\FilterText $filter
165
	 * @return void
166
	 */
167
	public function applyFilterText(Filter\FilterText $filter)
168
	{
169
		$condition = $filter->getCondition();
170
		$or = [];
171
172
		foreach ($condition as $column => $value) {
173
			$column = Dibi\Helpers::escape(
174
				$this->data_source->getConnection()->getDriver(),
175
				$column,
176
				\dibi::IDENTIFIER
177
			);
178
179
			if ($filter->isExactSearch()) {
180
				$this->data_source->where("$column = %s", $value);
0 ignored issues
show
Unused Code introduced by
The call to Fluent::where() has too many arguments starting with $value.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
181
				continue;
182
			}
183
184 View Code Duplication
			if ($filter->hasSplitWordsSearch() === FALSE) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
185
				$words = [$value];
186
			} else {
187
				$words = explode(' ', $value);
188
			}
189
190
			foreach ($words as $word) {
191
				$escaped = $this->data_source->getConnection()->getDriver()->escapeLike($word, 0);
192
193
				if (preg_match("/[\x80-\xFF]/", $escaped)) {
194
					$or[] = "$column LIKE $escaped COLLATE utf8_bin";
195
				} else {
196
					$escaped = Strings::toAscii($escaped);
197
					$or[] = "$column LIKE $escaped COLLATE utf8_general_ci";
198
				}
199
			}
200
		}
201
202 View Code Duplication
		if (sizeof($or) > 1) {
203
			$this->data_source->where('(%or)', $or);
0 ignored issues
show
Unused Code introduced by
The call to Fluent::where() has too many arguments starting with $or.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
204
		} else {
205
			$this->data_source->where($or);
206
		}
207
	}
208
209
210
	/**
211
	 * Filter by multi select value
212
	 * @param  Filter\FilterMultiSelect $filter
213
	 * @return void
214
	 */
215
	public function applyFilterMultiSelect(Filter\FilterMultiSelect $filter)
216
	{
217
		$condition = $filter->getCondition();
218
		$values = $condition[$filter->getColumn()];
219
		$or = [];
0 ignored issues
show
Unused Code introduced by
$or is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
220
221
		if (sizeof($values) > 1) {
222
			$value1 = array_shift($values);
223
			$length = sizeof($values);
224
			$i = 1;
225
226
			$this->data_source->where('(%n = ?', $filter->getColumn(), $value1);
0 ignored issues
show
Unused Code introduced by
The call to Fluent::where() has too many arguments starting with $filter->getColumn().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
227
228
			foreach ($values as $value) {
229
				if ($i == $length) {
230
					$this->data_source->or('%n = ?)', $filter->getColumn(), $value);
231
				} else {
232
					$this->data_source->or('%n = ?', $filter->getColumn(), $value);
233
				}
234
235
				$i++;
236
			}
237
		} else {
238
			$this->data_source->where('%n = ?', $filter->getColumn(), reset($values));
0 ignored issues
show
Unused Code introduced by
The call to Fluent::where() has too many arguments starting with $filter->getColumn().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
239
		}
240
	}
241
242
243
	/**
244
	 * Filter by select value
245
	 * @param  Filter\FilterSelect $filter
246
	 * @return void
247
	 */
248
	public function applyFilterSelect(Filter\FilterSelect $filter)
249
	{
250
		$this->data_source->where($filter->getCondition());
251
	}
252
253
254
	/**
255
	 * Apply limit and offset on data
256
	 * @param int $offset
257
	 * @param int $limit
258
	 * @return static
259
	 */
260
	public function limit($offset, $limit)
261
	{
262
		$this->data = $this->data_source->fetchAll($offset, $limit);
263
264
		return $this;
265
	}
266
267
268
	/**
269
	 * Sort data
270
	 * @param  Sorting $sorting
271
	 * @return static
272
	 */
273
	public function sort(Sorting $sorting)
274
	{
275
		if (is_callable($sorting->getSortCallback())) {
276
			call_user_func(
277
				$sorting->getSortCallback(),
278
				$this->data_source,
279
				$sorting->getSort()
280
			);
281
282
			return $this;
283
		}
284
285
		$sort = $sorting->getSort();
286
287
		if (!empty($sort)) {
288
			$this->data_source->removeClause('ORDER BY');
289
			$this->data_source->orderBy($sort);
290
		} else {
291
			/**
292
			 * Has the statement already a order by clause?
293
			 */
294
			$this->data_source->clause('ORDER BY');
295
296
			$reflection = new \ReflectionClass('DibiFluent');
297
			$cursor_property = $reflection->getProperty('cursor');
298
			$cursor_property->setAccessible(TRUE);
299
			$cursor = $cursor_property->getValue($this->data_source);
300
301
			if (!$cursor) {
302
				$this->data_source->orderBy($this->primary_key);
303
			}
304
		}
305
306
		return $this;
307
	}
308
309
	/**
310
	 * @param string $aggregation_type
311
	 * @param string $column
312
	 */
313
	public function addAggregationColumn($aggregation_type, $column)
314
	{
315
		$this->aggregation_data_source = $this->aggregation_data_source->select($aggregation_type .'(%n)', $column)->as($column);
0 ignored issues
show
Unused Code introduced by
The call to Fluent::select() has too many arguments starting with $column.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
316
	}
317
318
319
	/**
320
	 * @return array|Dibi\Row|FALSE
321
	 */
322
	public function getAggregationData()
323
	{
324
		if ($this->hasAggregationFunctions) {
325
			return FALSE;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return FALSE; (false) is incompatible with the return type declared by the interface Ublaboo\DataGrid\DataSou...rce::getAggregationData 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...
326
		}
327
		$data = $this->aggregation_data_source->from($this->data_source)->as('data')->fetch();
328
		return $data;
329
	}
330
}
331