Newer
Older
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
99
<?php
namespace Mail\Mjml\Mjml\Process;
use Mail\Mjml\Exception\ProcessException;
/**
* Подготовка и запуск рендера шаблона
*/
class Process
{
private $sCommand;
private $sInput;
private $sOutput;
private $sErrorMessage = '';
public const STDIN = 0;
public const STDOUT = 1;
public const STDERR = 2;
private static $aDescriptors = [
self::STDIN => ['pipe', 'r'],
self::STDOUT => ['pipe', 'w'],
self::STDERR => ['pipe', 'w']
];
public function __construct(string $command, string $input)
{
$this->sCommand = $command;
$this->sInput = $input;
}
/**
* @throws ProcessException
*/
public function run(): void
{
$this->initialize();
$pipes = [];
$process = $this->createProcess($pipes);
$this->setInput($pipes);
$this->setOutput($pipes);
$this->setErrorMessage($pipes);
if (0 !== proc_close($process)) {
throw new ProcessException($this->sErrorMessage);
}
}
public function getOutput()
{
return $this->sOutput;
}
private function initialize(): void
{
$this->sOutput = null;
$this->sErrorMessage = '';
}
/**
* @return resource
*
* @throws ProcessException
*/
private function createProcess(array &$pipes)
{
$process = proc_open($this->sCommand, self::$aDescriptors, $pipes);
if (!is_resource($process)) {
throw new ProcessException('Unable to create a process.');
}
return $process;
}
private function setInput(array $pipes): void
{
$stdin = $pipes[self::STDIN];
fwrite($stdin, $this->sInput);
fclose($stdin);
}
private function setOutput(array $pipes): void
{
$stdout = $pipes[self::STDOUT];
$this->sOutput = stream_get_contents($stdout);
fclose($stdout);
}
private function setErrorMessage(array $pipes): void
{
$stderr = $pipes[self::STDERR];
$this->sErrorMessage = stream_get_contents($stderr);
fclose($stderr);
}
}