1
|
|
|
<?php namespace rtens\domin\delivery; |
2
|
|
|
|
3
|
|
|
class DelayedOutput { |
4
|
|
|
|
5
|
|
|
/** @var callable */ |
6
|
|
|
private $runner; |
7
|
|
|
|
8
|
|
|
/** @var callable */ |
9
|
|
|
private $printer; |
10
|
|
|
|
11
|
|
|
/** @var callable */ |
12
|
|
|
private $exceptionHandler; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @param callable $runner Will be called with the object itself, returns void |
16
|
|
|
*/ |
17
|
|
|
public function __construct(callable $runner) { |
18
|
|
|
$this->runner = $runner; |
19
|
|
|
$this->printer = function ($string) { |
20
|
|
|
echo $string; |
21
|
|
|
}; |
22
|
|
|
$this->exceptionHandler = function (\Exception $exception) { |
23
|
|
|
$message = get_class($exception) . ': ' . $exception->getMessage() . ' ' . |
24
|
|
|
'[' . $exception->getFile() . ':' . $exception->getLine() . ']' . "\n" . |
25
|
|
|
$exception->getTraceAsString(); |
26
|
|
|
|
27
|
|
|
$stderr = fopen('php://stderr', 'w'); |
28
|
|
|
fwrite($stderr, $message); |
29
|
|
|
fclose($stderr); |
30
|
|
|
exit(1); |
|
|
|
|
31
|
|
|
}; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
function __toString() { |
|
|
|
|
35
|
|
|
try { |
36
|
|
|
call_user_func($this->runner, $this); |
37
|
|
|
} catch (\Exception $e) { |
38
|
|
|
$this->handleException($e); |
39
|
|
|
} |
40
|
|
|
return ''; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function write($message) { |
44
|
|
|
call_user_func($this->printer, $message); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function writeLine($message) { |
48
|
|
|
$this->write($message . "\n"); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param callable $printer |
53
|
|
|
*/ |
54
|
|
|
public function setPrinter(callable $printer) { |
55
|
|
|
$this->printer = $printer; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param callable $exceptionHandler |
60
|
|
|
*/ |
61
|
|
|
public function setExceptionHandler($exceptionHandler) { |
62
|
|
|
$this->exceptionHandler = $exceptionHandler; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function handleException($message) { |
66
|
|
|
call_user_func($this->exceptionHandler, $message); |
67
|
|
|
} |
68
|
|
|
} |
An exit expression should only be used in rare cases. For example, if you write a short command line script.
In most cases however, using an
exit
expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.