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 EavBehavior 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 EavBehavior, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 73 | class EavBehavior extends Behavior |
||
| 74 | { |
||
| 75 | |||
| 76 | /** |
||
| 77 | * Instance of EavToolbox. |
||
| 78 | * |
||
| 79 | * @var \Eav\Model\Behavior\EavToolbox |
||
| 80 | */ |
||
| 81 | protected $_toolbox = null; |
||
| 82 | |||
| 83 | /** |
||
| 84 | * Default configuration. |
||
| 85 | * |
||
| 86 | * @var array |
||
| 87 | */ |
||
| 88 | protected $_defaultConfig = [ |
||
| 89 | 'enabled' => true, |
||
| 90 | 'cache' => false, |
||
| 91 | 'queryScope' => [ |
||
| 92 | 'Eav\\Model\\Behavior\\QueryScope\\SelectScope', |
||
| 93 | 'Eav\\Model\\Behavior\\QueryScope\\WhereScope', |
||
| 94 | 'Eav\\Model\\Behavior\\QueryScope\\OrderScope', |
||
| 95 | ], |
||
| 96 | 'implementedMethods' => [ |
||
| 97 | 'enableEav' => 'enableEav', |
||
| 98 | 'disableEav' => 'disableEav', |
||
| 99 | 'updateEavCache' => 'updateEavCache', |
||
| 100 | 'addColumn' => 'addColumn', |
||
| 101 | 'dropColumn' => 'dropColumn', |
||
| 102 | 'listColumns' => 'listColumns', |
||
| 103 | ], |
||
| 104 | ]; |
||
| 105 | |||
| 106 | /** |
||
| 107 | * Query scopes objects to be applied indexed by unique ID. |
||
| 108 | * |
||
| 109 | * @var array |
||
| 110 | */ |
||
| 111 | protected $_queryScopes = []; |
||
| 112 | |||
| 113 | /** |
||
| 114 | * Constructor. |
||
| 115 | * |
||
| 116 | * @param \Cake\ORM\Table $table The table this behavior is attached to |
||
| 117 | * @param array $config Configuration array for this behavior |
||
| 118 | */ |
||
| 119 | public function __construct(Table $table, array $config = []) |
||
| 120 | { |
||
| 121 | $config['cacheMap'] = false; // private config, prevent user modifications |
||
| 122 | $this->_toolbox = new EavToolbox($table); |
||
| 123 | parent::__construct($table, $config); |
||
| 124 | |||
| 125 | if ($this->config('cache')) { |
||
| 126 | $info = $this->config('cache'); |
||
| 127 | $holders = []; // column => [list of virtual columns] |
||
| 128 | |||
| 129 | if (is_string($info)) { |
||
| 130 | $holders[$info] = ['*']; |
||
| 131 | } elseif (is_array($info)) { |
||
| 132 | foreach ($info as $column => $fields) { |
||
| 133 | if (is_integer($column)) { |
||
| 134 | $holders[$fields] = ['*']; |
||
| 135 | } else { |
||
| 136 | $holders[$column] = ($fields === '*') ? ['*'] : $fields; |
||
| 137 | } |
||
| 138 | } |
||
| 139 | } |
||
| 140 | |||
| 141 | $this->config('cacheMap', $holders); |
||
| 142 | } |
||
| 143 | } |
||
| 144 | |||
| 145 | /** |
||
| 146 | * Enables EAV behavior so virtual columns WILL be fetched from database. |
||
| 147 | * |
||
| 148 | * @return void |
||
| 149 | */ |
||
| 150 | public function enableEav() |
||
| 151 | { |
||
| 152 | $this->config('enabled', true); |
||
| 153 | } |
||
| 154 | |||
| 155 | /** |
||
| 156 | * Disables EAV behavior so virtual columns WLL NOT be fetched from database. |
||
| 157 | * |
||
| 158 | * @return void |
||
| 159 | */ |
||
| 160 | public function disableEav() |
||
| 161 | { |
||
| 162 | $this->config('enabled', false); |
||
| 163 | } |
||
| 164 | |||
| 165 | /** |
||
| 166 | * Defines a new virtual-column, or update if already defined. |
||
| 167 | * |
||
| 168 | * ### Usage: |
||
| 169 | * |
||
| 170 | * ```php |
||
| 171 | * $errors = $this->Users->addColumn('user-age', [ |
||
| 172 | * 'type' => 'integer', |
||
| 173 | * 'bundle' => 'some-bundle-name', |
||
| 174 | * 'extra' => [ |
||
| 175 | * 'option1' => 'value1' |
||
| 176 | * ] |
||
| 177 | * ], true); |
||
| 178 | * |
||
| 179 | * if (empty($errors)) { |
||
| 180 | * // OK |
||
| 181 | * } else { |
||
| 182 | * // ERROR |
||
| 183 | * debug($errors); |
||
| 184 | * } |
||
| 185 | * ``` |
||
| 186 | * |
||
| 187 | * The third argument can be set to FALSE to get a boolean response: |
||
| 188 | * |
||
| 189 | * ```php |
||
| 190 | * $success = $this->Users->addColumn('user-age', [ |
||
| 191 | * 'type' => 'integer', |
||
| 192 | * 'bundle' => 'some-bundle-name', |
||
| 193 | * 'extra' => [ |
||
| 194 | * 'option1' => 'value1' |
||
| 195 | * ] |
||
| 196 | * ]); |
||
| 197 | * |
||
| 198 | * if ($success) { |
||
| 199 | * // OK |
||
| 200 | * } else { |
||
| 201 | * // ERROR |
||
| 202 | * } |
||
| 203 | * ``` |
||
| 204 | * |
||
| 205 | * @param string $name Column name. e.g. `user-age` |
||
| 206 | * @param array $options Column configuration options |
||
| 207 | * @param bool $errors If set to true will return an array list of errors |
||
| 208 | * instead of boolean response. Defaults to TRUE |
||
| 209 | * @return bool|array True on success or array of error messages, depending on |
||
| 210 | * $error argument |
||
| 211 | * @throws \Cake\Error\FatalErrorException When provided column name collides |
||
| 212 | * with existing column names. And when an invalid type is provided |
||
| 213 | */ |
||
| 214 | public function addColumn($name, array $options = [], $errors = true) |
||
| 215 | { |
||
| 216 | if (in_array($name, (array)$this->_table->schema()->columns())) { |
||
| 217 | throw new FatalErrorException(__d('eav', 'The column name "{0}" cannot be used as it is already defined in the table "{1}"', $name, $this->_table->alias())); |
||
| 218 | } |
||
| 219 | |||
| 220 | $data = $options + [ |
||
| 221 | 'type' => 'string', |
||
| 222 | 'bundle' => null, |
||
| 223 | 'searchable' => true, |
||
| 224 | ]; |
||
| 225 | |||
| 226 | $data['type'] = $this->_toolbox->mapType($data['type']); |
||
| 227 | if (!in_array($data['type'], EavToolbox::$types)) { |
||
| 228 | throw new FatalErrorException(__d('eav', 'The column {0}({1}) could not be created as "{2}" is not a valid type.', $name, $data['type'], $data['type'])); |
||
| 229 | } |
||
| 230 | |||
| 231 | $data['name'] = $name; |
||
| 232 | $data['table_alias'] = $this->_table->table(); |
||
| 233 | $attr = TableRegistry::get('Eav.EavAttributes')->find() |
||
| 234 | ->where([ |
||
| 235 | 'name' => $data['name'], |
||
| 236 | 'table_alias' => $data['table_alias'], |
||
| 237 | 'bundle IS' => $data['bundle'], |
||
| 238 | ]) |
||
| 239 | ->limit(1) |
||
| 240 | ->first(); |
||
| 241 | |||
| 242 | if ($attr) { |
||
| 243 | $attr = TableRegistry::get('Eav.EavAttributes')->patchEntity($attr, $data); |
||
| 244 | } else { |
||
| 245 | $attr = TableRegistry::get('Eav.EavAttributes')->newEntity($data); |
||
| 246 | } |
||
| 247 | |||
| 248 | $success = (bool)TableRegistry::get('Eav.EavAttributes')->save($attr); |
||
| 249 | Cache::clear(false, 'eav_table_attrs'); |
||
| 250 | |||
| 251 | if ($errors) { |
||
| 252 | return (array)$attr->errors(); |
||
| 253 | } |
||
| 254 | |||
| 255 | return (bool)$success; |
||
| 256 | } |
||
| 257 | |||
| 258 | /** |
||
| 259 | * Drops an existing column. |
||
| 260 | * |
||
| 261 | * @param string $name Name of the column to drop |
||
| 262 | * @param string|null $bundle Removes the column within a particular bundle |
||
| 263 | * @return bool True on success, false otherwise |
||
| 264 | */ |
||
| 265 | public function dropColumn($name, $bundle = null) |
||
| 266 | { |
||
| 267 | $attr = TableRegistry::get('Eav.EavAttributes')->find() |
||
| 268 | ->where([ |
||
| 269 | 'name' => $name, |
||
| 270 | 'table_alias' => $this->_table->table(), |
||
| 271 | 'bundle IS' => $bundle, |
||
| 272 | ]) |
||
| 273 | ->limit(1) |
||
| 274 | ->first(); |
||
| 275 | |||
| 276 | Cache::clear(false, 'eav_table_attrs'); |
||
| 277 | if ($attr) { |
||
| 278 | return (bool)TableRegistry::get('Eav.EavAttributes')->delete($attr); |
||
| 279 | } |
||
| 280 | |||
| 281 | return false; |
||
| 282 | } |
||
| 283 | |||
| 284 | /** |
||
| 285 | * Gets a list of virtual columns attached to this table. |
||
| 286 | * |
||
| 287 | * @param string|null $bundle Get attributes within given bundle, or all of them |
||
| 288 | * regardless of the bundle if not provided |
||
| 289 | * @return array Columns information indexed by column name |
||
| 290 | */ |
||
| 291 | public function listColumns($bundle = null) |
||
| 292 | { |
||
| 293 | $columns = []; |
||
| 294 | foreach ($this->_toolbox->attributes($bundle) as $name => $attr) { |
||
| 295 | $columns[$name] = [ |
||
| 296 | 'id' => $attr->get('id'), |
||
| 297 | 'bundle' => $attr->get('bundle'), |
||
| 298 | 'name' => $name, |
||
| 299 | 'type' => $attr->get('type'), |
||
| 300 | 'searchable ' => $attr->get('searchable'), |
||
| 301 | 'extra ' => $attr->get('extra'), |
||
| 302 | ]; |
||
| 303 | } |
||
| 304 | |||
| 305 | return $columns; |
||
| 306 | } |
||
| 307 | |||
| 308 | /** |
||
| 309 | * Update EAV cache for the specified $entity. |
||
| 310 | * |
||
| 311 | * @return bool Success |
||
| 312 | */ |
||
| 313 | public function updateEavCache(EntityInterface $entity) |
||
| 377 | |||
| 378 | /** |
||
| 379 | * Attaches virtual properties to entities. |
||
| 380 | * |
||
| 381 | * This method iterates over each retrieved entity and invokes the |
||
| 382 | * `attachEntityAttributes()` method. This method should return the altered |
||
| 383 | * entity object with its virtual properties, however if this method returns |
||
| 384 | * NULL the entity will be removed from the resulting collection. And if this |
||
| 385 | * method returns FALSE will stop the find() operation. |
||
| 386 | * |
||
| 387 | * This method is also responsible of looking for virtual columns in SELECT and |
||
| 388 | * WHERE clauses (if applicable) and properly scope the Query object. Query |
||
| 389 | * scoping is performed by the `_scopeQuery()` method. |
||
| 390 | * |
||
| 391 | * @param \Cake\Event\Event $event The beforeFind event that was triggered |
||
| 392 | * @param \Cake\ORM\Query $query The original query to modify |
||
| 393 | * @param \ArrayObject $options Additional options given as an array |
||
| 394 | * @param bool $primary Whether this find is a primary query or not |
||
| 395 | * @return bool|null |
||
| 396 | */ |
||
| 397 | public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary) |
||
| 398 | { |
||
| 399 | View Code Duplication | if (!$this->config('enabled') || |
|
| 400 | (isset($options['eav']) && $options['eav'] === false) |
||
| 401 | ) { |
||
| 402 | return true; |
||
| 403 | } |
||
| 404 | |||
| 405 | if (!isset($options['bundle'])) { |
||
| 406 | $options['bundle'] = null; |
||
| 407 | } |
||
| 408 | |||
| 409 | $query = $this->_scopeQuery($query, $options['bundle']); |
||
| 410 | |||
| 411 | return $query->formatResults(function ($results) use ($event, $query, $options, $primary) { |
||
| 412 | return $this->hydrateEntities($results, compact('event', 'query', 'options', 'primary')); |
||
| 413 | }); |
||
| 414 | } |
||
| 415 | |||
| 416 | /** |
||
| 417 | * Triggered before data is converted into entities. |
||
| 418 | * |
||
| 419 | * Converts incoming POST data to its corresponding types. |
||
| 420 | * |
||
| 421 | * @param \Cake\Event\Event $event The event that was triggered |
||
| 422 | * @param \ArrayObject $data The POST data to be merged with entity |
||
| 423 | * @param \ArrayObject $options The options passed to the marshaller |
||
| 424 | * @return void |
||
| 425 | */ |
||
| 426 | public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options) |
||
| 439 | |||
| 440 | /** |
||
| 441 | * After an entity is saved. |
||
| 442 | * |
||
| 443 | * @param \Cake\Event\Event $event The event that was triggered |
||
| 444 | * @param \Cake\Datasource\EntityInterface $entity The entity that was saved |
||
| 445 | * @param \ArrayObject $options Additional options given as an array |
||
| 446 | * @return bool True always |
||
| 447 | */ |
||
| 448 | public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options) |
||
| 449 | { |
||
| 450 | $attrsById = []; |
||
| 451 | $updatedAttrs = []; |
||
| 452 | $valuesTable = TableRegistry::get('Eav.EavValues'); |
||
| 453 | |||
| 454 | foreach ($this->_toolbox->attributes() as $name => $attr) { |
||
| 455 | if (!$this->_toolbox->propertyExists($entity, $name)) { |
||
|
|
|||
| 456 | continue; |
||
| 457 | } |
||
| 458 | $attrsById[$attr->get('id')] = $attr; |
||
| 459 | } |
||
| 460 | |||
| 461 | if (empty($attrsById)) { |
||
| 462 | return true; // nothing to do |
||
| 463 | } |
||
| 464 | |||
| 465 | $values = $valuesTable |
||
| 466 | ->find() |
||
| 467 | ->where([ |
||
| 468 | 'eav_attribute_id IN' => array_keys($attrsById), |
||
| 469 | 'entity_id' => $this->_toolbox->getEntityId($entity), |
||
| 470 | ]); |
||
| 471 | |||
| 472 | foreach ($values as $value) { |
||
| 473 | $updatedAttrs[] = $value->get('eav_attribute_id'); |
||
| 474 | $info = $attrsById[$value->get('eav_attribute_id')]; |
||
| 475 | $type = $this->_toolbox->getType($info->get('name')); |
||
| 476 | |||
| 477 | $marshaledValue = $this->_toolbox->marshal($entity->get($info->get('name')), $type); |
||
| 478 | $value->set("value_{$type}", $marshaledValue); |
||
| 479 | $entity->set($info->get('name'), $marshaledValue); |
||
| 480 | $valuesTable->save($value); |
||
| 481 | } |
||
| 482 | |||
| 483 | foreach ($this->_toolbox->attributes() as $name => $attr) { |
||
| 484 | if (!$this->_toolbox->propertyExists($entity, $name)) { |
||
| 485 | continue; |
||
| 486 | } |
||
| 487 | |||
| 488 | if (!in_array($attr->get('id'), $updatedAttrs)) { |
||
| 489 | $type = $this->_toolbox->getType($name); |
||
| 490 | $value = $valuesTable->newEntity([ |
||
| 491 | 'eav_attribute_id' => $attr->get('id'), |
||
| 492 | 'entity_id' => $this->_toolbox->getEntityId($entity), |
||
| 493 | ]); |
||
| 494 | |||
| 495 | $marshaledValue = $this->_toolbox->marshal($entity->get($name), $type); |
||
| 496 | $value->set("value_{$type}", $marshaledValue); |
||
| 497 | $entity->set($name, $marshaledValue); |
||
| 498 | $valuesTable->save($value); |
||
| 499 | } |
||
| 500 | } |
||
| 501 | |||
| 502 | if ($this->config('cacheMap')) { |
||
| 503 | $this->updateEavCache($entity); |
||
| 504 | } |
||
| 505 | |||
| 506 | return true; |
||
| 507 | } |
||
| 508 | |||
| 509 | /** |
||
| 510 | * After an entity was removed from database. Here is when EAV values are |
||
| 511 | * removed from DB. |
||
| 512 | * |
||
| 513 | * @param \Cake\Event\Event $event The event that was triggered |
||
| 514 | * @param \Cake\Datasource\EntityInterface $entity The entity that was deleted |
||
| 515 | * @param \ArrayObject $options Additional options given as an array |
||
| 516 | * @throws \Cake\Error\FatalErrorException When using this behavior in non-atomic mode |
||
| 517 | * @return void |
||
| 518 | */ |
||
| 519 | public function afterDelete(Event $event, EntityInterface $entity, ArrayObject $options) |
||
| 520 | { |
||
| 521 | if (!$options['atomic']) { |
||
| 522 | throw new FatalErrorException(__d('eav', 'Entities in fieldable tables can only be deleted using transactions. Set [atomic = true]')); |
||
| 523 | } |
||
| 524 | |||
| 525 | $valuesToDelete = TableRegistry::get('Eav.EavValues') |
||
| 526 | ->find() |
||
| 527 | ->contain(['EavAttribute']) |
||
| 528 | ->where([ |
||
| 529 | 'EavAttribute.table_alias' => $this->_table->table(), |
||
| 530 | 'EavValues.entity_id' => $this->_toolbox->getEntityId($entity), |
||
| 531 | ]) |
||
| 532 | ->all(); |
||
| 533 | |||
| 534 | foreach ($valuesToDelete as $value) { |
||
| 535 | TableRegistry::get('Eav.EavValues')->delete($value); |
||
| 536 | } |
||
| 537 | } |
||
| 538 | |||
| 539 | /** |
||
| 540 | * Attach EAV attributes for every entity in the provided result-set. |
||
| 541 | * |
||
| 542 | * @param \Cake\Collection\CollectionInterface $entities Set of entities to be |
||
| 543 | * processed |
||
| 544 | * @param array $options Arguments given to `beforeFind()` method, possible keys |
||
| 545 | * are "event", "query", "options", "primary" |
||
| 546 | * @return \Cake\Collection\CollectionInterface New set with altered entities |
||
| 547 | */ |
||
| 548 | public function hydrateEntities(CollectionInterface $entities, array $options) |
||
| 549 | { |
||
| 550 | $values = $this->_prepareSetValues($entities, $options); |
||
| 551 | |||
| 552 | return $entities->map(function ($entity) use ($values, $options) { |
||
| 553 | if ($entity instanceof EntityInterface) { |
||
| 554 | $entity = $this->_prepareCachedColumns($entity); |
||
| 555 | $entityId = $this->_toolbox->getEntityId($entity); |
||
| 556 | |||
| 557 | if (isset($values[$entityId])) { |
||
| 558 | $valuesForEntity = isset($values[$entityId]) ? $values[$entityId] : []; |
||
| 559 | $this->attachEntityAttributes($entity, $valuesForEntity); |
||
| 560 | } |
||
| 561 | |||
| 562 | // force cache-columns to be of the proper type as they might be NULL if |
||
| 563 | // entity has not been updated yet. |
||
| 564 | if ($this->config('cacheMap')) { |
||
| 565 | foreach ($this->config('cacheMap') as $column => $fields) { |
||
| 566 | if ($this->_toolbox->propertyExists($entity, $column) && !($entity->get($column) instanceof Entity)) { |
||
| 567 | $entity->set($column, new Entity); |
||
| 568 | } |
||
| 569 | } |
||
| 570 | } |
||
| 571 | } |
||
| 572 | |||
| 573 | if ($entity === false) { |
||
| 574 | $options['event']->stopPropagation(); |
||
| 575 | |||
| 576 | return; |
||
| 577 | } |
||
| 578 | |||
| 579 | if ($entity === null) { |
||
| 580 | return false; |
||
| 581 | } |
||
| 582 | |||
| 583 | return $entity; |
||
| 584 | }); |
||
| 585 | } |
||
| 586 | |||
| 587 | /** |
||
| 588 | * Retrieves all virtual values of all the entities within the given result-set. |
||
| 589 | * |
||
| 590 | * @param \Cake\Collection\CollectionInterface $entities Set of entities |
||
| 591 | * @param array $options Arguments given to `beforeFind()` method, possible keys |
||
| 592 | * are "event", "query", "options", "primary" |
||
| 593 | * @return array Virtual values indexed by entity ID |
||
| 594 | */ |
||
| 595 | protected function _prepareSetValues(CollectionInterface $entities, array $options) |
||
| 645 | |||
| 646 | /** |
||
| 647 | * Prepares entity's cache-columns (those defined using `cache` option). |
||
| 648 | * |
||
| 649 | * @param \Cake\Datasource\EntityInterface $entity The entity to prepare |
||
| 650 | * @return \Cake\Datasource\EntityInterfa Modified entity |
||
| 651 | */ |
||
| 652 | protected function _prepareCachedColumns(EntityInterface $entity) |
||
| 653 | { |
||
| 654 | if ($this->config('cacheMap')) { |
||
| 655 | foreach ((array)$this->config('cacheMap') as $column => $fields) { |
||
| 669 | |||
| 670 | /** |
||
| 671 | * Look for virtual columns in some query's clauses. |
||
| 672 | * |
||
| 673 | * @param \Cake\ORM\Query $query The query to scope |
||
| 674 | * @param string|null $bundle Consider attributes only for a specific bundle |
||
| 675 | * @return \Cake\ORM\Query The modified query object |
||
| 676 | */ |
||
| 677 | protected function _scopeQuery(Query $query, $bundle = null) |
||
| 688 | |||
| 689 | /** |
||
| 690 | * Initializes the scope objects |
||
| 691 | * |
||
| 692 | * @return void |
||
| 693 | */ |
||
| 694 | protected function _initScopes() |
||
| 709 | } |
||
| 710 |
This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.
Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.