Files
piratepoet/mailpoet/lib/Automation/Engine/Storage/WorkflowStorage.php
Jan Jakes a191c691f5 Add hook and basic handler for automation triggers
For now trigger keys are stored in the workflow as a JSON array.
This is not optimal in case someone has many workflows but as
workflows are user-created it's unlinkely someone will have thousands
of them. We can consider adding a workflow_triggers table as well.

[MAILPOET-4136]
2022-03-14 09:36:21 +01:00

66 lines
1.8 KiB
PHP

<?php declare(strict_types = 1);
namespace MailPoet\Automation\Engine\Storage;
use MailPoet\Automation\Engine\Exceptions;
use MailPoet\Automation\Engine\Workflows\Trigger;
use MailPoet\Automation\Engine\Workflows\Workflow;
use wpdb;
class WorkflowStorage {
/** @var string */
private $table;
/** @var wpdb */
private $wpdb;
public function __construct() {
global $wpdb;
$this->table = $wpdb->prefix . 'mailpoet_automation_workflows';
$this->wpdb = $wpdb;
}
public function createWorkflow(Workflow $workflow): int {
$result = $this->wpdb->insert($this->table, $workflow->toArray());
if (!$result) {
throw Exceptions::databaseError($this->wpdb->last_error);
}
return $this->wpdb->insert_id;
}
/** @return string[] */
public function getActiveTriggerKeys(): array {
$query = strval(
$this->wpdb->prepare(
"SELECT DISTINCT trigger_keys FROM $this->table WHERE status = %s",
Workflow::STATUS_ACTIVE
)
);
$result = $this->wpdb->get_col($query);
$triggerKeys = [];
foreach ($result as $item) {
/** @var string[] $keys */
$keys = (array)json_decode($item, true);
$triggerKeys = array_merge($triggerKeys, $keys);
}
return array_unique($triggerKeys);
}
/** @return Workflow[] */
public function getActiveWorkflowsByTrigger(Trigger $trigger): array {
$query = strval(
$this->wpdb->prepare(
"SELECT * FROM $this->table WHERE status = %s AND trigger_keys LIKE %s",
Workflow::STATUS_ACTIVE,
'%' . $this->wpdb->esc_like($trigger->getKey()) . '%'
)
);
$data = $this->wpdb->get_results($query, ARRAY_A);
return array_map(function (array $workflowData) {
return Workflow::fromArray($workflowData);
}, (array)$data);
}
}