99 lines
2.9 KiB
PHP
99 lines
2.9 KiB
PHP
<?php
|
|
namespace Contabilidad;
|
|
|
|
use DateTimeInterface;
|
|
use Carbon\Carbon;
|
|
use ProVM\Common\Alias\Model;
|
|
use ProVM\Common\Factory\Model as Factory;
|
|
|
|
/**
|
|
* @property int $id
|
|
* @property string $command
|
|
* @property DateTimeInterface $created
|
|
* @property bool $processed
|
|
*/
|
|
class Queue extends Model {
|
|
public static $_table = 'queue';
|
|
protected static $fields = ['command', 'created', 'processed'];
|
|
|
|
public function created(DateTimeInterface $fecha = null) {
|
|
if ($fecha === null) {
|
|
return Carbon::parse($this->created);
|
|
}
|
|
$this->created = $fecha->format('Y-m-d H:i:s');
|
|
return $this;
|
|
}
|
|
public function hasArguments(): bool {
|
|
return Model::factory(QueueArgument::class)
|
|
->whereEqual('queue_id', $this->id)
|
|
->groupBy('queue_id')
|
|
->count('id') > 0;
|
|
}
|
|
protected $arguments;
|
|
public function arguments() {
|
|
if ($this->arguments === null) {
|
|
$this->arguments = $this->parentOf(QueueArgument::class, [Model::CHILD_KEY => 'queue_id']);
|
|
}
|
|
return $this->arguments;
|
|
}
|
|
public function matchArguments(array $arguments): array {
|
|
$args = $this->arguments();
|
|
if ($args === null) {
|
|
return [];
|
|
}
|
|
$matched = [];
|
|
foreach ($arguments as $argument => $value) {
|
|
foreach ($args as $arg) {
|
|
if ($arg->argument == $argument and $arg->value == $value) {
|
|
$matched []= $arg;
|
|
}
|
|
}
|
|
}
|
|
return $matched;
|
|
}
|
|
public function isProcessed(): bool {
|
|
return $this->processed > 0;
|
|
}
|
|
public function setProcessed(bool $processed): Queue {
|
|
$this->processed = $processed ? 1 : 0;
|
|
return $this;
|
|
}
|
|
|
|
public static function find(Factory $factory, $data) {
|
|
$where = [
|
|
'command' => $data['command'],
|
|
'processed' => $data['processed'] ?? 0
|
|
];
|
|
array_walk($where, function(&$item, $key) {
|
|
$item = [$key, $item];
|
|
});
|
|
$where = array_values($where);
|
|
return $factory->find(Queue::class)->where($where)->one();
|
|
}
|
|
|
|
public function toArray(): array
|
|
{
|
|
$arr = parent::toArray();
|
|
$cmd = [(string) $this];
|
|
$arr['arguments'] = [];
|
|
if ($this->hasArguments()) {
|
|
$arr['arguments'] = array_map(function($item) use (&$cmd) {
|
|
$cmd []= (string) $item;
|
|
return $item->toArray();
|
|
}, $this->arguments());
|
|
}
|
|
$arr['cmd'] = implode(' ', $cmd);
|
|
return $arr;
|
|
}
|
|
|
|
public function __toString(): string {
|
|
$str = "{$this->command}";
|
|
$arguments = $this->arguments();
|
|
if ($arguments !== null and count($arguments) > 0) {
|
|
$arguments = implode(' ', array_map(function($item) {return (string) $item;}, $arguments));
|
|
$str .= " {$arguments}";
|
|
}
|
|
return $str;
|
|
}
|
|
}
|