AutocompleteContext::fillInDrupalAutocomplete()   B
last analyzed

Complexity

Conditions 4
Paths 9

Size

Total Lines 37
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
nc 9
nop 2
1
<?php
2
3
namespace NuvoleWeb\Drupal\DrupalExtension\Context;
4
5
use Behat\Mink\Exception\ExpectationException;
6
use Behat\Mink\Exception\UnsupportedDriverActionException;
7
8
/**
9
 * Autocomplete step definitions.
10
 */
11
class AutocompleteContext extends RawMinkContext {
12
13
  /**
14
   * Fill out autocomplete fields based on gist.
15
   *
16
   * @When I fill in the autocomplete :autocomplete with :text
17
   */
18
  public function fillInDrupalAutocomplete($locator, $text) {
19
20
    $session = $this->getSession();
21
    $el = $session->getPage()->findField($locator);
22
23
    if (empty($el)) {
24
      throw new ExpectationException('No such autocomplete element ' . $locator, $session);
25
    }
26
27
    // Set the text and trigger the autocomplete with a space keystroke.
28
    $el->setValue($text);
29
30
    try {
31
      $el->keyDown(' ');
32
      $el->keyUp(' ');
33
34
      // Wait for ajax.
35
      $this->getSession()->wait(1000, '(typeof(jQuery)=="undefined" || (0 === jQuery.active && 0 === jQuery(\':animated\').length))');
36
      // Wait a second, just to be sure.
37
      sleep(1);
38
39
      // Select the autocomplete popup with the name we are looking for.
40
      $popup = $session->getPage()->find('xpath', "//ul[contains(@class, 'ui-autocomplete')]/li/a[text() = '{$text}']");
41
42
      if (empty($popup)) {
43
        throw new ExpectationException('No such option ' . $text . ' in ' . $locator, $session);
44
      }
45
46
      // Clicking on the popup fills the autocomplete properly.
47
      $popup->click();
48
    }
49
    catch (UnsupportedDriverActionException $e) {
50
      // So javascript is not supported.
51
      // We did set the value correctly, so Drupal will figure it out.
52
    }
53
54
  }
55
56
}
57