IfElseAction.php
84 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\FilterHandler; |
| 9 | use MailPoet\Automation\Engine\Control\StepRunController; |
| 10 | use MailPoet\Automation\Engine\Data\FilterGroup; |
| 11 | use MailPoet\Automation\Engine\Data\Step; |
| 12 | use MailPoet\Automation\Engine\Data\StepRunArgs; |
| 13 | use MailPoet\Automation\Engine\Data\StepValidationArgs; |
| 14 | use MailPoet\Automation\Engine\Integration\Action; |
| 15 | use MailPoet\Automation\Engine\Integration\ValidationException; |
| 16 | use MailPoet\Validator\Builder; |
| 17 | use MailPoet\Validator\Schema\ObjectSchema; |
| 18 | |
| 19 | class IfElseAction implements Action { |
| 20 | public const KEY = 'core:if-else'; |
| 21 | |
| 22 | /** @var FilterHandler */ |
| 23 | private $filterHandler; |
| 24 | |
| 25 | public function __construct( |
| 26 | FilterHandler $filterHandler |
| 27 | ) { |
| 28 | $this->filterHandler = $filterHandler; |
| 29 | } |
| 30 | |
| 31 | public function getKey(): string { |
| 32 | return self::KEY; |
| 33 | } |
| 34 | |
| 35 | public function getName(): string { |
| 36 | // translators: automation action title |
| 37 | return __('If/Else', 'mailpoet'); |
| 38 | } |
| 39 | |
| 40 | public function getArgsSchema(): ObjectSchema { |
| 41 | return Builder::object(); |
| 42 | } |
| 43 | |
| 44 | public function getSubjectKeys(): array { |
| 45 | return []; |
| 46 | } |
| 47 | |
| 48 | public function validate(StepValidationArgs $args): void { |
| 49 | $step = $args->getStep(); |
| 50 | |
| 51 | // validate next steps |
| 52 | $nextSteps = $step->getNextSteps(); |
| 53 | if (count($nextSteps) !== 2) { |
| 54 | throw ValidationException::create()->withError( |
| 55 | 'if_else_next_steps_count', |
| 56 | __('If/Else action must have exactly two next steps.', 'mailpoet') |
| 57 | ); |
| 58 | } |
| 59 | |
| 60 | // validate conditions |
| 61 | $groups = $step->getFilters() ? $step->getFilters()->getGroups() : []; |
| 62 | $conditions = array_map(function (FilterGroup $group) { |
| 63 | return $group->getFilters(); |
| 64 | }, $groups); |
| 65 | |
| 66 | if (count($conditions) === 0) { |
| 67 | throw ValidationException::create()->withError( |
| 68 | 'if_else_conditions_count', |
| 69 | __('If/Else action must have at least one condition set.', 'mailpoet') |
| 70 | ); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | public function run(StepRunArgs $args, StepRunController $controller): void { |
| 75 | $matches = $this->filterHandler->matchesFilters($args); |
| 76 | $controller->scheduleNextStepByIndex($matches ? 0 : 1); |
| 77 | } |
| 78 | |
| 79 | public function onDuplicate(Step $step): Step { |
| 80 | // Intentionally left empty for now, this cannot be duplicated |
| 81 | return $step; |
| 82 | } |
| 83 | } |
| 84 |