1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace hanneskod\readmetester\Runner; |
6
|
|
|
|
7
|
|
|
use hanneskod\readmetester\Parser\CodeBlock; |
8
|
|
|
use Symfony\Component\Process\PhpProcess; |
9
|
|
|
use hkod\frontmatter\Parser; |
10
|
|
|
use hkod\frontmatter\JsonParser; |
11
|
|
|
use hkod\frontmatter\VoidParser; |
12
|
|
|
use hkod\frontmatter\InvertedBlockParser; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Execute code in isolation using symfony php-process |
16
|
|
|
*/ |
17
|
|
|
class IsolationRunner implements RunnerInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var Parser |
21
|
|
|
*/ |
22
|
|
|
private $parser; |
23
|
|
|
|
24
|
|
|
public function __construct() |
25
|
|
|
{ |
26
|
|
|
$this->parser = new Parser( |
27
|
|
|
new JsonParser, |
28
|
|
|
new VoidParser, |
29
|
|
|
new InvertedBlockParser |
30
|
|
|
); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @return OutcomeInterface[] |
35
|
|
|
*/ |
36
|
|
|
public function run(CodeBlock $codeBlock): array |
37
|
|
|
{ |
38
|
|
|
$process = new PhpProcess(<<<EOF |
39
|
|
|
<?php |
40
|
|
|
try { |
41
|
|
|
$codeBlock |
42
|
|
|
} catch (Exception \$e) { |
43
|
|
|
echo "---\n"; |
44
|
|
|
echo json_encode([ |
45
|
|
|
'exception' => [ |
46
|
|
|
'class' => get_class(\$e), |
47
|
|
|
'message' => \$e->getMessage(), |
48
|
|
|
'code' => \$e->getCode() |
49
|
|
|
] |
50
|
|
|
]); |
51
|
|
|
echo "\n---\n"; |
52
|
|
|
} |
53
|
|
|
EOF |
54
|
|
|
); |
55
|
|
|
|
56
|
|
|
$process->run(); |
57
|
|
|
$outcomes = []; |
58
|
|
|
|
59
|
|
|
if ($errorOutput = $process->getErrorOutput()) { |
60
|
|
|
$outcomes[] = new ErrorOutcome(trim($errorOutput)); |
61
|
|
|
} elseif ($output = $process->getOutput()) { |
62
|
|
|
$result = $this->parser->parse($output); |
63
|
|
|
|
64
|
|
|
if ($body = $result->getBody()) { |
65
|
|
|
$outcomes[] = new OutputOutcome($body); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if ($exceptionDef = $result->getFrontmatter()['exception'] ?? null) { |
69
|
|
|
$outcomes[] = new ExceptionOutcome( |
70
|
|
|
$exceptionDef['class'], |
71
|
|
|
$exceptionDef['message'], |
72
|
|
|
$exceptionDef['code'] |
73
|
|
|
); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $outcomes; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|