]> BookStack Code Mirror - bookstack/blob - app/Util/OutOfMemoryHandler.php
Images: Changed how new image permissions are set
[bookstack] / app / Util / OutOfMemoryHandler.php
1 <?php
2
3 namespace BookStack\Util;
4
5 use BookStack\Exceptions\Handler;
6 use Illuminate\Contracts\Debug\ExceptionHandler;
7
8 /**
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.
12  *
13  * Essentially provides a wrapper and memory reserving around the
14  * memory handling added to the default app error handler.
15  */
16 class OutOfMemoryHandler
17 {
18     protected $onOutOfMemory;
19     protected string $memoryReserve = '';
20
21     public function __construct(callable $onOutOfMemory, int $memoryReserveMB = 4)
22     {
23         $this->onOutOfMemory = $onOutOfMemory;
24
25         $this->memoryReserve = str_repeat('x', $memoryReserveMB * 1_000_000);
26         $this->getHandler()->prepareForOutOfMemory(function () {
27             return $this->handle();
28         });
29     }
30
31     protected function handle(): mixed
32     {
33         $result = null;
34         $this->memoryReserve = '';
35
36         if ($this->onOutOfMemory) {
37             $result = call_user_func($this->onOutOfMemory);
38             $this->forget();
39         }
40
41         return $result;
42     }
43
44     /**
45      * Forget the handler so no action is taken place on out of memory.
46      */
47     public function forget(): void
48     {
49         $this->memoryReserve = '';
50         $this->onOutOfMemory = null;
51         $this->getHandler()->forgetOutOfMemoryHandler();
52     }
53
54     protected function getHandler(): Handler
55     {
56         return app()->make(ExceptionHandler::class);
57     }
58 }