← All changes
|
vendor/wp-php-toolkit/reprint-server/src/class-resource-budget.php
+55
-0
16.2-beta
→
16.3-beta
View file →
| @@ -1,0 +1,55 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +// Declared here rather than in export.php so it can live in this package's | |
| 4 | +// namespace. export.php is a global-namespace file of endpoint functions that | |
| 5 | +// callers reach by unqualified name. | |
| 6 | + | |
| 7 | +namespace WordPress\Reprint\Server; | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * Tracks time and memory limits for a single API request. | |
| 11 | + * | |
| 12 | + * Every export endpoint runs under resource constraints — a maximum | |
| 13 | + * execution time and a memory ceiling. Rather than threading four | |
| 14 | + * separate values through every function signature and every | |
| 15 | + * should_continue() call, this class bundles them into a single | |
| 16 | + * object with a simple has_remaining() check. | |
| 17 | + */ | |
| 18 | +class ResourceBudget | |
| 19 | +{ | |
| 20 | + /** @var float */ | |
| 21 | + public $start_time; | |
| 22 | + /** @var int */ | |
| 23 | + public $max_time; | |
| 24 | + /** @var int */ | |
| 25 | + public $max_memory; | |
| 26 | + /** @var float */ | |
| 27 | + public $memory_threshold; | |
| 28 | + | |
| 29 | + public function __construct( | |
| 30 | + float $start_time, | |
| 31 | + int $max_time, | |
| 32 | + int $max_memory, | |
| 33 | + float $memory_threshold | |
| 34 | + ) { | |
| 35 | + $this->start_time = $start_time; | |
| 36 | + $this->max_time = $max_time; | |
| 37 | + $this->max_memory = $max_memory; | |
| 38 | + $this->memory_threshold = $memory_threshold; | |
| 39 | + } | |
| 40 | + | |
| 41 | + /** Returns false when the request should yield due to time or memory pressure. */ | |
| 42 | + public function has_remaining(): bool | |
| 43 | + { | |
| 44 | + if (microtime(true) - $this->start_time >= $this->max_time) { | |
| 45 | + return false; | |
| 46 | + } | |
| 47 | + | |
| 48 | + $memory_used = memory_get_usage(true); | |
| 49 | + if ($memory_used >= $this->max_memory * $this->memory_threshold) { | |
| 50 | + return false; | |
| 51 | + } | |
| 52 | + | |
| 53 | + return true; | |
| 54 | + } | |
| 55 | +} | |