47 lines
1.6 KiB
PHP
47 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace Modules\Automation\Services;
|
|
|
|
use Illuminate\Support\Str;
|
|
use Modules\Automation\Jobs\ExecuteAutomation;
|
|
use Modules\Automation\Models\Automation;
|
|
use Modules\Automation\Models\AutomationRun;
|
|
|
|
final class AutomationRunner
|
|
{
|
|
public function dispatch(Automation $automation, array $payload = [], ?string $triggerType = null): AutomationRun
|
|
{
|
|
abort_unless($automation->isActive(), 422, 'Automation is not active.');
|
|
$run = $automation->runs()->create(['execution_id' => (string) Str::uuid(), 'trigger_type' => $triggerType ?? $automation->trigger_type, 'payload' => $payload, 'status' => 'queued']);
|
|
ExecuteAutomation::dispatch($run->id)->onQueue(config('automation.queue', 'default'));
|
|
|
|
return $run;
|
|
}
|
|
|
|
public function dispatchMatching(string $triggerType, array $payload = [], array $constraints = []): int
|
|
{
|
|
$query = Automation::query()->where('status', 'active')->where('trigger_type', $triggerType);
|
|
$count = 0;
|
|
foreach ($query->get() as $automation) {
|
|
if ($this->matches($automation, $constraints)) {
|
|
$this->dispatch($automation, $payload, $triggerType);
|
|
$count++;
|
|
}
|
|
}
|
|
|
|
return $count;
|
|
}
|
|
|
|
private function matches(Automation $automation, array $constraints): bool
|
|
{
|
|
$config = $automation->trigger_config ?? [];
|
|
foreach ($constraints as $key => $value) {
|
|
if (isset($config[$key]) && (string) $config[$key] !== (string) $value) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|