Repository navigation
Expand file tree
/
Copy pathOutOfMemoryHandler.php
More file actions
63 lines (53 loc) · 1.69 KB
/
Copy pathOutOfMemoryHandler.php
File metadata and controls
63 lines (53 loc) · 1.69 KB
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
<?php
namespace BookStack\Util;
use BookStack\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
/**
* Create a handler which runs the provided actions upon an
* out-of-memory event. This allows reserving of memory to allow
* the desired action to run as needed.
*
* Essentially provides a wrapper and memory reserving around the
* memory handling added to the default app error handler.
*/
class OutOfMemoryHandler
{
protected $onOutOfMemory;
protected string $memoryReserve = '';
public function __construct(callable $onOutOfMemory, int $memoryReserveMB = 4)
{
$this->onOutOfMemory = $onOutOfMemory;
$this->memoryReserve = str_repeat('x', $memoryReserveMB * 1_000_000);
$this->getHandler()->prepareForOutOfMemory(function () {
return $this->handle();
});
}
protected function handle(): mixed
{
$result = null;
$this->memoryReserve = '';
if ($this->onOutOfMemory) {
$result = call_user_func($this->onOutOfMemory);
$this->forget();
}
return $result;
}
/**
* Forget the handler, so no action is taken place on out of memory.
*/
public function forget(): void
{
$this->memoryReserve = '';
$this->onOutOfMemory = null;
$this->getHandler()->forgetOutOfMemoryHandler();
}
protected function getHandler(): Handler
{
/**
* We want to resolve our specific BookStack handling via the set app handler
* singleton, but phpstan will only infer based on the interface.
* @phpstan-ignore return.type
*/
return app()->make(ExceptionHandler::class);
}
}