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)); |
|
|
|
|
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
|
|
|
|
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: