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 SilverStripeContext 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 SilverStripeContext, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 28 | class SilverStripeContext extends MinkContext implements SilverStripeAwareContextInterface |
||
| 29 | { |
||
| 30 | protected $databaseName; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * @var Array Partial string match for step names |
||
| 34 | * that are considered to trigger Ajax request in the CMS, |
||
| 35 | * and hence need special timeout handling. |
||
| 36 | * @see \SilverStripe\BehatExtension\Context\BasicContext->handleAjaxBeforeStep(). |
||
| 37 | */ |
||
| 38 | protected $ajaxSteps; |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @var Int Timeout in milliseconds, after which the interface assumes |
||
| 42 | * that an Ajax request has timed out, and continues with assertions. |
||
| 43 | */ |
||
| 44 | protected $ajaxTimeout; |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @var String Relative URL to the SilverStripe admin interface. |
||
| 48 | */ |
||
| 49 | protected $adminUrl; |
||
| 50 | |||
| 51 | /** |
||
| 52 | * @var String Relative URL to the SilverStripe login form. |
||
| 53 | */ |
||
| 54 | protected $loginUrl; |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @var String Relative path to a writeable folder where screenshots can be stored. |
||
| 58 | * If set to NULL, no screenshots will be stored. |
||
| 59 | */ |
||
| 60 | protected $screenshotPath; |
||
| 61 | |||
| 62 | protected $context; |
||
| 63 | |||
| 64 | protected $testSessionEnvironment; |
||
| 65 | |||
| 66 | |||
| 67 | /** |
||
| 68 | * Initializes context. |
||
| 69 | * Every scenario gets it's own context object. |
||
| 70 | * |
||
| 71 | * @param array $parameters context parameters (set them up through behat.yml) |
||
| 72 | */ |
||
| 73 | public function __construct(array $parameters) { |
||
| 78 | |||
| 79 | public function setDatabase($databaseName) { |
||
| 82 | |||
| 83 | public function setAjaxSteps($ajaxSteps) { |
||
| 86 | |||
| 87 | public function getAjaxSteps() { |
||
| 90 | |||
| 91 | public function setAjaxTimeout($ajaxTimeout) { |
||
| 94 | |||
| 95 | public function getAjaxTimeout() { |
||
| 98 | |||
| 99 | public function setAdminUrl($adminUrl) { |
||
| 102 | |||
| 103 | public function getAdminUrl() { |
||
| 106 | |||
| 107 | public function setLoginUrl($loginUrl) { |
||
| 110 | |||
| 111 | public function getLoginUrl() { |
||
| 114 | |||
| 115 | public function setScreenshotPath($screenshotPath) { |
||
| 118 | |||
| 119 | public function getScreenshotPath() { |
||
| 122 | |||
| 123 | public function getRegionMap(){ |
||
| 126 | |||
| 127 | public function setRegionMap($regionMap){ |
||
| 130 | |||
| 131 | /** |
||
| 132 | * Returns MinkElement based off region defined in .yml file. |
||
| 133 | * Also supports direct CSS selectors and regions identified by a "data-title" attribute. |
||
| 134 | * When using the "data-title" attribute, ensure not to include double quotes. |
||
| 135 | * |
||
| 136 | * @param String $region Region name or CSS selector |
||
| 137 | * @return MinkElement|null |
||
| 138 | */ |
||
| 139 | public function getRegionObj($region) { |
||
| 181 | |||
| 182 | /** |
||
| 183 | * @BeforeScenario |
||
| 184 | */ |
||
| 185 | public function before(ScenarioEvent $event) { |
||
| 186 | if (!isset($this->databaseName)) { |
||
| 187 | throw new \LogicException( |
||
| 188 | 'Context\'s $databaseName has to be set when implementing SilverStripeAwareContextInterface.' |
||
| 189 | ); |
||
| 190 | } |
||
| 191 | |||
| 192 | $state = $this->getTestSessionState(); |
||
| 193 | $this->testSessionEnvironment->startTestSession($state); |
||
| 194 | |||
| 195 | // Optionally import database |
||
| 196 | if(!empty($state['importDatabasePath'])) { |
||
| 197 | $this->testSessionEnvironment->importDatabase( |
||
| 198 | $state['importDatabasePath'], |
||
| 199 | !empty($state['requireDefaultRecords']) ? $state['requireDefaultRecords'] : false |
||
| 200 | ); |
||
| 201 | } else if(!empty($state['requireDefaultRecords']) && $state['requireDefaultRecords']) { |
||
| 202 | $this->testSessionEnvironment->requireDefaultRecords(); |
||
| 203 | } |
||
| 204 | |||
| 205 | // Fixtures |
||
| 206 | $fixtureFile = (!empty($state['fixture'])) ? $state['fixture'] : null; |
||
| 207 | if($fixtureFile) { |
||
| 208 | $this->testSessionEnvironment->loadFixtureIntoDb($fixtureFile); |
||
| 209 | } |
||
| 210 | |||
| 211 | if($screenSize = getenv('BEHAT_SCREEN_SIZE')) { |
||
| 212 | list($screenWidth, $screenHeight) = explode('x', $screenSize); |
||
| 213 | $this->getSession()->resizeWindow((int)$screenWidth, (int)$screenHeight); |
||
| 214 | } else { |
||
| 215 | $this->getSession()->resizeWindow(1024, 768); |
||
| 216 | } |
||
| 217 | } |
||
| 218 | |||
| 219 | /** |
||
| 220 | * Returns a parameter map of state to set within the test session. |
||
| 221 | * Takes TESTSESSION_PARAMS environment variable into account for run-specific configurations. |
||
| 222 | * |
||
| 223 | * @return array |
||
| 224 | */ |
||
| 225 | public function getTestSessionState() { |
||
| 236 | |||
| 237 | /** |
||
| 238 | * Parses given URL and returns its components |
||
| 239 | * |
||
| 240 | * @param $url |
||
| 241 | * @return array|mixed Parsed URL |
||
| 242 | */ |
||
| 243 | public function parseUrl($url) { |
||
| 255 | |||
| 256 | /** |
||
| 257 | * Checks whether current URL is close enough to the given URL. |
||
| 258 | * Unless specified in $url, get vars will be ignored |
||
| 259 | * Unless specified in $url, fragment identifiers will be ignored |
||
| 260 | * |
||
| 261 | * @param $url string URL to compare to current URL |
||
| 262 | * @return boolean Returns true if the current URL is close enough to the given URL, false otherwise. |
||
| 263 | */ |
||
| 264 | public function isCurrentUrlSimilarTo($url) { |
||
| 284 | |||
| 285 | /** |
||
| 286 | * Returns base URL parameter set in MinkExtension. |
||
| 287 | * It simplifies configuration by allowing to specify this parameter |
||
| 288 | * once but makes code dependent on MinkExtension. |
||
| 289 | * |
||
| 290 | * @return string |
||
| 291 | */ |
||
| 292 | public function getBaseUrl() { |
||
| 295 | |||
| 296 | /** |
||
| 297 | * Joins URL parts into an URL using forward slash. |
||
| 298 | * Forward slash usages are normalised to one between parts. |
||
| 299 | * This method takes variable number of parameters. |
||
| 300 | * |
||
| 301 | * @param $... |
||
| 302 | * @return string |
||
| 303 | * @throws \InvalidArgumentException |
||
| 304 | */ |
||
| 305 | public function joinUrlParts() { |
||
| 318 | |||
| 319 | public function canIntercept() { |
||
| 333 | |||
| 334 | /** |
||
| 335 | * @Given /^(.*) without redirection$/ |
||
| 336 | */ |
||
| 337 | public function theRedirectionsAreIntercepted($step) { |
||
| 344 | |||
| 345 | /** |
||
| 346 | * Fills in form field with specified id|name|label|value. |
||
| 347 | * Overwritten to select the first *visible* element, see https://github.com/Behat/Mink/issues/311 |
||
| 348 | */ |
||
| 349 | View Code Duplication | public function fillField($field, $value) { |
|
| 350 | $value = $this->fixStepArgument($value); |
||
| 351 | $fields = $this->getSession()->getPage()->findAll('named', array( |
||
| 352 | 'field', $this->getSession()->getSelectorsHandler()->xpathLiteral($field) |
||
| 353 | )); |
||
| 354 | if($fields) foreach($fields as $f) { |
||
| 355 | if($f->isVisible()) { |
||
| 356 | $f->setValue($value); |
||
| 357 | return; |
||
| 358 | } |
||
| 359 | } |
||
| 360 | |||
| 361 | throw new ElementNotFoundException( |
||
| 362 | $this->getSession(), 'form field', 'id|name|label|value', $field |
||
| 363 | ); |
||
| 364 | } |
||
| 365 | |||
| 366 | /** |
||
| 367 | * Overwritten to click the first *visable* link the DOM. |
||
| 368 | */ |
||
| 369 | View Code Duplication | public function clickLink($link) { |
|
| 384 | |||
| 385 | /** |
||
| 386 | * Sets the current date. Relies on the underlying functionality using |
||
| 387 | * {@link SS_Datetime::now()} rather than PHP's system time methods like date(). |
||
| 388 | * Supports ISO fomat: Y-m-d |
||
| 389 | * Example: Given the current date is "2009-10-31" |
||
| 390 | * |
||
| 391 | * @Given /^the current date is "([^"]*)"$/ |
||
| 392 | */ |
||
| 393 | View Code Duplication | public function givenTheCurrentDateIs($date) { |
|
| 407 | |||
| 408 | /** |
||
| 409 | * Sets the current time. Relies on the underlying functionality using |
||
| 410 | * {@link \SS_Datetime::now()} rather than PHP's system time methods like date(). |
||
| 411 | * Supports ISO fomat: H:i:s |
||
| 412 | * Example: Given the current time is "20:31:50" |
||
| 413 | * |
||
| 414 | * @Given /^the current time is "([^"]*)"$/ |
||
| 415 | */ |
||
| 416 | View Code Duplication | public function givenTheCurrentTimeIs($time) { |
|
| 430 | |||
| 431 | /** |
||
| 432 | * Selects option in select field with specified id|name|label|value. |
||
| 433 | * |
||
| 434 | * @override /^(?:|I )select "(?P<option>(?:[^"]|\\")*)" from "(?P<select>(?:[^"]|\\")*)"$/ |
||
| 435 | */ |
||
| 436 | public function selectOption($select, $option) { |
||
| 450 | |||
| 451 | /** |
||
| 452 | * Selects option in select field with specified id|name|label|value using javascript |
||
| 453 | * This method uses javascript to allow selection of options that may be |
||
| 454 | * overridden by javascript libraries, and thus hide the element. |
||
| 455 | * |
||
| 456 | * @When /^(?:|I )select "(?P<option>(?:[^"]|\\")*)" from "(?P<select>(?:[^"]|\\")*)" with javascript$/ |
||
| 457 | */ |
||
| 458 | public function selectOptionWithJavascript($select, $option) { |
||
| 500 | |||
| 501 | |||
| 502 | /** |
||
| 503 | * @Override "When /^(?:|I )go to "(?P<page>[^"]+)"$/" |
||
| 504 | * We override this function to detect issues with .htaccess external redirects. |
||
| 505 | * |
||
| 506 | * For instance, if the behat test is being run with a base_url which includes a |
||
| 507 | * path, e.g. "http://localhost/behat-test-abc123/", .htaccess redirects may take the browser |
||
| 508 | * to the wrong base path, e.g. "http://localhost/", which will then probably generate |
||
| 509 | * a apache 404 response, which is pretty standard and we can detect it and give a better |
||
| 510 | * error message. |
||
| 511 | */ |
||
| 512 | public function visit($page){ |
||
| 521 | |||
| 522 | } |
||
| 523 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: