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 FixtureContext 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 FixtureContext, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 17 | class FixtureContext extends BehatContext |
||
| 18 | { |
||
| 19 | protected $context; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var \FixtureFactory |
||
| 23 | */ |
||
| 24 | protected $fixtureFactory; |
||
| 25 | |||
| 26 | /** |
||
| 27 | * @var String Absolute path where file fixtures are located. |
||
| 28 | * These will automatically get copied to their location |
||
| 29 | * declare through the 'Given a file "..."' step defition. |
||
| 30 | */ |
||
| 31 | protected $filesPath; |
||
| 32 | |||
| 33 | /** |
||
| 34 | * @var String Tracks all files and folders created from fixtures, for later cleanup. |
||
| 35 | */ |
||
| 36 | protected $createdFilesPaths = array(); |
||
| 37 | |||
| 38 | /** |
||
| 39 | * @var array Stores the asset tuples. |
||
| 40 | */ |
||
| 41 | protected $createdAssets = array(); |
||
| 42 | |||
| 43 | public function __construct(array $parameters) { |
||
| 44 | $this->context = $parameters; |
||
| 45 | } |
||
| 46 | |||
| 47 | public function getSession($name = null) { |
||
| 48 | return $this->getMainContext()->getSession($name); |
||
|
|
|||
| 49 | } |
||
| 50 | |||
| 51 | /** |
||
| 52 | * @return \FixtureFactory |
||
| 53 | */ |
||
| 54 | public function getFixtureFactory() { |
||
| 55 | if(!$this->fixtureFactory) { |
||
| 56 | $this->fixtureFactory = \Injector::inst()->create('FixtureFactory', 'FixtureContextFactory'); |
||
| 57 | } |
||
| 58 | return $this->fixtureFactory; |
||
| 59 | } |
||
| 60 | |||
| 61 | /** |
||
| 62 | * @param \FixtureFactory $factory |
||
| 63 | */ |
||
| 64 | public function setFixtureFactory(\FixtureFactory $factory) { |
||
| 65 | $this->fixtureFactory = $factory; |
||
| 66 | } |
||
| 67 | |||
| 68 | /** |
||
| 69 | * @param String |
||
| 70 | */ |
||
| 71 | public function setFilesPath($path) { |
||
| 72 | $this->filesPath = $path; |
||
| 73 | } |
||
| 74 | |||
| 75 | /** |
||
| 76 | * @return String |
||
| 77 | */ |
||
| 78 | public function getFilesPath() { |
||
| 79 | return $this->filesPath; |
||
| 80 | } |
||
| 81 | |||
| 82 | /** |
||
| 83 | * @BeforeScenario @database-defaults |
||
| 84 | */ |
||
| 85 | public function beforeDatabaseDefaults(ScenarioEvent $event) { |
||
| 86 | \SapphireTest::empty_temp_db(); |
||
| 87 | \DB::getConn()->quiet(); |
||
| 88 | $dataClasses = \ClassInfo::subclassesFor('DataObject'); |
||
| 89 | array_shift($dataClasses); |
||
| 90 | foreach ($dataClasses as $dataClass) { |
||
| 91 | \singleton($dataClass)->requireDefaultRecords(); |
||
| 92 | } |
||
| 93 | } |
||
| 94 | |||
| 95 | /** |
||
| 96 | * @AfterScenario |
||
| 97 | */ |
||
| 98 | public function afterResetDatabase(ScenarioEvent $event) { |
||
| 99 | \SapphireTest::empty_temp_db(); |
||
| 100 | } |
||
| 101 | |||
| 102 | /** |
||
| 103 | * @AfterScenario |
||
| 104 | */ |
||
| 105 | public function afterResetAssets(ScenarioEvent $event) { |
||
| 106 | $store = $this->getAssetStore(); |
||
| 107 | if (is_array($this->createdAssets)) { |
||
| 108 | foreach ($this->createdAssets as $asset) { |
||
| 109 | $store->delete($asset['FileFilename'], $asset['FileHash']); |
||
| 110 | } |
||
| 111 | } |
||
| 112 | } |
||
| 113 | |||
| 114 | /** |
||
| 115 | * Example: Given a "page" "Page 1" |
||
| 116 | * |
||
| 117 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)"$/ |
||
| 118 | */ |
||
| 119 | public function stepCreateRecord($type, $id) { |
||
| 120 | $class = $this->convertTypeToClass($type); |
||
| 121 | $fields = $this->prepareFixture($class, $id); |
||
| 122 | $this->fixtureFactory->createObject($class, $id, $fields); |
||
| 123 | } |
||
| 124 | |||
| 125 | /** |
||
| 126 | * Example: Given a "page" "Page 1" has the "content" "My content" |
||
| 127 | * |
||
| 128 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" has (?:(an|a|the) )"(?<field>.*)" "(?<value>.*)"$/ |
||
| 129 | */ |
||
| 130 | public function stepCreateRecordHasField($type, $id, $field, $value) { |
||
| 131 | $class = $this->convertTypeToClass($type); |
||
| 132 | $fields = $this->convertFields( |
||
| 133 | $class, |
||
| 134 | array($field => $value) |
||
| 135 | ); |
||
| 136 | // We should check if this fixture object already exists - if it does, we update it. If not, we create it |
||
| 137 | View Code Duplication | if($existingFixture = $this->fixtureFactory->get($class, $id)) { |
|
| 138 | // Merge existing data with new data, and create new object to replace existing object |
||
| 139 | foreach($fields as $k => $v) { |
||
| 140 | $existingFixture->$k = $v; |
||
| 141 | } |
||
| 142 | $existingFixture->write(); |
||
| 143 | } else { |
||
| 144 | $this->fixtureFactory->createObject($class, $id, $fields); |
||
| 145 | } |
||
| 146 | } |
||
| 147 | |||
| 148 | /** |
||
| 149 | * Example: Given a "page" "Page 1" with "URL"="page-1" and "Content"="my page 1" |
||
| 150 | * Example: Given the "page" "Page 1" has "URL"="page-1" and "Content"="my page 1" |
||
| 151 | * |
||
| 152 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" (?:(with|has)) (?<data>".*)$/ |
||
| 153 | */ |
||
| 154 | public function stepCreateRecordWithData($type, $id, $data) { |
||
| 155 | $class = $this->convertTypeToClass($type); |
||
| 156 | preg_match_all( |
||
| 157 | '/"(?<key>[^"]+)"\s*=\s*"(?<value>[^"]+)"/', |
||
| 158 | $data, |
||
| 159 | $matches |
||
| 160 | ); |
||
| 161 | $fields = $this->convertFields( |
||
| 162 | $class, |
||
| 163 | array_combine($matches['key'], $matches['value']) |
||
| 164 | ); |
||
| 165 | $fields = $this->prepareFixture($class, $id, $fields); |
||
| 166 | // We should check if this fixture object already exists - if it does, we update it. If not, we create it |
||
| 167 | View Code Duplication | if($existingFixture = $this->fixtureFactory->get($class, $id)) { |
|
| 168 | // Merge existing data with new data, and create new object to replace existing object |
||
| 169 | foreach($fields as $k => $v) { |
||
| 170 | $existingFixture->$k = $v; |
||
| 171 | } |
||
| 172 | $existingFixture->write(); |
||
| 173 | } else { |
||
| 174 | $this->fixtureFactory->createObject($class, $id, $fields); |
||
| 175 | } |
||
| 176 | } |
||
| 177 | |||
| 178 | /** |
||
| 179 | * Example: And the "page" "Page 2" has the following data |
||
| 180 | * | Content | <blink> | |
||
| 181 | * | My Property | foo | |
||
| 182 | * | My Boolean | bar | |
||
| 183 | * |
||
| 184 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" has the following data$/ |
||
| 185 | */ |
||
| 186 | public function stepCreateRecordWithTable($type, $id, $null, TableNode $fieldsTable) { |
||
| 187 | $class = $this->convertTypeToClass($type); |
||
| 188 | // TODO Support more than one record |
||
| 189 | $fields = $this->convertFields($class, $fieldsTable->getRowsHash()); |
||
| 190 | $fields = $this->prepareFixture($class, $id, $fields); |
||
| 191 | |||
| 192 | // We should check if this fixture object already exists - if it does, we update it. If not, we create it |
||
| 193 | View Code Duplication | if($existingFixture = $this->fixtureFactory->get($class, $id)) { |
|
| 194 | // Merge existing data with new data, and create new object to replace existing object |
||
| 195 | foreach($fields as $k => $v) { |
||
| 196 | $existingFixture->$k = $v; |
||
| 197 | } |
||
| 198 | $existingFixture->write(); |
||
| 199 | } else { |
||
| 200 | $this->fixtureFactory->createObject($class, $id, $fields); |
||
| 201 | } |
||
| 202 | } |
||
| 203 | |||
| 204 | /** |
||
| 205 | * Example: Given the "page" "Page 1.1" is a child of the "page" "Page1". |
||
| 206 | * Note that this change is not published by default |
||
| 207 | * |
||
| 208 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" is a (?<relation>[^\s]*) of (?:(an|a|the) )"(?<relationType>[^"]+)" "(?<relationId>[^"]+)"/ |
||
| 209 | */ |
||
| 210 | public function stepUpdateRecordRelation($type, $id, $relation, $relationType, $relationId) { |
||
| 211 | $class = $this->convertTypeToClass($type); |
||
| 212 | |||
| 213 | $relationClass = $this->convertTypeToClass($relationType); |
||
| 214 | $relationObj = $this->fixtureFactory->get($relationClass, $relationId); |
||
| 215 | if(!$relationObj) $relationObj = $this->fixtureFactory->createObject($relationClass, $relationId); |
||
| 216 | |||
| 217 | $data = array(); |
||
| 218 | if($relation == 'child') { |
||
| 219 | $data['ParentID'] = $relationObj->ID; |
||
| 220 | } |
||
| 221 | |||
| 222 | $obj = $this->fixtureFactory->get($class, $id); |
||
| 223 | if($obj) { |
||
| 224 | $obj->update($data); |
||
| 225 | $obj->write(); |
||
| 226 | } else { |
||
| 227 | $obj = $this->fixtureFactory->createObject($class, $id, $data); |
||
| 228 | } |
||
| 229 | |||
| 230 | switch($relation) { |
||
| 231 | case 'parent': |
||
| 232 | $relationObj->ParentID = $obj->ID; |
||
| 233 | $relationObj->write(); |
||
| 234 | break; |
||
| 235 | case 'child': |
||
| 236 | // already written through $data above |
||
| 237 | break; |
||
| 238 | default: |
||
| 239 | throw new \InvalidArgumentException(sprintf( |
||
| 240 | 'Invalid relation "%s"', $relation |
||
| 241 | )); |
||
| 242 | } |
||
| 243 | } |
||
| 244 | |||
| 245 | /** |
||
| 246 | * Assign a type of object to another type of object. The base object will be created if it does not exist already. |
||
| 247 | * If the last part of the string (in the "X" relation) is omitted, then the first matching relation will be used. |
||
| 248 | * |
||
| 249 | * @example I assign the "TaxonomyTerm" "For customers" to the "Page" "Page1" |
||
| 250 | * @Given /^I assign (?:(an|a|the) )"(?<type>[^"]+)" "(?<value>[^"]+)" to (?:(an|a|the) )"(?<relationType>[^"]+)" "(?<relationId>[^"]+)"$/ |
||
| 251 | */ |
||
| 252 | public function stepIAssignObjToObj($type, $value, $relationType, $relationId) { |
||
| 255 | |||
| 256 | /** |
||
| 257 | * Assign a type of object to another type of object. The base object will be created if it does not exist already. |
||
| 258 | * If the last part of the string (in the "X" relation) is omitted, then the first matching relation will be used. |
||
| 259 | * Assumption: one object has relationship (has_one, has_many or many_many ) with the other object |
||
| 260 | * |
||
| 261 | * @example I assign the "TaxonomyTerm" "For customers" to the "Page" "Page1" in the "Terms" relation |
||
| 262 | * @Given /^I assign (?:(an|a|the) )"(?<type>[^"]+)" "(?<value>[^"]+)" to (?:(an|a|the) )"(?<relationType>[^"]+)" "(?<relationId>[^"]+)" in the "(?<relationName>[^"]+)" relation$/ |
||
| 263 | */ |
||
| 264 | public function stepIAssignObjToObjInTheRelation($type, $value, $relationType, $relationId, $relationName) { |
||
| 312 | |||
| 313 | /** |
||
| 314 | * Example: Given the "page" "Page 1" is not published |
||
| 315 | * |
||
| 316 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" is (?<state>[^"]*)$/ |
||
| 317 | */ |
||
| 318 | public function stepUpdateRecordState($type, $id, $state) { |
||
| 319 | $class = $this->convertTypeToClass($type); |
||
| 320 | $obj = $this->fixtureFactory->get($class, $id); |
||
| 321 | if(!$obj) { |
||
| 322 | throw new \InvalidArgumentException(sprintf( |
||
| 323 | 'Can not find record "%s" with identifier "%s"', |
||
| 324 | $type, |
||
| 325 | $id |
||
| 326 | )); |
||
| 327 | } |
||
| 328 | |||
| 329 | switch($state) { |
||
| 330 | case 'published': |
||
| 331 | $obj->publish('Stage', 'Live'); |
||
| 332 | break; |
||
| 333 | case 'not published': |
||
| 334 | case 'unpublished': |
||
| 335 | $oldMode = \Versioned::get_reading_mode(); |
||
| 336 | \Versioned::reading_stage('Live'); |
||
| 337 | $clone = clone $obj; |
||
| 338 | $clone->delete(); |
||
| 339 | \Versioned::reading_stage($oldMode); |
||
| 340 | break; |
||
| 341 | case 'deleted': |
||
| 342 | $obj->delete(); |
||
| 343 | break; |
||
| 344 | default: |
||
| 345 | throw new \InvalidArgumentException(sprintf( |
||
| 346 | 'Invalid state: "%s"', $state |
||
| 347 | )); |
||
| 348 | } |
||
| 349 | } |
||
| 350 | |||
| 351 | /** |
||
| 352 | * Accepts YAML fixture definitions similar to the ones used in SilverStripe unit testing. |
||
| 353 | * |
||
| 354 | * Example: Given there are the following member records: |
||
| 355 | * member1: |
||
| 356 | * Email: [email protected] |
||
| 357 | * member2: |
||
| 358 | * Email: [email protected] |
||
| 359 | * |
||
| 360 | * @Given /^there are the following ([^\s]*) records$/ |
||
| 361 | */ |
||
| 362 | public function stepThereAreTheFollowingRecords($dataObject, PyStringNode $string) { |
||
| 371 | |||
| 372 | /** |
||
| 373 | * Example: Given a "member" "Admin" belonging to "Admin Group" |
||
| 374 | * |
||
| 375 | * @Given /^(?:(an|a|the) )"member" "(?<id>[^"]+)" belonging to "(?<groupId>[^"]+)"$/ |
||
| 376 | */ |
||
| 377 | public function stepCreateMemberWithGroup($id, $groupId) { |
||
| 384 | |||
| 385 | /** |
||
| 386 | * Example: Given a "member" "Admin" belonging to "Admin Group" with "Email"="[email protected]" |
||
| 387 | * |
||
| 388 | * @Given /^(?:(an|a|the) )"member" "(?<id>[^"]+)" belonging to "(?<groupId>[^"]+)" with (?<data>.*)$/ |
||
| 389 | */ |
||
| 390 | public function stepCreateMemberWithGroupAndData($id, $groupId, $data) { |
||
| 408 | |||
| 409 | /** |
||
| 410 | * Example: Given a "group" "Admin" with permissions "Access to 'Pages' section" and "Access to 'Files' section" |
||
| 411 | * |
||
| 412 | * @Given /^(?:(an|a|the) )"group" "(?<id>[^"]+)" (?:(with|has)) permissions (?<permissionStr>.*)$/ |
||
| 413 | */ |
||
| 414 | public function stepCreateGroupWithPermissions($id, $permissionStr) { |
||
| 441 | |||
| 442 | /** |
||
| 443 | * Navigates to a record based on its identifier set during fixture creation, |
||
| 444 | * using its RelativeLink() method to map the record to a URL. |
||
| 445 | * Example: Given I go to the "page" "My Page" |
||
| 446 | * |
||
| 447 | * @Given /^I go to (?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)"/ |
||
| 448 | */ |
||
| 449 | public function stepGoToNamedRecord($type, $id) { |
||
| 464 | |||
| 465 | |||
| 466 | /** |
||
| 467 | * Checks that a file or folder exists in the webroot. |
||
| 468 | * Example: There should be a file "assets/Uploads/test.jpg" |
||
| 469 | * |
||
| 470 | * @Then /^there should be a (?<type>(file|folder) )"(?<path>[^"]*)"/ |
||
| 471 | */ |
||
| 472 | public function stepThereShouldBeAFileOrFolder($type, $path) { |
||
| 473 | assertFileExists($this->joinPaths(BASE_PATH, $path)); |
||
| 474 | } |
||
| 475 | |||
| 476 | /** |
||
| 477 | * Checks that a file exists in the asset store with a given filename and hash |
||
| 478 | * |
||
| 479 | * Example: there should be a filename "Uploads/test.jpg" with hash "59de0c841f" |
||
| 480 | * |
||
| 481 | * @Then /^there should be a filename "(?<filename>[^"]*)" with hash "(?<hash>[a-fA-Z0-9]+)"/ |
||
| 482 | */ |
||
| 483 | public function stepThereShouldBeAFileWithTuple($filename, $hash) { |
||
| 487 | |||
| 488 | /** |
||
| 489 | * Replaces fixture references in values with their respective database IDs, |
||
| 490 | * with the notation "=><class>.<identifier>". Example: "=>Page.My Page". |
||
| 491 | * |
||
| 492 | * @Transform /^([^"]+)$/ |
||
| 493 | */ |
||
| 494 | public function lookupFixtureReference($string) { |
||
| 509 | |||
| 510 | /** |
||
| 511 | * @Given /^(?:(an|a|the) )"(?<type>[^"]*)" "(?<id>[^"]*)" was (?<mod>(created|last edited)) "(?<time>[^"]*)"$/ |
||
| 512 | */ |
||
| 513 | public function aRecordWasLastEditedRelative($type, $id, $mod, $time) { |
||
| 538 | |||
| 539 | /** |
||
| 540 | * Prepares a fixture for use |
||
| 541 | * |
||
| 542 | * @param string $class |
||
| 543 | * @param string $identifier |
||
| 544 | * @param array $data |
||
| 545 | * @return array Prepared $data with additional injected fields |
||
| 546 | */ |
||
| 547 | protected function prepareFixture($class, $identifier, $data = array()) { |
||
| 553 | |||
| 554 | protected function prepareAsset($class, $identifier, $data = null) { |
||
| 601 | |||
| 602 | /** |
||
| 603 | * |
||
| 604 | * @return AssetStore |
||
| 605 | */ |
||
| 606 | protected function getAssetStore() { |
||
| 609 | |||
| 610 | /** |
||
| 611 | * Converts a natural language class description to an actual class name. |
||
| 612 | * Respects {@link DataObject::$singular_name} variations. |
||
| 613 | * Example: "redirector page" -> "RedirectorPage" |
||
| 614 | * |
||
| 615 | * @param String |
||
| 616 | * @return String Class name |
||
| 617 | */ |
||
| 618 | protected function convertTypeToClass($type) { |
||
| 637 | |||
| 638 | /** |
||
| 639 | * Updates an object with values, resolving aliases set through |
||
| 640 | * {@link DataObject->fieldLabels()}. |
||
| 641 | * |
||
| 642 | * @param String Class name |
||
| 643 | * @param Array Map of field names or aliases to their values. |
||
| 644 | * @return Array Map of actual object properties to their values. |
||
| 645 | */ |
||
| 646 | protected function convertFields($class, $fields) { |
||
| 657 | |||
| 658 | protected function joinPaths() { |
||
| 666 | |||
| 667 | } |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: