2023-08-08 23:53:49 -04:00
|
|
|
<?php
|
|
|
|
namespace Incoviba\Common\Implement\Repository;
|
|
|
|
|
2024-06-11 12:07:57 -04:00
|
|
|
use Error;
|
2023-08-08 23:53:49 -04:00
|
|
|
use Closure;
|
|
|
|
use Incoviba\Common\Define;
|
2024-07-17 22:33:33 -04:00
|
|
|
use Incoviba\Common\Implement\Exception\EmptyResult;
|
2023-08-08 23:53:49 -04:00
|
|
|
|
|
|
|
class Mapper implements Define\Repository\Mapper
|
|
|
|
{
|
|
|
|
public string $property;
|
|
|
|
public Closure $function;
|
|
|
|
public Define\Repository\Factory $factory;
|
|
|
|
public mixed $default;
|
|
|
|
|
|
|
|
public function setProperty(string $property): Define\Repository\Mapper
|
|
|
|
{
|
|
|
|
$this->property = $property;
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
public function setFunction(callable $function): Define\Repository\Mapper
|
|
|
|
{
|
|
|
|
$this->function = $function(...);
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
public function setFactory(Define\Repository\Factory $factory): Define\Repository\Mapper
|
|
|
|
{
|
|
|
|
$this->factory = $factory;
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
public function setDefault(mixed $value): Define\Repository\Mapper
|
|
|
|
{
|
|
|
|
$this->default = $value;
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function hasProperty(): bool
|
|
|
|
{
|
|
|
|
return isset($this->property);
|
|
|
|
}
|
|
|
|
public function hasFunction(): bool
|
|
|
|
{
|
|
|
|
return isset($this->function);
|
|
|
|
}
|
|
|
|
public function hasFactory(): bool
|
|
|
|
{
|
|
|
|
return isset($this->factory);
|
|
|
|
}
|
|
|
|
public function hasDefault(): bool
|
|
|
|
{
|
2024-06-11 12:07:57 -04:00
|
|
|
try {
|
|
|
|
return isset($this->default) or $this->default === null;
|
|
|
|
} catch (Error) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-08-08 23:53:49 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
public function parse(Define\Model &$model, string $column, ?array $data): bool
|
|
|
|
{
|
|
|
|
$property = $column;
|
|
|
|
if ($this->hasProperty()) {
|
|
|
|
$property = $this->property;
|
|
|
|
}
|
2023-12-21 19:15:11 -03:00
|
|
|
if (in_array($column, array_keys($data))) {
|
2023-08-08 23:53:49 -04:00
|
|
|
if ($this->hasFactory()) {
|
|
|
|
$model->addFactory($property, $this->factory);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
$value = $data[$column];
|
|
|
|
if ($this->hasFunction()) {
|
2025-02-04 12:09:34 -03:00
|
|
|
try {
|
|
|
|
$value = ($this->function)($data);
|
|
|
|
} catch (EmptyResult $exception) {
|
|
|
|
if ($this->hasDefault()) {
|
|
|
|
$value = $this->default;
|
|
|
|
} else {
|
|
|
|
throw $exception;
|
2024-07-17 22:33:33 -04:00
|
|
|
}
|
2024-01-10 20:32:55 -03:00
|
|
|
}
|
2023-08-08 23:53:49 -04:00
|
|
|
}
|
|
|
|
$model->{$property} = $value;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
if ($this->hasDefault()) {
|
|
|
|
$model->{$property} = $this->default;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|