Completed
Pull Request — master (#50)
by Juan Francisco
02:32
created

JavascriptTrait::fixJavascriptForUse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 13
rs 9.4286
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
3
namespace Zumba\Mink\Driver;
4
5
use Behat\Mink\Exception\DriverException;
6
7
/**
8
 * Class JavascriptTrait
9
 * @package Zumba\Mink\Driver
10
 */
11
trait JavascriptTrait {
12
13
  /**
14
   * Helper function to fix javascript code before sending it to the phantomjs API
15
   * @param $script
16
   * @return string
17
   */
18
  protected function fixJavascriptForUse($script){
19
    //Fix self returning piece of code;
20
    $scriptToUse = trim($script);
21
    $returningRegexp = "#^return(.+)#is";
22
    $selfFunctionRegexp = '#^function[\s\(]#is';
23
    if (preg_match($returningRegexp, $scriptToUse, $scriptMatch) === 1) {
24
      $scriptToUse = trim($scriptMatch[1]);
25
    } elseif (preg_match($selfFunctionRegexp, $scriptToUse, $scriptMatch) === 1) {
26
      //Fix self function without proper encapsulation to anonymous javascript functions
27
      $scriptToUse = sprintf("(%s)", preg_replace("#;$#", '', $scriptToUse));
28
    }
29
    return $scriptToUse;
30
  }
31
32
  /**
33
   * Executes a script on the browser
34
   * @param string $script
35
   */
36
  public function executeScript($script) {
37
    $this->browser->execute($this->fixJavascriptForUse($script));
0 ignored issues
show
Bug introduced by
The property browser does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
38
  }
39
40
  /**
41
   * Evaluates a script and returns the result
42
   * @param string $script
43
   * @return mixed
44
   */
45
  public function evaluateScript($script) {
46
    return $this->browser->evaluate($this->fixJavascriptForUse($script));
47
  }
48
49
  /**
50
   * Waits some time or until JS condition turns true.
51
   *
52
   * @param integer $timeout timeout in milliseconds
53
   * @param string  $condition JS condition
54
   * @return boolean
55
   * @throws DriverException                  When the operation cannot be done
56
   */
57
  public function wait($timeout, $condition) {
58
    $start = microtime(true);
59
    $end = $start + $timeout / 1000.0;
60
    do {
61
      $result = $this->browser->evaluate($condition);
62
      usleep(100000);
63
    } while (microtime(true) < $end && !$result);
64
65
    return (bool)$result;
66
  }
67
68
}
69