negundo-client/src/Task.php
2024-11-08 09:14:56 -05:00

69 lines
2.3 KiB
PHP

<?php
namespace Negundo\Client {
class Task {
public static array $instances = [];
protected array $sent = [];
protected Transport\TransportInterface $transport;
protected Util\TaskHandler $taskHandler;
protected SoftwareConfig $config;
public function __construct(SoftwareConfig $config, ? DataInterface $dataManipulator = null, Transport\TransportInterface $transport = null)
{
$this->config = $config;
$this->transport = $transport ?: new Transport\Curl();
$this->taskHandler = new Util\TaskHandler($dataManipulator);
static::$instances[] = $this;
}
public function newReport(string $message, ? string $title = null, ? array $data = [], ? array $events = []) : object|null|bool
{
$report = $this->taskHandler->sendReport($message, $title, $data, $events);
// Make sure not to spam the server if an ErrorMessage or Exception was already sent (like inside a loop)
$dumpHash = $this->taskHandler->hash($report);
if ( $this->sent[$dumpHash] ?? false ) {
return null;
}
$this->sent[$dumpHash] = true;
return $this->transport->push($this->config->url('task/report'), $report);
}
}
}
namespace {
use Negundo\Client\Task\StatusEnum;
use Negundo\Client\Task\TaskReport;
if (! function_exists('ntask') ) {
function ntask(string $message, ? string $title = null, ? array $data = null, ? Negundo\Client\Task\StatusEnum $status = null, array $events = []) {
foreach (\Negundo\Client\Task::$instances as $instance) {
$sent = $instance->newReport($message, $title, $data, $events);
if (! $sent ) {
throw new \Exception(sprintf('Could not send report titled `%s`.', $title));
}
}
}
function nreport(TaskReport $report)
{
if ($report->status !== StatusEnum::NothingToDo || $report->getEvents()) {
ntask($report->getMessage(), $report->getTitle(), $report->getData(), $report->getStatus(), $report->getEvents());
}
}
}
}