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 |
||
23 | class FixtureContext extends BehatContext |
||
24 | { |
||
25 | protected $context; |
||
26 | |||
27 | /** |
||
28 | * @var \FixtureFactory |
||
29 | */ |
||
30 | protected $fixtureFactory; |
||
31 | |||
32 | /** |
||
33 | * @var String Absolute path where file fixtures are located. |
||
34 | * These will automatically get copied to their location |
||
35 | * declare through the 'Given a file "..."' step defition. |
||
36 | */ |
||
37 | protected $filesPath; |
||
38 | |||
39 | /** |
||
40 | * @var String Tracks all files and folders created from fixtures, for later cleanup. |
||
41 | */ |
||
42 | protected $createdFilesPaths = array(); |
||
43 | |||
44 | /** |
||
45 | * @var array Stores the asset tuples. |
||
46 | */ |
||
47 | protected $createdAssets = array(); |
||
48 | |||
49 | public function __construct(array $parameters) { |
||
50 | $this->context = $parameters; |
||
51 | } |
||
52 | |||
53 | public function getSession($name = null) { |
||
54 | return $this->getMainContext()->getSession($name); |
||
|
|||
55 | } |
||
56 | |||
57 | /** |
||
58 | * @return \FixtureFactory |
||
59 | */ |
||
60 | public function getFixtureFactory() { |
||
61 | if(!$this->fixtureFactory) { |
||
62 | $this->fixtureFactory = \Injector::inst()->create('FixtureFactory', 'FixtureContextFactory'); |
||
63 | } |
||
64 | return $this->fixtureFactory; |
||
65 | } |
||
66 | |||
67 | /** |
||
68 | * @param \FixtureFactory $factory |
||
69 | */ |
||
70 | public function setFixtureFactory(\FixtureFactory $factory) { |
||
71 | $this->fixtureFactory = $factory; |
||
72 | } |
||
73 | |||
74 | /** |
||
75 | * @param String |
||
76 | */ |
||
77 | public function setFilesPath($path) { |
||
78 | $this->filesPath = $path; |
||
79 | } |
||
80 | |||
81 | /** |
||
82 | * @return String |
||
83 | */ |
||
84 | public function getFilesPath() { |
||
85 | return $this->filesPath; |
||
86 | } |
||
87 | |||
88 | /** |
||
89 | * @BeforeScenario @database-defaults |
||
90 | */ |
||
91 | public function beforeDatabaseDefaults(ScenarioEvent $event) { |
||
92 | \SapphireTest::empty_temp_db(); |
||
93 | DB::get_conn()->quiet(); |
||
94 | $dataClasses = \ClassInfo::subclassesFor('SilverStripe\\ORM\\DataObject'); |
||
95 | array_shift($dataClasses); |
||
96 | foreach ($dataClasses as $dataClass) { |
||
97 | \singleton($dataClass)->requireDefaultRecords(); |
||
98 | } |
||
99 | } |
||
100 | |||
101 | /** |
||
102 | * @AfterScenario |
||
103 | */ |
||
104 | public function afterResetDatabase(ScenarioEvent $event) { |
||
105 | \SapphireTest::empty_temp_db(); |
||
106 | } |
||
107 | |||
108 | /** |
||
109 | * @AfterScenario |
||
110 | */ |
||
111 | public function afterResetAssets(ScenarioEvent $event) { |
||
112 | $store = $this->getAssetStore(); |
||
113 | if (is_array($this->createdAssets)) { |
||
114 | foreach ($this->createdAssets as $asset) { |
||
115 | $store->delete($asset['FileFilename'], $asset['FileHash']); |
||
116 | } |
||
117 | } |
||
118 | } |
||
119 | |||
120 | /** |
||
121 | * Example: Given a "page" "Page 1" |
||
122 | * |
||
123 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)"$/ |
||
124 | */ |
||
125 | public function stepCreateRecord($type, $id) { |
||
126 | $class = $this->convertTypeToClass($type); |
||
127 | $fields = $this->prepareFixture($class, $id); |
||
128 | $this->fixtureFactory->createObject($class, $id, $fields); |
||
129 | } |
||
130 | |||
131 | /** |
||
132 | * Example: Given a "page" "Page 1" has the "content" "My content" |
||
133 | * |
||
134 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" has (?:(an|a|the) )"(?<field>.*)" "(?<value>.*)"$/ |
||
135 | */ |
||
136 | public function stepCreateRecordHasField($type, $id, $field, $value) { |
||
137 | $class = $this->convertTypeToClass($type); |
||
138 | $fields = $this->convertFields( |
||
139 | $class, |
||
140 | array($field => $value) |
||
141 | ); |
||
142 | // We should check if this fixture object already exists - if it does, we update it. If not, we create it |
||
143 | View Code Duplication | if($existingFixture = $this->fixtureFactory->get($class, $id)) { |
|
144 | // Merge existing data with new data, and create new object to replace existing object |
||
145 | foreach($fields as $k => $v) { |
||
146 | $existingFixture->$k = $v; |
||
147 | } |
||
148 | $existingFixture->write(); |
||
149 | } else { |
||
150 | $this->fixtureFactory->createObject($class, $id, $fields); |
||
151 | } |
||
152 | } |
||
153 | |||
154 | /** |
||
155 | * Example: Given a "page" "Page 1" with "URL"="page-1" and "Content"="my page 1" |
||
156 | * Example: Given the "page" "Page 1" has "URL"="page-1" and "Content"="my page 1" |
||
157 | * |
||
158 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" (?:(with|has)) (?<data>".*)$/ |
||
159 | */ |
||
160 | public function stepCreateRecordWithData($type, $id, $data) { |
||
161 | $class = $this->convertTypeToClass($type); |
||
162 | preg_match_all( |
||
163 | '/"(?<key>[^"]+)"\s*=\s*"(?<value>[^"]+)"/', |
||
164 | $data, |
||
165 | $matches |
||
166 | ); |
||
167 | $fields = $this->convertFields( |
||
168 | $class, |
||
169 | array_combine($matches['key'], $matches['value']) |
||
170 | ); |
||
171 | $fields = $this->prepareFixture($class, $id, $fields); |
||
172 | // We should check if this fixture object already exists - if it does, we update it. If not, we create it |
||
173 | View Code Duplication | if($existingFixture = $this->fixtureFactory->get($class, $id)) { |
|
174 | // Merge existing data with new data, and create new object to replace existing object |
||
175 | foreach($fields as $k => $v) { |
||
176 | $existingFixture->$k = $v; |
||
177 | } |
||
178 | $existingFixture->write(); |
||
179 | } else { |
||
180 | $this->fixtureFactory->createObject($class, $id, $fields); |
||
181 | } |
||
182 | } |
||
183 | |||
184 | /** |
||
185 | * Example: And the "page" "Page 2" has the following data |
||
186 | * | Content | <blink> | |
||
187 | * | My Property | foo | |
||
188 | * | My Boolean | bar | |
||
189 | * |
||
190 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" has the following data$/ |
||
191 | */ |
||
192 | public function stepCreateRecordWithTable($type, $id, $null, TableNode $fieldsTable) { |
||
193 | $class = $this->convertTypeToClass($type); |
||
194 | // TODO Support more than one record |
||
195 | $fields = $this->convertFields($class, $fieldsTable->getRowsHash()); |
||
196 | $fields = $this->prepareFixture($class, $id, $fields); |
||
197 | |||
198 | // We should check if this fixture object already exists - if it does, we update it. If not, we create it |
||
199 | View Code Duplication | if($existingFixture = $this->fixtureFactory->get($class, $id)) { |
|
200 | // Merge existing data with new data, and create new object to replace existing object |
||
201 | foreach($fields as $k => $v) { |
||
202 | $existingFixture->$k = $v; |
||
203 | } |
||
204 | $existingFixture->write(); |
||
205 | } else { |
||
206 | $this->fixtureFactory->createObject($class, $id, $fields); |
||
207 | } |
||
208 | } |
||
209 | |||
210 | /** |
||
211 | * Example: Given the "page" "Page 1.1" is a child of the "page" "Page1". |
||
212 | * Note that this change is not published by default |
||
213 | * |
||
214 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" is a (?<relation>[^\s]*) of (?:(an|a|the) )"(?<relationType>[^"]+)" "(?<relationId>[^"]+)"/ |
||
215 | */ |
||
216 | public function stepUpdateRecordRelation($type, $id, $relation, $relationType, $relationId) { |
||
217 | $class = $this->convertTypeToClass($type); |
||
218 | |||
219 | $relationClass = $this->convertTypeToClass($relationType); |
||
220 | $relationObj = $this->fixtureFactory->get($relationClass, $relationId); |
||
221 | if(!$relationObj) $relationObj = $this->fixtureFactory->createObject($relationClass, $relationId); |
||
222 | |||
223 | $data = array(); |
||
224 | if($relation == 'child') { |
||
225 | $data['ParentID'] = $relationObj->ID; |
||
226 | } |
||
227 | |||
228 | $obj = $this->fixtureFactory->get($class, $id); |
||
229 | if($obj) { |
||
230 | $obj->update($data); |
||
231 | $obj->write(); |
||
232 | } else { |
||
233 | $obj = $this->fixtureFactory->createObject($class, $id, $data); |
||
234 | } |
||
235 | |||
236 | switch($relation) { |
||
237 | case 'parent': |
||
238 | $relationObj->ParentID = $obj->ID; |
||
239 | $relationObj->write(); |
||
240 | break; |
||
241 | case 'child': |
||
242 | // already written through $data above |
||
243 | break; |
||
244 | default: |
||
245 | throw new \InvalidArgumentException(sprintf( |
||
246 | 'Invalid relation "%s"', $relation |
||
247 | )); |
||
248 | } |
||
249 | } |
||
250 | |||
251 | /** |
||
252 | * Assign a type of object to another type of object. The base object will be created if it does not exist already. |
||
253 | * If the last part of the string (in the "X" relation) is omitted, then the first matching relation will be used. |
||
254 | * |
||
255 | * @example I assign the "TaxonomyTerm" "For customers" to the "Page" "Page1" |
||
256 | * @Given /^I assign (?:(an|a|the) )"(?<type>[^"]+)" "(?<value>[^"]+)" to (?:(an|a|the) )"(?<relationType>[^"]+)" "(?<relationId>[^"]+)"$/ |
||
257 | */ |
||
258 | public function stepIAssignObjToObj($type, $value, $relationType, $relationId) { |
||
261 | |||
262 | /** |
||
263 | * Assign a type of object to another type of object. The base object will be created if it does not exist already. |
||
264 | * If the last part of the string (in the "X" relation) is omitted, then the first matching relation will be used. |
||
265 | * Assumption: one object has relationship (has_one, has_many or many_many ) with the other object |
||
266 | * |
||
267 | * @example I assign the "TaxonomyTerm" "For customers" to the "Page" "Page1" in the "Terms" relation |
||
268 | * @Given /^I assign (?:(an|a|the) )"(?<type>[^"]+)" "(?<value>[^"]+)" to (?:(an|a|the) )"(?<relationType>[^"]+)" "(?<relationId>[^"]+)" in the "(?<relationName>[^"]+)" relation$/ |
||
269 | */ |
||
270 | public function stepIAssignObjToObjInTheRelation($type, $value, $relationType, $relationId, $relationName) { |
||
271 | $class = $this->convertTypeToClass($type); |
||
272 | $relationClass = $this->convertTypeToClass($relationType); |
||
273 | |||
274 | // Check if this fixture object already exists - if not, we create it |
||
275 | $relationObj = $this->fixtureFactory->get($relationClass, $relationId); |
||
318 | |||
319 | /** |
||
320 | * Example: Given the "page" "Page 1" is not published |
||
321 | * |
||
322 | * @Given /^(?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)" is (?<state>[^"]*)$/ |
||
323 | */ |
||
324 | public function stepUpdateRecordState($type, $id, $state) { |
||
356 | |||
357 | /** |
||
358 | * Accepts YAML fixture definitions similar to the ones used in SilverStripe unit testing. |
||
359 | * |
||
360 | * Example: Given there are the following member records: |
||
361 | * member1: |
||
362 | * Email: [email protected] |
||
363 | * member2: |
||
364 | * Email: [email protected] |
||
365 | * |
||
366 | * @Given /^there are the following ([^\s]*) records$/ |
||
367 | */ |
||
368 | public function stepThereAreTheFollowingRecords($dataObject, PyStringNode $string) { |
||
377 | |||
378 | /** |
||
379 | * Example: Given a "member" "Admin" belonging to "Admin Group" |
||
380 | * |
||
381 | * @Given /^(?:(an|a|the) )"member" "(?<id>[^"]+)" belonging to "(?<groupId>[^"]+)"$/ |
||
382 | */ |
||
383 | public function stepCreateMemberWithGroup($id, $groupId) { |
||
390 | |||
391 | /** |
||
392 | * Example: Given a "member" "Admin" belonging to "Admin Group" with "Email"="[email protected]" |
||
393 | * |
||
394 | * @Given /^(?:(an|a|the) )"member" "(?<id>[^"]+)" belonging to "(?<groupId>[^"]+)" with (?<data>.*)$/ |
||
395 | */ |
||
396 | public function stepCreateMemberWithGroupAndData($id, $groupId, $data) { |
||
414 | |||
415 | /** |
||
416 | * Example: Given a "group" "Admin" with permissions "Access to 'Pages' section" and "Access to 'Files' section" |
||
417 | * |
||
418 | * @Given /^(?:(an|a|the) )"group" "(?<id>[^"]+)" (?:(with|has)) permissions (?<permissionStr>.*)$/ |
||
419 | */ |
||
420 | public function stepCreateGroupWithPermissions($id, $permissionStr) { |
||
447 | |||
448 | /** |
||
449 | * Navigates to a record based on its identifier set during fixture creation, |
||
450 | * using its RelativeLink() method to map the record to a URL. |
||
451 | * Example: Given I go to the "page" "My Page" |
||
452 | * |
||
453 | * @Given /^I go to (?:(an|a|the) )"(?<type>[^"]+)" "(?<id>[^"]+)"/ |
||
454 | */ |
||
455 | public function stepGoToNamedRecord($type, $id) { |
||
470 | |||
471 | |||
472 | /** |
||
473 | * Checks that a file or folder exists in the webroot. |
||
474 | * Example: There should be a file "assets/Uploads/test.jpg" |
||
475 | * |
||
476 | * @Then /^there should be a (?<type>(file|folder) )"(?<path>[^"]*)"/ |
||
477 | */ |
||
478 | public function stepThereShouldBeAFileOrFolder($type, $path) { |
||
481 | |||
482 | /** |
||
483 | * Checks that a file exists in the asset store with a given filename and hash |
||
484 | * |
||
485 | * Example: there should be a filename "Uploads/test.jpg" with hash "59de0c841f" |
||
486 | * |
||
487 | * @Then /^there should be a filename "(?<filename>[^"]*)" with hash "(?<hash>[a-fA-Z0-9]+)"/ |
||
488 | */ |
||
489 | public function stepThereShouldBeAFileWithTuple($filename, $hash) { |
||
493 | |||
494 | /** |
||
495 | * Replaces fixture references in values with their respective database IDs, |
||
496 | * with the notation "=><class>.<identifier>". Example: "=>Page.My Page". |
||
497 | * |
||
498 | * @Transform /^([^"]+)$/ |
||
499 | */ |
||
500 | public function lookupFixtureReference($string) { |
||
515 | |||
516 | /** |
||
517 | * @Given /^(?:(an|a|the) )"(?<type>[^"]*)" "(?<id>[^"]*)" was (?<mod>(created|last edited)) "(?<time>[^"]*)"$/ |
||
518 | */ |
||
519 | public function aRecordWasLastEditedRelative($type, $id, $mod, $time) { |
||
544 | |||
545 | /** |
||
546 | * Prepares a fixture for use |
||
547 | * |
||
548 | * @param string $class |
||
549 | * @param string $identifier |
||
550 | * @param array $data |
||
551 | * @return array Prepared $data with additional injected fields |
||
552 | */ |
||
553 | protected function prepareFixture($class, $identifier, $data = array()) { |
||
559 | |||
560 | protected function prepareAsset($class, $identifier, $data = null) { |
||
607 | |||
608 | /** |
||
609 | * |
||
610 | * @return AssetStore |
||
611 | */ |
||
612 | protected function getAssetStore() { |
||
615 | |||
616 | /** |
||
617 | * Converts a natural language class description to an actual class name. |
||
618 | * Respects {@link DataObject::$singular_name} variations. |
||
619 | * Example: "redirector page" -> "RedirectorPage" |
||
620 | * |
||
621 | * @param String |
||
622 | * @return String Class name |
||
623 | */ |
||
624 | protected function convertTypeToClass($type) { |
||
645 | |||
646 | /** |
||
647 | * Updates an object with values, resolving aliases set through |
||
648 | * {@link DataObject->fieldLabels()}. |
||
649 | * |
||
650 | * @param string $class Class name |
||
651 | * @param array $fields Map of field names or aliases to their values. |
||
652 | * @return array Map of actual object properties to their values. |
||
653 | */ |
||
654 | protected function convertFields($class, $fields) { |
||
665 | |||
666 | protected function joinPaths() { |
||
674 | |||
675 | } |
||
676 |
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: