| 1 |
<?php |
| 2 |
/** |
| 3 |
* The conditions of a single cleanup run. |
| 4 |
* |
| 5 |
* @package Templately |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Templately\Modules\Utilities\Cleanup; |
| 9 |
|
| 10 |
/** |
| 11 |
* Immutable. `with_dry_run()` returns a copy, which is how a task's `estimate()` |
| 12 |
* reuses its `run()` path without mutating the context the rest of the sweep is |
| 13 |
* sharing. |
| 14 |
*/ |
| 15 |
final class Context { |
| 16 |
|
| 17 |
const TRIGGER_SCHEDULE = 'schedule'; |
| 18 |
const TRIGGER_MANUAL = 'manual'; |
| 19 |
const TRIGGER_POST_IMPORT = 'post_import'; |
| 20 |
|
| 21 |
/** @var bool */ |
| 22 |
private $dry_run; |
| 23 |
|
| 24 |
/** @var string */ |
| 25 |
private $trigger; |
| 26 |
|
| 27 |
/** @var RetentionPolicy */ |
| 28 |
private $policy; |
| 29 |
|
| 30 |
/** @var float Seconds this run may spend in total. */ |
| 31 |
private $budget; |
| 32 |
|
| 33 |
/** @var float */ |
| 34 |
private $started_at; |
| 35 |
|
| 36 |
private function __construct( bool $dry_run, string $trigger, RetentionPolicy $policy, float $budget, float $started_at ) { |
| 37 |
$this->dry_run = $dry_run; |
| 38 |
$this->trigger = $trigger; |
| 39 |
$this->policy = $policy; |
| 40 |
$this->budget = $budget; |
| 41 |
$this->started_at = $started_at; |
| 42 |
} |
| 43 |
|
| 44 |
public static function create( string $trigger, RetentionPolicy $policy, bool $dry_run = false, float $budget = 20.0 ): self { |
| 45 |
return new self( $dry_run, $trigger, $policy, $budget, microtime( true ) ); |
| 46 |
} |
| 47 |
|
| 48 |
public function with_dry_run( bool $dry_run ): self { |
| 49 |
$copy = clone $this; |
| 50 |
$copy->dry_run = $dry_run; |
| 51 |
|
| 52 |
return $copy; |
| 53 |
} |
| 54 |
|
| 55 |
public function is_dry_run(): bool { |
| 56 |
return $this->dry_run; |
| 57 |
} |
| 58 |
|
| 59 |
public function trigger(): string { |
| 60 |
return $this->trigger; |
| 61 |
} |
| 62 |
|
| 63 |
public function policy(): RetentionPolicy { |
| 64 |
return $this->policy; |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Seconds left before this run must stop at a task boundary. |
| 69 |
*/ |
| 70 |
public function remaining(): float { |
| 71 |
return $this->budget - ( microtime( true ) - $this->started_at ); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* Check this at your OWN item boundary, not only between tasks. A task that |
| 76 |
* runs to completion regardless gets killed mid-delete by the host, which is |
| 77 |
* the one failure mode a resumable sweep exists to avoid. |
| 78 |
* |
| 79 |
* @param float $headroom Seconds a single item is expected to need. |
| 80 |
*/ |
| 81 |
public function has_budget( float $headroom = 1.0 ): bool { |
| 82 |
return $this->remaining() > $headroom; |
| 83 |
} |
| 84 |
|
| 85 |
public function elapsed_ms(): int { |
| 86 |
return (int) round( ( microtime( true ) - $this->started_at ) * 1000 ); |
| 87 |
} |
| 88 |
} |
| 89 |
|