negundo-client/src/Task.php

59 lines
1.8 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 = []) : object|null|bool
{
$report = $this->taskHandler->sendReport($message, $title, $data);
// 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 {
if (! function_exists('ntask') ) {
function ntask(string $message, ? string $title = null, ? array $data = null) {
foreach (\Negundo\Client\Task::$instances as $instance) {
$sent = $instance->newReport($message, $title, $data);
if (! $sent ) {
throw new \Exception(sprintf('Could not send report titled `%s`.', $title));
}
}
}
}
}