| Total Complexity | 55 | 
| Total Lines | 466 | 
| Duplicated Lines | 0 % | 
| Changes | 0 | ||
Complex classes like ManyManyList 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.
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 ManyManyList, and based on these observations, apply Extract Interface, too.
| 1 | <?php | ||
| 16 | class ManyManyList extends RelationList | ||
| 17 | { | ||
| 18 | |||
| 19 | /** | ||
| 20 | * @var string $joinTable | ||
| 21 | */ | ||
| 22 | protected $joinTable; | ||
| 23 | |||
| 24 | /** | ||
| 25 | * @var string $localKey | ||
| 26 | */ | ||
| 27 | protected $localKey; | ||
| 28 | |||
| 29 | /** | ||
| 30 | * @var string $foreignKey | ||
| 31 | */ | ||
| 32 | protected $foreignKey; | ||
| 33 | |||
| 34 | /** | ||
| 35 | * @var array $extraFields | ||
| 36 | */ | ||
| 37 | protected $extraFields; | ||
| 38 | |||
| 39 | /** | ||
| 40 | * @var array $_compositeExtraFields | ||
| 41 | */ | ||
| 42 | protected $_compositeExtraFields = array(); | ||
| 43 | |||
| 44 | /** | ||
| 45 | * Create a new ManyManyList object. | ||
| 46 | * | ||
| 47 |      * A ManyManyList object represents a list of {@link DataObject} records | ||
| 48 | * that correspond to a many-many relationship. | ||
| 49 | * | ||
| 50 | * Generation of the appropriate record set is left up to the caller, using | ||
| 51 |      * the normal {@link DataList} methods. Addition arguments are used to | ||
| 52 |      * support {@@link add()} and {@link remove()} methods. | ||
| 53 | * | ||
| 54 | * @param string $dataClass The class of the DataObjects that this will list. | ||
| 55 | * @param string $joinTable The name of the table whose entries define the content of this many_many relation. | ||
| 56 | * @param string $localKey The key in the join table that maps to the dataClass' PK. | ||
| 57 | * @param string $foreignKey The key in the join table that maps to joined class' PK. | ||
| 58 | * @param array $extraFields A map of field => fieldtype of extra fields on the join table. | ||
| 59 | * | ||
| 60 |      * @example new ManyManyList('Group','Group_Members', 'GroupID', 'MemberID'); | ||
| 61 | */ | ||
| 62 | public function __construct($dataClass, $joinTable, $localKey, $foreignKey, $extraFields = array()) | ||
| 63 |     { | ||
| 64 | parent::__construct($dataClass); | ||
| 65 | |||
| 66 | $this->joinTable = $joinTable; | ||
| 67 | $this->localKey = $localKey; | ||
| 68 | $this->foreignKey = $foreignKey; | ||
| 69 | $this->extraFields = $extraFields; | ||
| 70 | |||
| 71 | $this->linkJoinTable(); | ||
| 72 | } | ||
| 73 | |||
| 74 | /** | ||
| 75 | * Setup the join between this dataobject and the necessary mapping table | ||
| 76 | */ | ||
| 77 | protected function linkJoinTable() | ||
| 78 |     { | ||
| 79 | // Join to the many-many join table | ||
| 80 | $dataClassIDColumn = DataObject::getSchema()->sqlColumnForField($this->dataClass(), 'ID'); | ||
| 81 | $this->dataQuery->innerJoin( | ||
| 82 | $this->joinTable, | ||
| 83 |             "\"{$this->joinTable}\".\"{$this->localKey}\" = {$dataClassIDColumn}" | ||
| 84 | ); | ||
| 85 | |||
| 86 | // Add the extra fields to the query | ||
| 87 |         if ($this->extraFields) { | ||
|  | |||
| 88 | $this->appendExtraFieldsToQuery(); | ||
| 89 | } | ||
| 90 | } | ||
| 91 | |||
| 92 | /** | ||
| 93 | * Adds the many_many_extraFields to the select of the underlying | ||
| 94 |      * {@link DataQuery}. | ||
| 95 | * | ||
| 96 | * @return void | ||
| 97 | */ | ||
| 98 | protected function appendExtraFieldsToQuery() | ||
| 99 |     { | ||
| 100 | $finalized = array(); | ||
| 101 | |||
| 102 |         foreach ($this->extraFields as $field => $spec) { | ||
| 103 | $obj = Injector::inst()->create($spec); | ||
| 104 | |||
| 105 |             if ($obj instanceof DBComposite) { | ||
| 106 | $this->_compositeExtraFields[$field] = array(); | ||
| 107 | |||
| 108 | // append the composite field names to the select | ||
| 109 |                 foreach ($obj->compositeDatabaseFields() as $subField => $subSpec) { | ||
| 110 | $col = $field . $subField; | ||
| 111 | $finalized[] = $col; | ||
| 112 | |||
| 113 | // cache | ||
| 114 | $this->_compositeExtraFields[$field][] = $subField; | ||
| 115 | } | ||
| 116 |             } else { | ||
| 117 | $finalized[] = $field; | ||
| 118 | } | ||
| 119 | } | ||
| 120 | |||
| 121 | $this->dataQuery->addSelectFromTable($this->joinTable, $finalized); | ||
| 122 | } | ||
| 123 | |||
| 124 | /** | ||
| 125 | * Create a DataObject from the given SQL row. | ||
| 126 | * | ||
| 127 | * @param array $row | ||
| 128 | * @return DataObject | ||
| 129 | */ | ||
| 130 | public function createDataObject($row) | ||
| 131 |     { | ||
| 132 | // remove any composed fields | ||
| 133 | $add = array(); | ||
| 134 | |||
| 135 |         if ($this->_compositeExtraFields) { | ||
| 136 |             foreach ($this->_compositeExtraFields as $fieldName => $composed) { | ||
| 137 | // convert joined extra fields into their composite field types. | ||
| 138 | $value = array(); | ||
| 139 | |||
| 140 |                 foreach ($composed as $subField) { | ||
| 141 |                     if (isset($row[$fieldName . $subField])) { | ||
| 142 | $value[$subField] = $row[$fieldName . $subField]; | ||
| 143 | |||
| 144 | // don't duplicate data in the record | ||
| 145 | unset($row[$fieldName . $subField]); | ||
| 146 | } | ||
| 147 | } | ||
| 148 | |||
| 149 | $obj = Injector::inst()->create($this->extraFields[$fieldName], $fieldName); | ||
| 150 | $obj->setValue($value, null, false); | ||
| 151 | $add[$fieldName] = $obj; | ||
| 152 | } | ||
| 153 | } | ||
| 154 | |||
| 155 | $dataObject = parent::createDataObject($row); | ||
| 156 | |||
| 157 |         foreach ($add as $fieldName => $obj) { | ||
| 158 | $dataObject->$fieldName = $obj; | ||
| 159 | } | ||
| 160 | |||
| 161 | return $dataObject; | ||
| 162 | } | ||
| 163 | |||
| 164 | /** | ||
| 165 | * Return a filter expression for when getting the contents of the | ||
| 166 | * relationship for some foreign ID | ||
| 167 | * | ||
| 168 | * @param int|null $id | ||
| 169 | * | ||
| 170 | * @return array | ||
| 171 | */ | ||
| 172 | protected function foreignIDFilter($id = null) | ||
| 173 |     { | ||
| 174 |         if ($id === null) { | ||
| 175 | $id = $this->getForeignID(); | ||
| 176 | } | ||
| 177 | |||
| 178 | // Apply relation filter | ||
| 179 |         $key = "\"{$this->joinTable}\".\"{$this->foreignKey}\""; | ||
| 180 |         if (is_array($id)) { | ||
| 181 |             return array("$key IN (" . DB::placeholders($id) . ")"  => $id); | ||
| 182 |         } elseif ($id !== null) { | ||
| 183 | return array($key => $id); | ||
| 184 | } | ||
| 185 | return null; | ||
| 186 | } | ||
| 187 | |||
| 188 | /** | ||
| 189 | * Return a filter expression for the join table when writing to the join table | ||
| 190 | * | ||
| 191 | * When writing (add, remove, removeByID), we need to filter the join table to just the relevant | ||
| 192 | * entries. However some subclasses of ManyManyList (Member_GroupSet) modify foreignIDFilter to | ||
| 193 | * include additional calculated entries, so we need different filters when reading and when writing | ||
| 194 | * | ||
| 195 | * @param array|int|null $id (optional) An ID or an array of IDs - if not provided, will use the current ids | ||
| 196 | * as per getForeignID | ||
| 197 | * @return array Condition In array(SQL => parameters format) | ||
| 198 | */ | ||
| 199 | protected function foreignIDWriteFilter($id = null) | ||
| 202 | } | ||
| 203 | |||
| 204 | /** | ||
| 205 | * Add an item to this many_many relationship | ||
| 206 | * Does so by adding an entry to the joinTable. | ||
| 207 | * | ||
| 208 | * Can also be used to update an already existing joinTable entry: | ||
| 209 | * | ||
| 210 | * $manyManyList->add($recordID,["ExtraField" => "value"]); | ||
| 211 | * | ||
| 212 | * @throws InvalidArgumentException | ||
| 213 | * @throws Exception | ||
| 214 | * | ||
| 215 | * @param DataObject|int $item | ||
| 216 | * @param array $extraFields A map of additional columns to insert into the joinTable. | ||
| 217 | * Column names should be ANSI quoted. | ||
| 218 | * @throws Exception | ||
| 219 | */ | ||
| 220 | public function add($item, $extraFields = array()) | ||
| 221 |     { | ||
| 222 | // Ensure nulls or empty strings are correctly treated as empty arrays | ||
| 223 |         if (empty($extraFields)) { | ||
| 224 | $extraFields = array(); | ||
| 225 | } | ||
| 226 | |||
| 227 | // Determine ID of new record | ||
| 228 | $itemID = null; | ||
| 229 |         if (is_numeric($item)) { | ||
| 230 | $itemID = $item; | ||
| 231 |         } elseif ($item instanceof $this->dataClass) { | ||
| 232 | $itemID = $item->ID; | ||
| 233 |         } else { | ||
| 234 | throw new InvalidArgumentException( | ||
| 235 | "ManyManyList::add() expecting a $this->dataClass object, or ID value" | ||
| 236 | ); | ||
| 237 | } | ||
| 238 |         if (empty($itemID)) { | ||
| 239 |             throw new InvalidArgumentException("ManyManyList::add() doesn't accept unsaved records"); | ||
| 240 | } | ||
| 241 | |||
| 242 | // Validate foreignID | ||
| 243 | $foreignIDs = $this->getForeignID(); | ||
| 244 |         if (empty($foreignIDs)) { | ||
| 245 |             throw new BadMethodCallException("ManyManyList::add() can't be called until a foreign ID is set"); | ||
| 246 | } | ||
| 247 | |||
| 248 | // Apply this item to each given foreign ID record | ||
| 249 |         if (!is_array($foreignIDs)) { | ||
| 250 | $foreignIDs = array($foreignIDs); | ||
| 251 | } | ||
| 252 |         foreach ($foreignIDs as $foreignID) { | ||
| 253 | // Check for existing records for this item | ||
| 254 |             if ($foreignFilter = $this->foreignIDWriteFilter($foreignID)) { | ||
| 255 | // With the current query, simply add the foreign and local conditions | ||
| 256 | // The query can be a bit odd, especially if custom relation classes | ||
| 257 | // don't join expected tables (@see Member_GroupSet for example). | ||
| 258 |                 $query = new SQLSelect("*", "\"{$this->joinTable}\""); | ||
| 259 | $query->addWhere($foreignFilter); | ||
| 260 | $query->addWhere(array( | ||
| 261 |                     "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID | ||
| 262 | )); | ||
| 263 | $hasExisting = ($query->count() > 0); | ||
| 264 |             } else { | ||
| 265 | $hasExisting = false; | ||
| 266 | } | ||
| 267 | |||
| 268 | // Blank manipulation | ||
| 269 | $manipulation = array( | ||
| 270 | $this->joinTable => array( | ||
| 271 | 'command' => $hasExisting ? 'update' : 'insert', | ||
| 272 | 'fields' => array() | ||
| 273 | ) | ||
| 274 | ); | ||
| 275 |             if ($hasExisting) { | ||
| 276 | $manipulation[$this->joinTable]['where'] = array( | ||
| 277 |                     "\"{$this->joinTable}\".\"{$this->foreignKey}\"" => $foreignID, | ||
| 278 |                     "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID | ||
| 279 | ); | ||
| 280 | } | ||
| 281 | |||
| 282 |             if ($extraFields && $this->extraFields) { | ||
| 283 | // Write extra field to manipluation in the same way | ||
| 284 | // that DataObject::prepareManipulationTable writes fields | ||
| 285 |                 foreach ($this->extraFields as $fieldName => $fieldSpec) { | ||
| 286 | // Skip fields without an assignment | ||
| 287 |                     if (array_key_exists($fieldName, $extraFields)) { | ||
| 288 | $fieldObject = Injector::inst()->create($fieldSpec, $fieldName); | ||
| 289 | $fieldObject->setValue($extraFields[$fieldName]); | ||
| 290 | $fieldObject->writeToManipulation($manipulation[$this->joinTable]); | ||
| 291 | } | ||
| 292 | } | ||
| 293 | } | ||
| 294 | |||
| 295 | $manipulation[$this->joinTable]['fields'][$this->localKey] = $itemID; | ||
| 296 | $manipulation[$this->joinTable]['fields'][$this->foreignKey] = $foreignID; | ||
| 297 | |||
| 298 | // Make sure none of our field assignments are arrays | ||
| 299 |             foreach ($manipulation as $tableManipulation) { | ||
| 300 |                 if (!isset($tableManipulation['fields'])) { | ||
| 301 | continue; | ||
| 302 | } | ||
| 303 |                 foreach ($tableManipulation['fields'] as $fieldValue) { | ||
| 304 |                     if (is_array($fieldValue)) { | ||
| 305 | throw new InvalidArgumentException( | ||
| 306 | 'ManyManyList::add: parameterised field assignments are disallowed' | ||
| 307 | ); | ||
| 308 | } | ||
| 309 | } | ||
| 310 | } | ||
| 311 | |||
| 312 | DB::manipulate($manipulation); | ||
| 313 | } | ||
| 314 | } | ||
| 315 | |||
| 316 | /** | ||
| 317 | * Remove the given item from this list. | ||
| 318 | * | ||
| 319 | * Note that for a ManyManyList, the item is never actually deleted, only | ||
| 320 | * the join table is affected. | ||
| 321 | * | ||
| 322 | * @param DataObject $item | ||
| 323 | */ | ||
| 324 | public function remove($item) | ||
| 325 |     { | ||
| 326 |         if (!($item instanceof $this->dataClass)) { | ||
| 327 |             throw new InvalidArgumentException("ManyManyList::remove() expecting a $this->dataClass object"); | ||
| 328 | } | ||
| 329 | |||
| 330 | return $this->removeByID($item->ID); | ||
| 331 | } | ||
| 332 | |||
| 333 | /** | ||
| 334 | * Remove the given item from this list. | ||
| 335 | * | ||
| 336 | * Note that for a ManyManyList, the item is never actually deleted, only | ||
| 337 | * the join table is affected | ||
| 338 | * | ||
| 339 | * @param int $itemID The item ID | ||
| 340 | */ | ||
| 341 | public function removeByID($itemID) | ||
| 342 |     { | ||
| 343 |         if (!is_numeric($itemID)) { | ||
| 344 |             throw new InvalidArgumentException("ManyManyList::removeById() expecting an ID"); | ||
| 345 | } | ||
| 346 | |||
| 347 |         $query = new SQLDelete("\"{$this->joinTable}\""); | ||
| 348 | |||
| 349 |         if ($filter = $this->foreignIDWriteFilter($this->getForeignID())) { | ||
| 350 | $query->setWhere($filter); | ||
| 351 |         } else { | ||
| 352 |             user_error("Can't call ManyManyList::remove() until a foreign ID is set"); | ||
| 353 | } | ||
| 354 | |||
| 355 | $query->addWhere(array( | ||
| 356 |             "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID | ||
| 357 | )); | ||
| 358 | $query->execute(); | ||
| 359 | } | ||
| 360 | |||
| 361 | /** | ||
| 362 | * Remove all items from this many-many join. To remove a subset of items, | ||
| 363 | * filter it first. | ||
| 364 | * | ||
| 365 | * @return void | ||
| 366 | */ | ||
| 367 | public function removeAll() | ||
| 368 |     { | ||
| 369 | |||
| 370 | // Remove the join to the join table to avoid MySQL row locking issues. | ||
| 371 | $query = $this->dataQuery(); | ||
| 372 |         $foreignFilter = $query->getQueryParam('Foreign.Filter'); | ||
| 373 | $query->removeFilterOn($foreignFilter); | ||
| 374 | |||
| 375 | // Select ID column | ||
| 376 | $selectQuery = $query->query(); | ||
| 377 | $dataClassIDColumn = DataObject::getSchema()->sqlColumnForField($this->dataClass(), 'ID'); | ||
| 378 | $selectQuery->setSelect($dataClassIDColumn); | ||
| 379 | |||
| 380 | $from = $selectQuery->getFrom(); | ||
| 381 | unset($from[$this->joinTable]); | ||
| 382 | $selectQuery->setFrom($from); | ||
| 383 | $selectQuery->setOrderBy(); // ORDER BY in subselects breaks MS SQL Server and is not necessary here | ||
| 384 | $selectQuery->setDistinct(false); | ||
| 385 | |||
| 386 | // Use a sub-query as SQLite does not support setting delete targets in | ||
| 387 | // joined queries. | ||
| 388 | $delete = new SQLDelete(); | ||
| 389 |         $delete->setFrom("\"{$this->joinTable}\""); | ||
| 390 | $delete->addWhere($this->foreignIDFilter()); | ||
| 391 | $subSelect = $selectQuery->sql($parameters); | ||
| 392 | $delete->addWhere(array( | ||
| 393 |             "\"{$this->joinTable}\".\"{$this->localKey}\" IN ($subSelect)" => $parameters | ||
| 394 | )); | ||
| 395 | $delete->execute(); | ||
| 396 | } | ||
| 397 | |||
| 398 | /** | ||
| 399 | * Find the extra field data for a single row of the relationship join | ||
| 400 | * table, given the known child ID. | ||
| 401 | * | ||
| 402 | * @param string $componentName The name of the component | ||
| 403 | * @param int $itemID The ID of the child for the relationship | ||
| 404 | * | ||
| 405 | * @return array Map of fieldName => fieldValue | ||
| 406 | */ | ||
| 407 | public function getExtraData($componentName, $itemID) | ||
| 408 |     { | ||
| 409 | $result = array(); | ||
| 410 | |||
| 411 | // Skip if no extrafields or unsaved record | ||
| 412 |         if (empty($this->extraFields) || empty($itemID)) { | ||
| 413 | return $result; | ||
| 414 | } | ||
| 415 | |||
| 416 |         if (!is_numeric($itemID)) { | ||
| 417 |             throw new InvalidArgumentException('ManyManyList::getExtraData() passed a non-numeric child ID'); | ||
| 418 | } | ||
| 419 | |||
| 420 | $cleanExtraFields = array(); | ||
| 421 |         foreach ($this->extraFields as $fieldName => $dbFieldSpec) { | ||
| 422 |             $cleanExtraFields[] = "\"{$fieldName}\""; | ||
| 423 | } | ||
| 424 |         $query = new SQLSelect($cleanExtraFields, "\"{$this->joinTable}\""); | ||
| 425 | $filter = $this->foreignIDWriteFilter($this->getForeignID()); | ||
| 426 |         if ($filter) { | ||
| 427 | $query->setWhere($filter); | ||
| 428 |         } else { | ||
| 429 |             throw new BadMethodCallException("Can't call ManyManyList::getExtraData() until a foreign ID is set"); | ||
| 430 | } | ||
| 431 | $query->addWhere(array( | ||
| 432 |             "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID | ||
| 433 | )); | ||
| 434 | $queryResult = $query->execute()->current(); | ||
| 435 |         if ($queryResult) { | ||
| 436 |             foreach ($queryResult as $fieldName => $value) { | ||
| 437 | $result[$fieldName] = $value; | ||
| 438 | } | ||
| 439 | } | ||
| 440 | |||
| 441 | return $result; | ||
| 442 | } | ||
| 443 | |||
| 444 | /** | ||
| 445 | * Gets the join table used for the relationship. | ||
| 446 | * | ||
| 447 | * @return string the name of the table | ||
| 448 | */ | ||
| 449 | public function getJoinTable() | ||
| 450 |     { | ||
| 451 | return $this->joinTable; | ||
| 452 | } | ||
| 453 | |||
| 454 | /** | ||
| 455 | * Gets the key used to store the ID of the local/parent object. | ||
| 456 | * | ||
| 457 | * @return string the field name | ||
| 458 | */ | ||
| 459 | public function getLocalKey() | ||
| 462 | } | ||
| 463 | |||
| 464 | /** | ||
| 465 | * Gets the key used to store the ID of the foreign/child object. | ||
| 466 | * | ||
| 467 | * @return string the field name | ||
| 468 | */ | ||
| 469 | public function getForeignKey() | ||
| 472 | } | ||
| 473 | |||
| 474 | /** | ||
| 475 | * Gets the extra fields included in the relationship. | ||
| 476 | * | ||
| 477 | * @return array a map of field names to types | ||
| 478 | */ | ||
| 479 | public function getExtraFields() | ||
| 482 | } | ||
| 483 | } | ||
| 484 | 
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.