Files
jsonedit/src/Tree/ObjectNode.php
2024-10-07 00:30:09 +02:00

55 lines
1.2 KiB
PHP

<?php
namespace NoccyLabs\JsonEdit\Tree;
class ObjectNode extends Node implements CollapsibleNode
{
use CollapsibleNodeTrait;
public function __construct(public array $properties)
{
}
public function set(string $key, Node $value)
{
$this->properties[$key] = $value;
}
public function hasKey(string $key): bool
{
return array_key_exists($key, $this->properties);
}
public function rename(string $key, string $newKey)
{
if (array_key_exists($newKey, $this->properties)) {
throw new \Exception("Key {$newKey} already exists");
}
$renamed = [];
foreach ($this->properties as $k=>$v) {
$renamed[($k==$key)?$newKey:$k] = $v;
}
$this->properties = $renamed;
}
public function unset(string $key)
{
unset($this->properties[$key]);
}
public function __clone(): void
{
$this->properties = array_combine(
array_keys($this->properties),
array_map(fn($v) => clone $v, $this->properties)
);
}
public function jsonSerialize(): mixed
{
return $this->properties;
}
}