forked from team-telnyx/telnyx-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTelnyxMock.php
98 lines (83 loc) · 2.58 KB
/
TelnyxMock.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace Telnyx;
use \Symfony\Component\Process\Process;
class TelnyxMock
{
protected static $process = null;
protected static $port = -1;
const PATH_SPEC = __DIR__ . '/openapi/spec3.json';
const PATH_FIXTURES = __DIR__ . '/openapi/fixtures3.json';
/**
* Starts a telnyx-mock process with custom OpenAPI spec and fixtures files, if they exist.
*
* @return bool true if a telnyx-mock process was started, false otherwise.
*/
public static function start()
{
if (!file_exists(self::PATH_SPEC)) {
return false;
}
if (!is_null(static::$process) && static::$process->isRunning()) {
echo "telnyx-mock already running on port " . static::$port . "\n";
return true;
}
static::$port = static::findAvailablePort();
echo "Starting telnyx-mock on port " . static::$port . "...\n";
static::$process = new Process(join(' ', [
'telnyx-mock',
'-http-port',
static::$port,
'-spec',
self::PATH_SPEC,
'-fixtures',
self::PATH_FIXTURES,
]));
static::$process->start();
sleep(1);
if (static::$process->isRunning()) {
echo "Started telnyx-mock, PID = " . static::$process->getPid() . "\n";
} else {
die("telnyx-mock terminated early, exit code = " . static::$process->wait());
}
return true;
}
/**
* Stops the telnyx-mock process, if one was started. Otherwise do nothing.
*/
public static function stop()
{
if (is_null(static::$process) || !static::$process->isRunning()) {
return;
}
echo "Stopping telnyx-mock...\n";
static::$process->stop(0, SIGTERM);
static::$process->wait();
static::$process = null;
static::$port = -1;
echo "Stopped telnyx-mock\n";
}
/**
* Returns the port number used by the telnyx-mock process.
*
* @return int the port number used by telnyx-mock, or -1 if no telnyx-mock process was started
*/
public static function getPort()
{
return static::$port;
}
/**
* Finds a random available TCP port.
*
* @return int the port number
*/
private static function findAvailablePort()
{
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, "localhost", 0);
$addr = null;
$port = -1;
socket_getsockname($sock, $addr, $port);
socket_close($sock);
return $port;
}
}