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:
Complex classes like QueryBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use QueryBuilder, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 26 | class QueryBuilder implements Countable |
||
| 27 | { |
||
| 28 | /** |
||
| 29 | * The type of the model we're building a query for |
||
| 30 | * @var string |
||
| 31 | */ |
||
| 32 | protected $type; |
||
| 33 | |||
| 34 | /** |
||
| 35 | * The columns that the model provided us |
||
| 36 | * @var array |
||
| 37 | */ |
||
| 38 | protected $columns = array('id' => 'id'); |
||
| 39 | |||
| 40 | /** |
||
| 41 | * The conditions to include in WHERE |
||
| 42 | * @var string[] |
||
| 43 | */ |
||
| 44 | protected $conditions = array(); |
||
| 45 | |||
| 46 | /** |
||
| 47 | * The MySQL value parameters |
||
| 48 | * @var array |
||
| 49 | */ |
||
| 50 | protected $parameters = array(); |
||
| 51 | |||
| 52 | /** |
||
| 53 | * The MySQL parameter types |
||
| 54 | * @var string |
||
| 55 | */ |
||
| 56 | protected $types = ''; |
||
| 57 | |||
| 58 | /** |
||
| 59 | * The MySQL value parameters for pagination |
||
| 60 | * @var array |
||
| 61 | */ |
||
| 62 | protected $paginationParameters = array(); |
||
| 63 | |||
| 64 | /** |
||
| 65 | * The MySQL parameter types for pagination |
||
| 66 | * @var string |
||
| 67 | */ |
||
| 68 | protected $paginationTypes = ''; |
||
| 69 | |||
| 70 | /** |
||
| 71 | * Extra MySQL query string to pass |
||
| 72 | * @var string |
||
| 73 | */ |
||
| 74 | protected $extras = ''; |
||
| 75 | |||
| 76 | /** |
||
| 77 | * Extra MySQL query groupby string to pass |
||
| 78 | * @var string |
||
| 79 | */ |
||
| 80 | protected $groupQuery = ''; |
||
| 81 | |||
| 82 | /** |
||
| 83 | * A column based on which we should sort the results |
||
| 84 | * @var string|null |
||
| 85 | */ |
||
| 86 | private $sortBy = null; |
||
| 87 | |||
| 88 | /** |
||
| 89 | * Whether to reverse the results |
||
| 90 | * @var bool |
||
| 91 | */ |
||
| 92 | private $reverseSort = false; |
||
| 93 | |||
| 94 | /** |
||
| 95 | * The currently selected column |
||
| 96 | * @var string|null |
||
| 97 | */ |
||
| 98 | private $currentColumn = null; |
||
| 99 | |||
| 100 | /** |
||
| 101 | * The currently selected column without the table name (unless it was |
||
| 102 | * explicitly provided) |
||
| 103 | * @var string|null |
||
| 104 | */ |
||
| 105 | protected $currentColumnRaw = null; |
||
| 106 | |||
| 107 | /** |
||
| 108 | * A column to consider the name of the model |
||
| 109 | * @var string|null |
||
| 110 | */ |
||
| 111 | private $nameColumn = null; |
||
| 112 | |||
| 113 | /** |
||
| 114 | * Whether to return the results as arrays instead of models |
||
| 115 | * @var bool |
||
| 116 | */ |
||
| 117 | private $returnArray = false; |
||
|
|
|||
| 118 | |||
| 119 | /** |
||
| 120 | * The page to return |
||
| 121 | * @var int|null |
||
| 122 | */ |
||
| 123 | private $page = null; |
||
| 124 | |||
| 125 | /** |
||
| 126 | * Whether the ID of the first/last element has been provided |
||
| 127 | * @var bool |
||
| 128 | */ |
||
| 129 | private $limited = false; |
||
| 130 | |||
| 131 | /** |
||
| 132 | * The number of elements on every page |
||
| 133 | * @var int |
||
| 134 | */ |
||
| 135 | protected $resultsPerPage = 30; |
||
| 136 | |||
| 137 | /** |
||
| 138 | * Create a new QueryBuilder |
||
| 139 | * |
||
| 140 | * A new query builder should be created on a static getQueryBuilder() |
||
| 141 | * method on each model. The options array can contain the following |
||
| 142 | * properties: |
||
| 143 | * |
||
| 144 | * - `columns`: An associative array - the key of each entry is the column |
||
| 145 | * name that will be used by other methods, while the value is |
||
| 146 | * is the column name that is used in the database structure |
||
| 147 | * |
||
| 148 | * - `activeStatuses`: If the model has a status column, this should be |
||
| 149 | * a list of values that make the entry be considered |
||
| 150 | * "active" |
||
| 151 | * |
||
| 152 | * - `name`: The name of the column which represents the name of the object |
||
| 153 | * |
||
| 154 | * @param string $type The type of the Model (e.g. "Player" or "Match") |
||
| 155 | * @param array $options The options to pass to the builder (see above) |
||
| 156 | */ |
||
| 157 | 1 | public function __construct($type, $options = array()) |
|
| 158 | { |
||
| 159 | 1 | $this->type = $type; |
|
| 160 | |||
| 161 | 1 | if (isset($options['columns'])) { |
|
| 162 | 1 | $this->columns += $options['columns']; |
|
| 163 | } |
||
| 164 | |||
| 165 | 1 | if (isset($options['name'])) { |
|
| 166 | 1 | $this->nameColumn = $options['name']; |
|
| 167 | } |
||
| 168 | 1 | } |
|
| 169 | |||
| 170 | /** |
||
| 171 | * Select a column |
||
| 172 | * |
||
| 173 | * `$queryBuilder->where('username')->equals('administrator');` |
||
| 174 | * |
||
| 175 | * @param string $column The column to select |
||
| 176 | * @return self |
||
| 177 | */ |
||
| 178 | 1 | public function where($column) |
|
| 188 | |||
| 189 | /** |
||
| 190 | * Request that a column equals a string (case-insensitive) |
||
| 191 | * |
||
| 192 | * @param string $string The string that the column's value should equal to |
||
| 193 | * @return self |
||
| 194 | */ |
||
| 195 | public function equals($string) |
||
| 201 | |||
| 202 | /** |
||
| 203 | * Request that a column doesNOT equals a string (case-insensitive) |
||
| 204 | * |
||
| 205 | * @param string $string The string that the column's value should equal to |
||
| 206 | * @return self |
||
| 207 | */ |
||
| 208 | 1 | public function notEquals($string) |
|
| 214 | |||
| 215 | /** |
||
| 216 | * Request that a column is greater than a quantity |
||
| 217 | * |
||
| 218 | * @param string $quantity The quantity to test against |
||
| 219 | * @return self |
||
| 220 | */ |
||
| 221 | public function greaterThan($quantity) |
||
| 227 | |||
| 228 | /** |
||
| 229 | * Request that a column is less than a quantity |
||
| 230 | * |
||
| 231 | * @param string $quantity The quantity to test against |
||
| 232 | * @return self |
||
| 233 | */ |
||
| 234 | public function lessThan($quantity) |
||
| 240 | |||
| 241 | /** |
||
| 242 | * Request that a timestamp is before the specified time |
||
| 243 | * |
||
| 244 | * @param string|TimeDate $time The timestamp to compare to |
||
| 245 | * @param bool $inclusive Whether to include the given timestamp |
||
| 246 | * @param bool $reverse Whether to reverse the results |
||
| 247 | */ |
||
| 248 | public function isBefore($time, $inclusive = false, $reverse = false) |
||
| 252 | |||
| 253 | /** |
||
| 254 | * Request that a timestamp is after the specified time |
||
| 255 | * |
||
| 256 | * @param string|TimeDate $time The timestamp to compare to |
||
| 257 | * @param bool $inclusive Whether to include the given timestamp |
||
| 258 | * @param bool $reverse Whether to reverse the results |
||
| 259 | */ |
||
| 260 | 1 | public function isAfter($time, $inclusive = false, $reverse = false) |
|
| 261 | { |
||
| 262 | 1 | if ($time instanceof TimeDate) { |
|
| 263 | 1 | $time = $time->toMysql(); |
|
| 264 | } |
||
| 265 | |||
| 266 | 1 | $comparison = ($reverse) ? '<' : '>'; |
|
| 267 | 1 | $comparison .= ($inclusive) ? '=' : ''; |
|
| 268 | |||
| 269 | 1 | $this->addColumnCondition("$comparison ?", $time, 's'); |
|
| 270 | |||
| 271 | 1 | return $this; |
|
| 272 | } |
||
| 273 | |||
| 274 | /** |
||
| 275 | * Request that a column equals a number |
||
| 276 | * |
||
| 277 | * @param int|Model|null $number The number that the column's value should |
||
| 278 | * equal to. If a Model is provided, use the |
||
| 279 | * model's ID, while null values are ignored. |
||
| 280 | * @return self |
||
| 281 | */ |
||
| 282 | 1 | View Code Duplication | public function is($number) |
| 283 | { |
||
| 284 | 1 | if ($number === null) { |
|
| 285 | return $this; |
||
| 286 | } |
||
| 287 | |||
| 288 | 1 | if ($number instanceof Model) { |
|
| 289 | 1 | $number = $number->getId(); |
|
| 290 | } |
||
| 291 | |||
| 292 | 1 | $this->addColumnCondition("= ?", $number, 'i'); |
|
| 293 | |||
| 294 | 1 | return $this; |
|
| 295 | } |
||
| 296 | |||
| 297 | /** |
||
| 298 | * Request that a column equals one of some strings |
||
| 299 | * |
||
| 300 | * @param string[] $strings The list of accepted values for the column |
||
| 301 | * @return self |
||
| 302 | */ |
||
| 303 | 1 | public function isOneOf($strings) |
|
| 316 | |||
| 317 | /** |
||
| 318 | * Request that a column value starts with a string (case-insensitive) |
||
| 319 | * |
||
| 320 | * @param string $string The substring that the column's value should start with |
||
| 321 | * @return self |
||
| 322 | */ |
||
| 323 | public function startsWith($string) |
||
| 329 | |||
| 330 | /** |
||
| 331 | * Request that a specific model is not returned |
||
| 332 | * |
||
| 333 | * @param Model|int $model The ID or model you don't want to get |
||
| 334 | * @return self |
||
| 335 | */ |
||
| 336 | View Code Duplication | public function except($model) |
|
| 337 | { |
||
| 338 | if ($model instanceof Model) { |
||
| 339 | $model = $model->getId(); |
||
| 340 | } |
||
| 341 | |||
| 342 | $this->where('id'); |
||
| 343 | $this->addColumnCondition("!= ?", $model, 'i'); |
||
| 344 | |||
| 345 | return $this; |
||
| 346 | } |
||
| 347 | |||
| 348 | /** |
||
| 349 | * Return the results sorted by the value of a column |
||
| 350 | * |
||
| 351 | * @param string $column The column based on which the results should be ordered |
||
| 352 | * @return self |
||
| 353 | */ |
||
| 354 | 1 | public function sortBy($column) |
|
| 364 | |||
| 365 | /** |
||
| 366 | * Reverse the order |
||
| 367 | * |
||
| 368 | * Note: This only works if you have specified a column in the sortBy() method |
||
| 369 | * |
||
| 370 | * @return self |
||
| 371 | */ |
||
| 372 | 1 | public function reverse() |
|
| 378 | |||
| 379 | /** |
||
| 380 | * Specify the number of results per page |
||
| 381 | * |
||
| 382 | * @param int $count The number of results |
||
| 383 | * @return self |
||
| 384 | */ |
||
| 385 | 1 | public function limit($count) |
|
| 391 | |||
| 392 | /** |
||
| 393 | * Only show results from a specific page |
||
| 394 | * |
||
| 395 | * @param int|null $page The page number (or null to show all pages - counting starts from 0) |
||
| 396 | * @return self |
||
| 397 | */ |
||
| 398 | 1 | public function fromPage($page) |
|
| 404 | |||
| 405 | /** |
||
| 406 | * End with a specific result |
||
| 407 | * |
||
| 408 | * @param int|Model $model The model (or database ID) after the first result |
||
| 409 | * @param bool $inclusive Whether to include the provided model |
||
| 410 | * @param bool $reverse Whether to reverse the results |
||
| 411 | * @return self |
||
| 412 | */ |
||
| 413 | 1 | public function endAt($model, $inclusive = false, $reverse = false) |
|
| 417 | |||
| 418 | /** |
||
| 419 | * Start with a specific result |
||
| 420 | * |
||
| 421 | * @param int|Model $model The model (or database ID) before the first result |
||
| 422 | * @param bool $inclusive Whether to include the provided model |
||
| 423 | * @param bool $reverse Whether to reverse the results |
||
| 424 | * @return self |
||
| 425 | */ |
||
| 426 | 1 | public function startAt($model, $inclusive = false, $reverse = false) |
|
| 454 | |||
| 455 | /** |
||
| 456 | * Request that only "active" Models should be returned |
||
| 457 | * |
||
| 458 | * @return self |
||
| 459 | */ |
||
| 460 | 1 | public function active() |
|
| 470 | |||
| 471 | /** |
||
| 472 | * Make sure that Models invisible to a player are not returned |
||
| 473 | * |
||
| 474 | * Note that this method does not take PermissionModel::canBeSeenBy() into |
||
| 475 | * consideration for performance purposes, so you will have to override this |
||
| 476 | * in your query builder if necessary. |
||
| 477 | * |
||
| 478 | * @param Player $player The player in question |
||
| 479 | * @param bool $showDeleted false to hide deleted models even from admins |
||
| 480 | * @return self |
||
| 481 | */ |
||
| 482 | 1 | public function visibleTo($player, $showDeleted = false) |
|
| 498 | |||
| 499 | /** |
||
| 500 | * Perform the query and get back the results in an array of names |
||
| 501 | * |
||
| 502 | * @return string[] An array of the type $id => $name |
||
| 503 | */ |
||
| 504 | 1 | public function getNames() |
|
| 514 | |||
| 515 | /** |
||
| 516 | * Perform the query and get back the results in a list of arrays |
||
| 517 | * |
||
| 518 | * @todo Play with partial models? |
||
| 519 | * @param string|string[] $columns The column(s) that should be returned |
||
| 520 | * @return array[] |
||
| 521 | */ |
||
| 522 | 1 | public function getArray($columns) |
|
| 523 | { |
||
| 524 | 1 | if (!is_array($columns)) { |
|
| 525 | 1 | $columns = array($columns); |
|
| 526 | } |
||
| 527 | |||
| 528 | 1 | $db = Database::getInstance(); |
|
| 529 | |||
| 530 | 1 | return $db->query($this->createQuery($columns), $this->getTypes(), $this->getParameters()); |
|
| 531 | } |
||
| 532 | |||
| 533 | /** |
||
| 534 | * An alias for QueryBuilder::getModels(), with fast fetching on by default |
||
| 535 | * and no return of results |
||
| 536 | * |
||
| 537 | * @param bool $fastFetch Whether to perform one query to load all |
||
| 538 | * the model data instead of fetching them |
||
| 539 | * one by one |
||
| 540 | * @return void |
||
| 541 | */ |
||
| 542 | public function addToCache($fastFetch = true) |
||
| 546 | |||
| 547 | /** |
||
| 548 | * Perform the query and get the results as Models |
||
| 549 | * |
||
| 550 | * @todo Fix fast fetch for queries with multiple tables |
||
| 551 | * @param bool $fastFetch Whether to perform one query to load all |
||
| 552 | * the model data instead of fetching them |
||
| 553 | * one by one (ignores cache) |
||
| 554 | * @return array |
||
| 555 | */ |
||
| 556 | 1 | public function getModels($fastFetch = false) |
|
| 571 | |||
| 572 | /** |
||
| 573 | * Count the results |
||
| 574 | * |
||
| 575 | * @return int |
||
| 576 | */ |
||
| 577 | 1 | public function count() |
|
| 590 | |||
| 591 | /** |
||
| 592 | * Count the number of pages that all the models could be separated into |
||
| 593 | */ |
||
| 594 | 1 | public function countPages() |
|
| 598 | |||
| 599 | /** |
||
| 600 | * Find if there is any result |
||
| 601 | * |
||
| 602 | * @return bool |
||
| 603 | */ |
||
| 604 | 1 | public function any() |
|
| 613 | |||
| 614 | /** |
||
| 615 | * Get the amount of results that are returned per page |
||
| 616 | * @return int |
||
| 617 | */ |
||
| 618 | 1 | public function getResultsPerPage() |
|
| 622 | |||
| 623 | /** |
||
| 624 | * Select a column to perform opeations on |
||
| 625 | * |
||
| 626 | * This is identical to the `where()` method, except that the column is |
||
| 627 | * specified as a MySQL column and not as a column name given by the model |
||
| 628 | * |
||
| 629 | * @param string $column The column to select |
||
| 630 | * @return self |
||
| 631 | */ |
||
| 632 | 1 | protected function column($column) |
|
| 633 | { |
||
| 634 | 1 | if (strpos($column, '.') === false) { |
|
| 635 | // Add the table name to the column if it isn't there already so that |
||
| 636 | // MySQL knows what to do when handling multiple tables |
||
| 637 | 1 | $table = $this->getTable(); |
|
| 638 | 1 | $this->currentColumn = "`$table`.`$column`"; |
|
| 639 | } else { |
||
| 640 | 1 | $this->currentColumn = $column; |
|
| 641 | } |
||
| 642 | |||
| 643 | 1 | $this->currentColumnRaw = $column; |
|
| 644 | |||
| 645 | 1 | return $this; |
|
| 646 | } |
||
| 647 | |||
| 648 | /** |
||
| 649 | * Add a condition for the column |
||
| 650 | * @param string $condition The MySQL condition |
||
| 651 | * @param mixed $value Value(s) to pass to MySQL |
||
| 652 | * @param string $type The type of the values |
||
| 653 | * @return void |
||
| 654 | */ |
||
| 655 | 1 | protected function addColumnCondition($condition, $value, $type) |
|
| 656 | { |
||
| 657 | 1 | if (!$this->currentColumn) { |
|
| 658 | throw new Exception("You haven't selected a column!"); |
||
| 659 | } |
||
| 660 | |||
| 661 | 1 | if (!is_array($value)) { |
|
| 662 | 1 | $value = array($value); |
|
| 663 | } |
||
| 664 | |||
| 665 | 1 | $this->conditions[] = "{$this->currentColumn} $condition"; |
|
| 666 | 1 | $this->parameters = array_merge($this->parameters, $value); |
|
| 667 | 1 | $this->types .= $type; |
|
| 668 | |||
| 669 | 1 | $this->currentColumn = null; |
|
| 670 | 1 | $this->currentColumnRaw = null; |
|
| 671 | 1 | } |
|
| 672 | |||
| 673 | /** |
||
| 674 | * Get the MySQL extra parameters |
||
| 675 | * |
||
| 676 | * @param bool $respectPagination Whether to respect pagination or not; useful for when pagination should be ignored such as count |
||
| 677 | * @return string |
||
| 678 | */ |
||
| 679 | 1 | protected function createQueryParams($respectPagination = true) |
|
| 680 | { |
||
| 681 | 1 | $extras = $this->extras; |
|
| 682 | 1 | $conditions = $this->createQueryConditions(); |
|
| 683 | 1 | $groupQuery = $this->groupQuery; |
|
| 684 | 1 | $order = $this->createQueryOrder(); |
|
| 685 | 1 | $pagination = ""; |
|
| 686 | |||
| 687 | 1 | if ($respectPagination) { |
|
| 688 | 1 | $pagination = $this->createQueryPagination(); |
|
| 689 | } |
||
| 690 | |||
| 691 | 1 | return "$extras $conditions $groupQuery $order $pagination"; |
|
| 692 | } |
||
| 693 | |||
| 694 | /** |
||
| 695 | * Get the query parameters |
||
| 696 | * |
||
| 697 | * @return array |
||
| 698 | */ |
||
| 699 | 1 | protected function getParameters() |
|
| 703 | |||
| 704 | /** |
||
| 705 | * Get the query types |
||
| 706 | * |
||
| 707 | * @return string |
||
| 708 | */ |
||
| 709 | 1 | protected function getTypes() |
|
| 713 | |||
| 714 | /** |
||
| 715 | * Get the table of the model |
||
| 716 | * |
||
| 717 | * @return string |
||
| 718 | */ |
||
| 719 | 1 | protected function getTable() |
|
| 725 | |||
| 726 | /** |
||
| 727 | * Get a MySQL query string in the requested format |
||
| 728 | * @param string|string[] $columns The columns that should be included |
||
| 729 | * (without the ID, if an array is provided) |
||
| 730 | * @return string The query |
||
| 731 | */ |
||
| 732 | 1 | protected function createQuery($columns = array()) |
|
| 733 | { |
||
| 734 | 1 | $type = $this->type; |
|
| 735 | 1 | $table = $type::TABLE; |
|
| 736 | 1 | $params = $this->createQueryParams(); |
|
| 737 | |||
| 738 | 1 | if (is_array($columns)) { |
|
| 739 | 1 | $columns = $this->createQueryColumns($columns); |
|
| 740 | } elseif (empty($columns)) { |
||
| 741 | $columns = $this->createQueryColumns(); |
||
| 742 | } |
||
| 743 | |||
| 744 | 1 | return "SELECT $columns FROM $table $params"; |
|
| 745 | } |
||
| 746 | |||
| 747 | /** |
||
| 748 | * Generate the columns for the query |
||
| 749 | * @param string[] $columns The columns that should be included (without the ID) |
||
| 750 | * @return string |
||
| 751 | */ |
||
| 752 | 1 | private function createQueryColumns($columns = array()) |
|
| 753 | { |
||
| 754 | 1 | $type = $this->type; |
|
| 755 | 1 | $table = $type::TABLE; |
|
| 756 | 1 | $columnStrings = array("`$table`.id"); |
|
| 757 | |||
| 758 | 1 | foreach ($columns as $returnName) { |
|
| 759 | 1 | if (strpos($returnName, ' ') === false) { |
|
| 760 | 1 | $dbName = $this->columns[$returnName]; |
|
| 761 | 1 | $columnStrings[] = "`$table`.`$dbName` as `$returnName`"; |
|
| 762 | } else { |
||
| 763 | // "Column" contains a space, pass it as is |
||
| 764 | 1 | $columnStrings[] = $returnName; |
|
| 765 | } |
||
| 766 | } |
||
| 767 | |||
| 768 | 1 | return implode(',', $columnStrings); |
|
| 769 | } |
||
| 770 | |||
| 771 | /** |
||
| 772 | * Generates all the WHERE conditions for the query |
||
| 773 | * @return string |
||
| 774 | */ |
||
| 775 | 1 | private function createQueryConditions() |
|
| 787 | |||
| 788 | /** |
||
| 789 | * Generates the sorting instructions for the query |
||
| 790 | * @return string |
||
| 791 | */ |
||
| 792 | 1 | private function createQueryOrder() |
|
| 793 | { |
||
| 794 | 1 | if ($this->sortBy) { |
|
| 795 | 1 | $order = 'ORDER BY ' . $this->sortBy; |
|
| 796 | |||
| 797 | // Sort by ID if the sorting columns are equal |
||
| 810 | |||
| 811 | /** |
||
| 812 | * Generates the pagination instructions for the query |
||
| 813 | * @return string |
||
| 814 | */ |
||
| 815 | 1 | private function createQueryPagination() |
|
| 840 | } |
||
| 841 |
This check marks private properties in classes that are never used. Those properties can be removed.