DelayAction.php
79 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Automation\Integrations\Core\Actions; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Automation\Engine\Control\StepRunController; |
| 9 | use MailPoet\Automation\Engine\Data\Step; |
| 10 | use MailPoet\Automation\Engine\Data\StepRunArgs; |
| 11 | use MailPoet\Automation\Engine\Data\StepValidationArgs; |
| 12 | use MailPoet\Automation\Engine\Integration\Action; |
| 13 | use MailPoet\Automation\Engine\Integration\ValidationException; |
| 14 | use MailPoet\Validator\Builder; |
| 15 | use MailPoet\Validator\Schema\ObjectSchema; |
| 16 | |
| 17 | class DelayAction implements Action { |
| 18 | public const KEY = 'core:delay'; |
| 19 | |
| 20 | public function getKey(): string { |
| 21 | return self::KEY; |
| 22 | } |
| 23 | |
| 24 | public function getName(): string { |
| 25 | // translators: automation action title |
| 26 | return _x('Delay', 'noun', 'mailpoet'); |
| 27 | } |
| 28 | |
| 29 | public function getArgsSchema(): ObjectSchema { |
| 30 | return Builder::object([ |
| 31 | 'delay' => Builder::integer()->required()->minimum(1), |
| 32 | 'delay_type' => Builder::string()->required()->pattern('^(MINUTES|DAYS|HOURS|WEEKS)$')->default('HOURS'), |
| 33 | ]); |
| 34 | } |
| 35 | |
| 36 | public function getSubjectKeys(): array { |
| 37 | return []; |
| 38 | } |
| 39 | |
| 40 | public function validate(StepValidationArgs $args): void { |
| 41 | $seconds = $this->calculateSeconds($args->getStep()); |
| 42 | if ($seconds <= 0) { |
| 43 | throw ValidationException::create() |
| 44 | ->withError('delay', __('A delay must have a positive value', 'mailpoet')); |
| 45 | } |
| 46 | if ($seconds > 2 * YEAR_IN_SECONDS) { |
| 47 | throw ValidationException::create() |
| 48 | ->withError('delay', __("A delay can't be longer than two years", 'mailpoet')); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | public function run(StepRunArgs $args, StepRunController $controller): void { |
| 53 | if ($args->isFirstRun()) { |
| 54 | $controller->scheduleProgress(time() + self::calculateSeconds($args->getStep())); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | public function onDuplicate(Step $step): Step { |
| 59 | // Intentionally left empty for now |
| 60 | return $step; |
| 61 | } |
| 62 | |
| 63 | public static function calculateSeconds(Step $step): int { |
| 64 | $delay = (int)($step->getArgs()['delay'] ?? null); |
| 65 | switch ($step->getArgs()['delay_type']) { |
| 66 | case "MINUTES": |
| 67 | return $delay * MINUTE_IN_SECONDS; |
| 68 | case "HOURS": |
| 69 | return $delay * HOUR_IN_SECONDS; |
| 70 | case "DAYS": |
| 71 | return $delay * DAY_IN_SECONDS; |
| 72 | case "WEEKS": |
| 73 | return $delay * WEEK_IN_SECONDS; |
| 74 | default: |
| 75 | return 0; |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 |