Periodic.php
78 lines
| 1 | <?php |
| 2 | |
| 3 | namespace IAWPSCOPED\Proper; |
| 4 | |
| 5 | use DateInterval; |
| 6 | use DateTime; |
| 7 | use Exception; |
| 8 | use Throwable; |
| 9 | /** @internal */ |
| 10 | class Periodic |
| 11 | { |
| 12 | private $option_name; |
| 13 | private $interval; |
| 14 | /** |
| 15 | * @param string $option_name |
| 16 | * @param string|DateInterval $interval A DateInterval or a period pattern for a date interval |
| 17 | * |
| 18 | * @throws Exception An exception is thrown if $interval is a string but isn't a valid period |
| 19 | */ |
| 20 | private function __construct(string $option_name, $interval) |
| 21 | { |
| 22 | $this->option_name = $option_name; |
| 23 | $this->interval = $interval; |
| 24 | if (\is_string($interval)) { |
| 25 | $this->interval = new DateInterval($interval); |
| 26 | } |
| 27 | } |
| 28 | /** |
| 29 | * @return bool True if it's time for the task to run. |
| 30 | */ |
| 31 | private function should_run() : bool |
| 32 | { |
| 33 | $last_execution = $this->get_last_execution(); |
| 34 | if (\is_null($last_execution)) { |
| 35 | return \true; |
| 36 | } |
| 37 | $is_past_interval_time = $last_execution->add($this->interval) < new DateTime('now', Timezone::utc_timezone()); |
| 38 | if ($is_past_interval_time) { |
| 39 | return \true; |
| 40 | } |
| 41 | return \false; |
| 42 | } |
| 43 | private function get_last_execution() : ?DateTime |
| 44 | { |
| 45 | $option_value = \get_option($this->option_name, \false); |
| 46 | if (!$option_value) { |
| 47 | return null; |
| 48 | } |
| 49 | try { |
| 50 | return new DateTime($option_value, Timezone::utc_timezone()); |
| 51 | } catch (Throwable $e) { |
| 52 | return null; |
| 53 | } |
| 54 | } |
| 55 | /** |
| 56 | * Mark task as complete |
| 57 | * |
| 58 | * @return void |
| 59 | */ |
| 60 | private function complete() : void |
| 61 | { |
| 62 | $now = new DateTime('now', Timezone::utc_timezone()); |
| 63 | \update_option($this->option_name, $now->format('c')); |
| 64 | } |
| 65 | /** |
| 66 | * @throws Exception |
| 67 | */ |
| 68 | public static function check(string $option_name, $interval) : bool |
| 69 | { |
| 70 | $periodically = new Periodic($option_name, $interval); |
| 71 | $should_run = $periodically->should_run(); |
| 72 | if ($should_run) { |
| 73 | $periodically->complete(); |
| 74 | } |
| 75 | return $should_run; |
| 76 | } |
| 77 | } |
| 78 |