Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 namespace Zumba\Mink\Driver;
|
Chris@0
|
4
|
Chris@0
|
5 use Behat\Mink\Exception\DriverException;
|
Chris@0
|
6
|
Chris@0
|
7 /**
|
Chris@0
|
8 * Class JavascriptTrait
|
Chris@0
|
9 * @package Zumba\Mink\Driver
|
Chris@0
|
10 */
|
Chris@0
|
11 trait JavascriptTrait {
|
Chris@0
|
12
|
Chris@0
|
13 /**
|
Chris@0
|
14 * Executes a script on the browser
|
Chris@0
|
15 * @param string $script
|
Chris@0
|
16 */
|
Chris@0
|
17 public function executeScript($script) {
|
Chris@12
|
18 $this->browser->execute($this->fixSelfExecutingFunction($script));
|
Chris@0
|
19 }
|
Chris@0
|
20
|
Chris@0
|
21 /**
|
Chris@0
|
22 * Evaluates a script and returns the result
|
Chris@0
|
23 * @param string $script
|
Chris@0
|
24 * @return mixed
|
Chris@0
|
25 */
|
Chris@0
|
26 public function evaluateScript($script) {
|
Chris@12
|
27 $script = preg_replace('/^return\s+/', '', $script);
|
Chris@12
|
28
|
Chris@12
|
29 $script = $this->fixSelfExecutingFunction($script);
|
Chris@12
|
30
|
Chris@12
|
31 return $this->browser->evaluate($script);
|
Chris@0
|
32 }
|
Chris@0
|
33
|
Chris@0
|
34 /**
|
Chris@0
|
35 * Waits some time or until JS condition turns true.
|
Chris@0
|
36 *
|
Chris@0
|
37 * @param integer $timeout timeout in milliseconds
|
Chris@0
|
38 * @param string $condition JS condition
|
Chris@0
|
39 * @return boolean
|
Chris@0
|
40 * @throws DriverException When the operation cannot be done
|
Chris@0
|
41 */
|
Chris@0
|
42 public function wait($timeout, $condition) {
|
Chris@0
|
43 $start = microtime(true);
|
Chris@0
|
44 $end = $start + $timeout / 1000.0;
|
Chris@0
|
45 do {
|
Chris@0
|
46 $result = $this->browser->evaluate($condition);
|
Chris@12
|
47 if ($result) {
|
Chris@12
|
48 // No need to wait any longer when the condition is met already.
|
Chris@12
|
49 return TRUE;
|
Chris@12
|
50 }
|
Chris@0
|
51 usleep(100000);
|
Chris@0
|
52 } while (microtime(true) < $end && !$result);
|
Chris@0
|
53
|
Chris@0
|
54 return (bool)$result;
|
Chris@0
|
55 }
|
Chris@0
|
56
|
Chris@12
|
57 /**
|
Chris@12
|
58 * Fixes self-executing functions to allow evaluating them.
|
Chris@12
|
59 *
|
Chris@12
|
60 * The self-executing function must be wrapped in braces to work.
|
Chris@12
|
61 *
|
Chris@12
|
62 * @param string $script
|
Chris@12
|
63 *
|
Chris@12
|
64 * @return string
|
Chris@12
|
65 */
|
Chris@12
|
66 private function fixSelfExecutingFunction($script)
|
Chris@12
|
67 {
|
Chris@12
|
68 if (preg_match('/^function[\s\(]/', $script)) {
|
Chris@12
|
69 $script = preg_replace('/;$/', '', $script);
|
Chris@12
|
70 $script = '(' . $script . ')';
|
Chris@12
|
71 }
|
Chris@12
|
72
|
Chris@12
|
73 return $script;
|
Chris@12
|
74 }
|
Chris@0
|
75 }
|