Initial Version
This commit is contained in:
68
shared/lib/Json/JsonSerializableCollection.php
Normal file
68
shared/lib/Json/JsonSerializableCollection.php
Normal file
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace KTXF\Json;
|
||||
|
||||
use KTXF\Json\JsonSerializable;
|
||||
use KTXF\Json\JsonDeserializable;
|
||||
use KTXF\Utile\Collection\CollectionAbstract;
|
||||
|
||||
abstract class JsonSerializableCollection extends CollectionAbstract implements JsonSerializable, JsonDeserializable {
|
||||
|
||||
protected array $primitiveTypes = [
|
||||
self::TYPE_STRING,
|
||||
self::TYPE_INT,
|
||||
self::TYPE_FLOAT,
|
||||
self::TYPE_BOOL,
|
||||
self::TYPE_ARRAY,
|
||||
self::TYPE_DATE,
|
||||
];
|
||||
|
||||
public function jsonSerialize(): mixed {
|
||||
return $this->getArrayCopy();
|
||||
}
|
||||
|
||||
public function jsonDeserialize(array|string $data): static {
|
||||
|
||||
if (is_string($data)) {
|
||||
$data = json_decode($data, true);
|
||||
}
|
||||
|
||||
$this->exchangeArray([]);
|
||||
|
||||
if (in_array($this->typeValue, $this->primitiveTypes)) {
|
||||
if ($this->associative) {
|
||||
foreach ($data as $key => $value) {
|
||||
$this[$key] = $value;
|
||||
}
|
||||
} else {
|
||||
foreach ($data as $value) {
|
||||
$this[] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!in_array($this->typeValue, $this->primitiveTypes) && class_exists($this->typeValue)) {
|
||||
$reflection = new \ReflectionClass($this->typeValue);
|
||||
if ($reflection->implementsInterface(JsonDeserializable::class)) {
|
||||
if ($this->associative) {
|
||||
foreach ($data as $key => $value) {
|
||||
$instance = $reflection->newInstance();
|
||||
/** @var JsonDeserializable $instance */
|
||||
$this[$key] = $instance->jsonDeserialize($value);
|
||||
}
|
||||
} else {
|
||||
foreach ($data as $value) {
|
||||
$instance = $reflection->newInstance();
|
||||
/** @var JsonDeserializable $instance */
|
||||
$this[] = $instance->jsonDeserialize($value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user