3 namespace BookStack\Util;
5 use BookStack\Exceptions\Handler;
6 use Illuminate\Contracts\Debug\ExceptionHandler;
9 * Create a handler which runs the provided actions upon an
10 * out-of-memory event. This allows reserving of memory to allow
11 * the desired action to run as needed.
13 * Essentially provides a wrapper and memory reserving around the
14 * memory handling added to the default app error handler.
16 class OutOfMemoryHandler
18 protected $onOutOfMemory;
19 protected string $memoryReserve = '';
21 public function __construct(callable $onOutOfMemory, int $memoryReserveMB = 4)
23 $this->onOutOfMemory = $onOutOfMemory;
25 $this->memoryReserve = str_repeat('x', $memoryReserveMB * 1_000_000);
26 $this->getHandler()->prepareForOutOfMemory(function () {
27 return $this->handle();
31 protected function handle(): mixed
34 $this->memoryReserve = '';
36 if ($this->onOutOfMemory) {
37 $result = call_user_func($this->onOutOfMemory);
45 * Forget the handler so no action is taken place on out of memory.
47 public function forget(): void
49 $this->memoryReserve = '';
50 $this->onOutOfMemory = null;
51 $this->getHandler()->forgetOutOfMemoryHandler();
54 protected function getHandler(): Handler
56 return app()->make(ExceptionHandler::class);