|
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
|
|
|
* Executes a script on the browser |
|
15
|
|
|
* @param string $script |
|
16
|
|
|
*/ |
|
17
|
|
|
public function executeScript($script) { |
|
18
|
|
|
$this->browser->execute($this->fixSelfExecutingFunction($script)); |
|
|
|
|
|
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Evaluates a script and returns the result |
|
23
|
|
|
* @param string $script |
|
24
|
|
|
* @return mixed |
|
25
|
|
|
*/ |
|
26
|
|
|
public function evaluateScript($script) { |
|
27
|
|
|
$script = preg_replace('/^return\s+/', '', $script); |
|
28
|
|
|
|
|
29
|
|
|
$script = $this->fixSelfExecutingFunction($script); |
|
30
|
|
|
|
|
31
|
|
|
return $this->browser->evaluate($script); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Waits some time or until JS condition turns true. |
|
36
|
|
|
* |
|
37
|
|
|
* @param integer $timeout timeout in milliseconds |
|
38
|
|
|
* @param string $condition JS condition |
|
39
|
|
|
* @return boolean |
|
40
|
|
|
* @throws DriverException When the operation cannot be done |
|
41
|
|
|
*/ |
|
42
|
|
|
public function wait($timeout, $condition) { |
|
43
|
|
|
$start = microtime(true); |
|
44
|
|
|
$end = $start + $timeout / 1000.0; |
|
45
|
|
|
do { |
|
46
|
|
|
$result = $this->browser->evaluate($condition); |
|
47
|
|
|
usleep(100000); |
|
48
|
|
|
} while (microtime(true) < $end && !$result); |
|
49
|
|
|
|
|
50
|
|
|
return (bool)$result; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Fixes self-executing functions to allow evaluating them. |
|
55
|
|
|
* |
|
56
|
|
|
* The self-executing function must be wrapped in braces to work. |
|
57
|
|
|
* |
|
58
|
|
|
* @param string $script |
|
59
|
|
|
* |
|
60
|
|
|
* @return string |
|
61
|
|
|
*/ |
|
62
|
|
|
private function fixSelfExecutingFunction($script) |
|
63
|
|
|
{ |
|
64
|
|
|
if (preg_match('/^function[\s\(]/', $script)) { |
|
65
|
|
|
$script = preg_replace('/;$/', '', $script); |
|
66
|
|
|
$script = '(' . $script . ')'; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
return $script; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
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: