| Total Complexity | 57 |
| Total Lines | 472 |
| 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 | /** @var DBField[] $fieldObjects */ |
||
| 283 | $fieldObjects = []; |
||
| 284 | if ($extraFields && $this->extraFields) { |
||
| 285 | // Write extra field to manipluation in the same way |
||
| 286 | // that DataObject::prepareManipulationTable writes fields |
||
| 287 | foreach ($this->extraFields as $fieldName => $fieldSpec) { |
||
| 288 | // Skip fields without an assignment |
||
| 289 | if (array_key_exists($fieldName, $extraFields)) { |
||
| 290 | $fieldObject = Injector::inst()->create($fieldSpec, $fieldName); |
||
| 291 | $fieldObject->setValue($extraFields[$fieldName]); |
||
| 292 | $fieldObject->writeToManipulation($manipulation[$this->joinTable]); |
||
| 293 | $fieldObjects[$fieldName] = $fieldObject; |
||
| 294 | } |
||
| 295 | } |
||
| 296 | } |
||
| 297 | |||
| 298 | $manipulation[$this->joinTable]['fields'][$this->localKey] = $itemID; |
||
| 299 | $manipulation[$this->joinTable]['fields'][$this->foreignKey] = $foreignID; |
||
| 300 | |||
| 301 | // Make sure none of our field assignments are arrays |
||
| 302 | foreach ($manipulation as $tableManipulation) { |
||
| 303 | if (!isset($tableManipulation['fields'])) { |
||
| 304 | continue; |
||
| 305 | } |
||
| 306 | foreach ($tableManipulation['fields'] as $fieldName => $fieldValue) { |
||
| 307 | if (is_array($fieldValue)) { |
||
| 308 | // If the field allows non-scalar values we'll let it do dynamic assignments |
||
| 309 | if (isset($fieldObjects[$fieldName]) && $fieldObjects[$fieldName]->scalarValueOnly()) { |
||
| 310 | throw new InvalidArgumentException( |
||
| 311 | 'ManyManyList::add: parameterised field assignments are disallowed' |
||
| 312 | ); |
||
| 313 | } |
||
| 314 | } |
||
| 315 | } |
||
| 316 | } |
||
| 317 | |||
| 318 | DB::manipulate($manipulation); |
||
| 319 | } |
||
| 320 | } |
||
| 321 | |||
| 322 | /** |
||
| 323 | * Remove the given item from this list. |
||
| 324 | * |
||
| 325 | * Note that for a ManyManyList, the item is never actually deleted, only |
||
| 326 | * the join table is affected. |
||
| 327 | * |
||
| 328 | * @param DataObject $item |
||
| 329 | */ |
||
| 330 | public function remove($item) |
||
| 331 | { |
||
| 332 | if (!($item instanceof $this->dataClass)) { |
||
| 333 | throw new InvalidArgumentException("ManyManyList::remove() expecting a $this->dataClass object"); |
||
| 334 | } |
||
| 335 | |||
| 336 | return $this->removeByID($item->ID); |
||
| 337 | } |
||
| 338 | |||
| 339 | /** |
||
| 340 | * Remove the given item from this list. |
||
| 341 | * |
||
| 342 | * Note that for a ManyManyList, the item is never actually deleted, only |
||
| 343 | * the join table is affected |
||
| 344 | * |
||
| 345 | * @param int $itemID The item ID |
||
| 346 | */ |
||
| 347 | public function removeByID($itemID) |
||
| 348 | { |
||
| 349 | if (!is_numeric($itemID)) { |
||
| 350 | throw new InvalidArgumentException("ManyManyList::removeById() expecting an ID"); |
||
| 351 | } |
||
| 352 | |||
| 353 | $query = new SQLDelete("\"{$this->joinTable}\""); |
||
| 354 | |||
| 355 | if ($filter = $this->foreignIDWriteFilter($this->getForeignID())) { |
||
| 356 | $query->setWhere($filter); |
||
| 357 | } else { |
||
| 358 | user_error("Can't call ManyManyList::remove() until a foreign ID is set"); |
||
| 359 | } |
||
| 360 | |||
| 361 | $query->addWhere(array( |
||
| 362 | "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID |
||
| 363 | )); |
||
| 364 | $query->execute(); |
||
| 365 | } |
||
| 366 | |||
| 367 | /** |
||
| 368 | * Remove all items from this many-many join. To remove a subset of items, |
||
| 369 | * filter it first. |
||
| 370 | * |
||
| 371 | * @return void |
||
| 372 | */ |
||
| 373 | public function removeAll() |
||
| 374 | { |
||
| 375 | |||
| 376 | // Remove the join to the join table to avoid MySQL row locking issues. |
||
| 377 | $query = $this->dataQuery(); |
||
| 378 | $foreignFilter = $query->getQueryParam('Foreign.Filter'); |
||
| 379 | $query->removeFilterOn($foreignFilter); |
||
| 380 | |||
| 381 | // Select ID column |
||
| 382 | $selectQuery = $query->query(); |
||
| 383 | $dataClassIDColumn = DataObject::getSchema()->sqlColumnForField($this->dataClass(), 'ID'); |
||
| 384 | $selectQuery->setSelect($dataClassIDColumn); |
||
| 385 | |||
| 386 | $from = $selectQuery->getFrom(); |
||
| 387 | unset($from[$this->joinTable]); |
||
| 388 | $selectQuery->setFrom($from); |
||
| 389 | $selectQuery->setOrderBy(); // ORDER BY in subselects breaks MS SQL Server and is not necessary here |
||
| 390 | $selectQuery->setDistinct(false); |
||
| 391 | |||
| 392 | // Use a sub-query as SQLite does not support setting delete targets in |
||
| 393 | // joined queries. |
||
| 394 | $delete = new SQLDelete(); |
||
| 395 | $delete->setFrom("\"{$this->joinTable}\""); |
||
| 396 | $delete->addWhere($this->foreignIDFilter()); |
||
| 397 | $subSelect = $selectQuery->sql($parameters); |
||
| 398 | $delete->addWhere(array( |
||
| 399 | "\"{$this->joinTable}\".\"{$this->localKey}\" IN ($subSelect)" => $parameters |
||
| 400 | )); |
||
| 401 | $delete->execute(); |
||
| 402 | } |
||
| 403 | |||
| 404 | /** |
||
| 405 | * Find the extra field data for a single row of the relationship join |
||
| 406 | * table, given the known child ID. |
||
| 407 | * |
||
| 408 | * @param string $componentName The name of the component |
||
| 409 | * @param int $itemID The ID of the child for the relationship |
||
| 410 | * |
||
| 411 | * @return array Map of fieldName => fieldValue |
||
| 412 | */ |
||
| 413 | public function getExtraData($componentName, $itemID) |
||
| 414 | { |
||
| 415 | $result = array(); |
||
| 416 | |||
| 417 | // Skip if no extrafields or unsaved record |
||
| 418 | if (empty($this->extraFields) || empty($itemID)) { |
||
| 419 | return $result; |
||
| 420 | } |
||
| 421 | |||
| 422 | if (!is_numeric($itemID)) { |
||
| 423 | throw new InvalidArgumentException('ManyManyList::getExtraData() passed a non-numeric child ID'); |
||
| 424 | } |
||
| 425 | |||
| 426 | $cleanExtraFields = array(); |
||
| 427 | foreach ($this->extraFields as $fieldName => $dbFieldSpec) { |
||
| 428 | $cleanExtraFields[] = "\"{$fieldName}\""; |
||
| 429 | } |
||
| 430 | $query = new SQLSelect($cleanExtraFields, "\"{$this->joinTable}\""); |
||
| 431 | $filter = $this->foreignIDWriteFilter($this->getForeignID()); |
||
| 432 | if ($filter) { |
||
| 433 | $query->setWhere($filter); |
||
| 434 | } else { |
||
| 435 | throw new BadMethodCallException("Can't call ManyManyList::getExtraData() until a foreign ID is set"); |
||
| 436 | } |
||
| 437 | $query->addWhere(array( |
||
| 438 | "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID |
||
| 439 | )); |
||
| 440 | $queryResult = $query->execute()->current(); |
||
| 441 | if ($queryResult) { |
||
| 442 | foreach ($queryResult as $fieldName => $value) { |
||
| 443 | $result[$fieldName] = $value; |
||
| 444 | } |
||
| 445 | } |
||
| 446 | |||
| 447 | return $result; |
||
| 448 | } |
||
| 449 | |||
| 450 | /** |
||
| 451 | * Gets the join table used for the relationship. |
||
| 452 | * |
||
| 453 | * @return string the name of the table |
||
| 454 | */ |
||
| 455 | public function getJoinTable() |
||
| 456 | { |
||
| 457 | return $this->joinTable; |
||
| 458 | } |
||
| 459 | |||
| 460 | /** |
||
| 461 | * Gets the key used to store the ID of the local/parent object. |
||
| 462 | * |
||
| 463 | * @return string the field name |
||
| 464 | */ |
||
| 465 | public function getLocalKey() |
||
| 468 | } |
||
| 469 | |||
| 470 | /** |
||
| 471 | * Gets the key used to store the ID of the foreign/child object. |
||
| 472 | * |
||
| 473 | * @return string the field name |
||
| 474 | */ |
||
| 475 | public function getForeignKey() |
||
| 478 | } |
||
| 479 | |||
| 480 | /** |
||
| 481 | * Gets the extra fields included in the relationship. |
||
| 482 | * |
||
| 483 | * @return array a map of field names to types |
||
| 484 | */ |
||
| 485 | public function getExtraFields() |
||
| 488 | } |
||
| 489 | } |
||
| 490 |
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.