Initial commit

This commit is contained in:
2024-10-01 18:46:03 +02:00
commit e2868cd7bf
16 changed files with 1036 additions and 0 deletions

31
src/Tree/ArrayNode.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
namespace NoccyLabs\JEdit\Tree;
class ArrayNode extends Node implements CollapsibleNode
{
use CollapsibleNodeTrait;
public function __construct(public array $items)
{
}
public function append(Node $value)
{
$this->items[] = $value;
}
public function removeIndex(int $index)
{
unset($this->items[$index]);
$this->items = array_values($this->items);
}
public function __clone()
{
$items = array_map(fn($v) => clone $v, $this->items);
return new ArrayNode($items);
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace NoccyLabs\JEdit\Tree;
interface CollapsibleNode
{
public function collapse(bool $collapsed): self;
public function isCollapsed(): bool;
}

View File

@@ -0,0 +1,21 @@
<?php
namespace NoccyLabs\JEdit\Tree;
trait CollapsibleNodeTrait
{
private bool $collapsed = false;
public function collapse(bool $collapsed): self
{
$this->collapsed = $collapsed;
return $this;
}
public function isCollapsed(): bool
{
return $this->collapsed;
}
}

8
src/Tree/Node.php Normal file
View File

@@ -0,0 +1,8 @@
<?php
namespace NoccyLabs\JEdit\Tree;
abstract class Node
{
}

33
src/Tree/ObjectNode.php Normal file
View File

@@ -0,0 +1,33 @@
<?php
namespace NoccyLabs\JEdit\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 unset(string $key)
{
unset($this->properties[$key]);
}
public function __clone()
{
$properties = array_combine(
array_keys($this->properties),
array_map(fn($v) => clone $v, $this->properties)
);
return new ObjectNode($properties);
}
}

35
src/Tree/Tree.php Normal file
View File

@@ -0,0 +1,35 @@
<?php
namespace NoccyLabs\JEdit\Tree;
class Tree
{
public ?Node $root = null;
public function load(mixed $document): self
{
$this->root = $this->parseNode($document);
return $this;
}
private function parseNode(mixed $node): Node
{
if (is_array($node) && array_is_list($node)) {
return new ArrayNode(
array_map($this->parseNode(...), $node)
);
} elseif (is_object($node) || is_array($node)) {
return new ObjectNode(
array_combine(
array_keys((array)$node),
array_map($this->parseNode(...), (array)$node)
)
);
} else {
return new ValueNode($node);
}
}
}

11
src/Tree/ValueNode.php Normal file
View File

@@ -0,0 +1,11 @@
<?php
namespace NoccyLabs\JEdit\Tree;
class ValueNode extends Node
{
public function __construct(public mixed $value)
{
}
}