| Conditions | 12 |
| Paths | 54 |
| Total Lines | 37 |
| Code Lines | 23 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 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 |
||
| 16 | public static function buildQuery(Builder $query, array $condition) |
||
| 17 | { |
||
| 18 | // 获取模型定义的搜索域 |
||
| 19 | $model = $query->getModel(); |
||
| 20 | $searchField = []; |
||
| 21 | if (property_exists($model, 'searchField')) { |
||
| 22 | $searchField = $model::$searchField; |
||
| 23 | } |
||
| 24 | |||
| 25 | foreach ($condition as $k => $v) { |
||
| 26 | if (!is_array($v) && isset($searchField[$k]['searchType'])) { |
||
| 27 | $condition[$k] = [$searchField[$k]['searchType'], $v]; |
||
| 28 | } |
||
| 29 | } |
||
| 30 | |||
| 31 | foreach ($condition as $k => $v) { |
||
| 32 | $type = 'like'; |
||
| 33 | $value = $v; |
||
| 34 | if (is_array($v)) { |
||
| 35 | list($type, $value) = $v; |
||
| 36 | } |
||
| 37 | $value = trim($value); |
||
| 38 | // 搜索值为空字符串则忽略该条件 |
||
| 39 | if ($value === '') { |
||
| 40 | continue; |
||
| 41 | } |
||
| 42 | |||
| 43 | if ($k === 'created_at' || $k === 'updated_at') { |
||
| 44 | $dates = explode(' ~ ', $value); |
||
| 45 | if (count($dates) === 2) { |
||
| 46 | $query->whereBetween($k, [ |
||
| 47 | Carbon::parse($dates[0])->startOfDay(), |
||
| 48 | Carbon::parse($dates[1])->endOfDay(), |
||
| 49 | ]); |
||
| 50 | } |
||
| 51 | } else { |
||
| 52 | $query->where($k, $type, $type === 'like' ? "%{$value}%" : $value); |
||
| 53 | } |
||
| 57 |