Conditions | 10 |
Paths | 144 |
Total Lines | 61 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
24 | protected function getQuery(SearchQuery $search): Query |
||
25 | { |
||
26 | $table = $this->getTable(); |
||
27 | |||
28 | $query = $table->select(); |
||
29 | |||
30 | //Filter by id |
||
31 | if (count($search->getIds())) { |
||
32 | $query->where('id IN', $search->getIds()); |
||
33 | } |
||
34 | |||
35 | if ($search->getPage() !== null) { |
||
36 | $limit = $search->getLimit(); |
||
37 | |||
38 | $query->offset(($search->getPage() * $limit) - $limit)->limit($limit); |
||
39 | } |
||
40 | |||
41 | if ($this->searchFields === null) { |
||
42 | $this->searchFields = [$this->getFirstField()]; |
||
43 | } |
||
44 | |||
45 | $orderBy = $search->getSort(); |
||
46 | |||
47 | if (empty($orderBy)) { |
||
48 | $query->orderBy("{$table->id} DESC"); |
||
49 | } else { |
||
50 | foreach ($orderBy as $field => $direction) { |
||
51 | $query->orderBy("{$table->$field} {$direction}"); |
||
52 | } |
||
53 | } |
||
54 | |||
55 | //Filter by words |
||
56 | foreach ($search->getWords() as $word) { |
||
57 | $query->where('('); |
||
58 | $like = "%{$word}%"; |
||
59 | |||
60 | foreach ($this->searchFields as $k => $field) { |
||
61 | if ($k !== 0) { |
||
62 | $query->catWhere(' OR '); |
||
63 | } |
||
64 | |||
65 | $query->catWhere("{$table->$field} LIKE ", $like); |
||
66 | } |
||
67 | |||
68 | $query->catWhere(')'); |
||
69 | } |
||
70 | |||
71 | //Filter by relations |
||
72 | $db = $table->getDatabase(); |
||
73 | |||
74 | foreach ($search->getConditions() as $name => $value) { |
||
75 | $related = $db->$name |
||
76 | ->select() |
||
77 | ->whereEquals(['id' => $value]) |
||
78 | ->run(); |
||
79 | |||
80 | $query->relatedWith($related); |
||
81 | } |
||
82 | |||
83 | return $query; |
||
84 | } |
||
85 | |||
232 |