File size: 2,998 Bytes
cf14c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | <?php
declare(strict_types=1);
namespace Option\Domain\Entities;
use DateTime;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use Option\Domain\ValueObjects\Key;
use Option\Domain\ValueObjects\Value;
use Shared\Domain\ValueObjects\Id;
#[ORM\Entity]
#[ORM\Table(name: '`option`')]
#[ORM\HasLifecycleCallbacks]
class OptionEntity
{
/** A unique numeric identifier of the entity. */
#[ORM\Embedded(class: Id::class, columnPrefix: false)]
private Id $id;
#[ORM\Embedded(class: Key::class, columnPrefix: false)]
private Key $key;
#[ORM\Embedded(class: Value::class, columnPrefix: false)]
private Value $value;
/** Creation date and time of the entity */
#[ORM\Column(type: 'datetime', name: 'created_at')]
private DateTimeInterface $createdAt;
/** The date and time when the entity was last modified. */
#[ORM\Column(type: 'datetime', name: 'updated_at', nullable: true)]
private ?DateTimeInterface $updatedAt = null;
public function __construct(
Key $key,
Value $value
) {
$this->id = new Id();
$this->key = $key;
$this->value = $value;
$this->createdAt = new DateTime();
}
public function getId(): Id
{
return $this->id;
}
public function getKey(): Key
{
return $this->key;
}
public function getValue(): Value
{
return $this->value;
}
public function setValue(Value $value): void
{
if (!$this->value->value) {
$this->value = $value;
return;
}
$current = json_decode($this->value->value, true);
if (!$current || !is_array($current)) {
$this->value = $value;
return;
}
$new = json_decode($value->value, true);
if (!$new || !is_array($new)) {
$this->value = $value;
return;
}
$this->value = new Value(json_encode(
$this->replaceValue($current, $new)
));
}
public function getCreatedAt(): DateTimeInterface
{
return $this->createdAt;
}
public function getUpdatedAt(): ?DateTimeInterface
{
return $this->updatedAt;
}
#[ORM\PreUpdate]
public function preUpdate(): void
{
$this->updatedAt = new DateTime();
}
private function replaceValue(
array $current,
array $new
): array {
foreach ($new as $key => $value) {
if (is_array($value) && isset($current[$key]) && is_array($current[$key])) {
// Check if the array is associative
if (array_keys($current[$key]) !== range(0, count($current[$key]) - 1)) {
$current[$key] = $this->replaceValue($current[$key], $value);
} else {
$current[$key] = $value;
}
} else {
$current[$key] = $value;
}
}
return $current;
}
}
|