1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Overwatch\ServiceBundle\Expectation; |
4
|
|
|
|
5
|
|
|
use Overwatch\ExpectationBundle\Exception as Result; |
6
|
|
|
use Overwatch\ExpectationBundle\Expectation\ExpectationInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* ToPingExpectation |
10
|
|
|
* Expectation classes are the actual runners of tests. |
11
|
|
|
* This is the runner for the "toPing" expectation. |
12
|
|
|
*/ |
13
|
|
|
class ToPingExpectation implements ExpectationInterface |
14
|
|
|
{ |
15
|
|
|
private $config; |
16
|
|
|
|
17
|
37 |
|
public function __construct($config) |
18
|
|
|
{ |
19
|
37 |
|
$this->config = $config; |
20
|
37 |
|
} |
21
|
|
|
|
22
|
10 |
|
public function run($actual, $expected = null) |
23
|
|
|
{ |
24
|
|
|
// From http://php.net/manual/en/function.socket-create.php#101012 |
25
|
10 |
|
$package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost"; |
26
|
10 |
|
$socket = socket_create(AF_INET, SOCK_RAW, 1); |
27
|
|
|
|
28
|
9 |
|
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => floor($this->config['timeout']), 'usec' => (($this->config['timeout'] - floor($this->config['timeout'])) * 1000)]); |
29
|
9 |
|
socket_connect($socket, $actual, null); |
30
|
|
|
|
31
|
9 |
|
$sent = microtime(true); |
32
|
9 |
|
socket_send($socket, $package, strLen($package), 0); |
33
|
|
|
|
34
|
9 |
|
if (socket_read($socket, 255)) { |
35
|
8 |
|
$rtt = microtime(true) - $sent; |
36
|
8 |
|
socket_close($socket); |
37
|
|
|
|
38
|
8 |
|
if ($rtt > $this->config['unsatisfactory']) { |
39
|
3 |
|
throw new Result\ExpectationUnsatisfactoryException("$actual responded in $rtt s, above the unsatisfactory threshold (" . $this->config['unsatisfactory'] . ' s)'); |
|
|
|
|
40
|
|
|
} |
41
|
|
|
|
42
|
7 |
|
return 'Pinged in ' . $rtt . 's'; |
43
|
|
|
} |
44
|
|
|
|
45
|
3 |
|
socket_close($socket); |
46
|
3 |
|
throw new Result\ExpectationFailedException("$actual failed to respond in the timeout threshold (" . $this->config['timeout'] . ' s)'); |
|
|
|
|
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.