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 |
||
| 9 | class QueryBuilder extends BaseBuilder |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * WP_Query instance |
||
| 13 | * |
||
| 14 | * @var WP_Query |
||
| 15 | */ |
||
| 16 | protected $query; |
||
| 17 | |||
| 18 | /** |
||
| 19 | * Post Model instance |
||
| 20 | * |
||
| 21 | * @var Model |
||
| 22 | */ |
||
| 23 | protected $model; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * Builder constructor. |
||
| 27 | * |
||
| 28 | * @param WP_Query $query |
||
| 29 | */ |
||
| 30 | public function __construct(WP_Query $query) |
||
| 34 | |||
| 35 | /** |
||
| 36 | * Create a new instance. |
||
| 37 | * |
||
| 38 | * @return static |
||
| 39 | */ |
||
| 40 | public static function make() |
||
| 44 | |||
| 45 | /** |
||
| 46 | * Limit the number of returned results |
||
| 47 | * |
||
| 48 | * @param integer $limit The maximum number of results to return |
||
| 49 | * use -1 for no limit |
||
| 50 | * |
||
| 51 | * @return $this |
||
| 52 | */ |
||
| 53 | public function limit($limit) |
||
| 59 | |||
| 60 | /** |
||
| 61 | * Return an unlimited number of results. |
||
| 62 | * |
||
| 63 | * @return $this |
||
| 64 | */ |
||
| 65 | public function all() |
||
| 69 | |||
| 70 | /** |
||
| 71 | * Set the order for the query |
||
| 72 | * |
||
| 73 | * @param string $order |
||
| 74 | * |
||
| 75 | * @return $this |
||
| 76 | */ |
||
| 77 | public function order($order) |
||
| 83 | |||
| 84 | /** |
||
| 85 | * Query by post status |
||
| 86 | * |
||
| 87 | * @param string|array $status the post status or stati to match |
||
| 88 | * |
||
| 89 | * @return $this |
||
| 90 | */ |
||
| 91 | public function whereStatus($status) |
||
| 97 | |||
| 98 | /** |
||
| 99 | * Query by slug |
||
| 100 | * |
||
| 101 | * @param string $slug the post slug to query by |
||
| 102 | * |
||
| 103 | * @return $this |
||
| 104 | */ |
||
| 105 | public function whereSlug($slug) |
||
| 111 | |||
| 112 | /** |
||
| 113 | * Get the results as a collection |
||
| 114 | * |
||
| 115 | * @return Collection |
||
| 116 | */ |
||
| 117 | public function results() |
||
| 125 | |||
| 126 | /** |
||
| 127 | * Get the results as a collection of post model instances |
||
| 128 | * |
||
| 129 | * @return Collection |
||
| 130 | */ |
||
| 131 | View Code Duplication | protected function collectModels() |
|
| 142 | |||
| 143 | /** |
||
| 144 | * Set a query variable on the query |
||
| 145 | * |
||
| 146 | * @param string $var Query variable key |
||
| 147 | * @param mixed $value Query value for key |
||
| 148 | * |
||
| 149 | * @return $this |
||
| 150 | */ |
||
| 151 | public function set($var, $value) |
||
| 157 | } |
||
| 158 |