From 46bf135446899585a2d493e7810e96a2a017e737 Mon Sep 17 00:00:00 2001 From: Christopher Vagnetoft Date: Mon, 7 Oct 2024 00:02:15 +0200 Subject: [PATCH] Prevent duplicate/overwritten keys --- src/Editor/Editor.php | 17 +++++++++++++---- src/List/TreeList.php | 13 ------------- src/Tree/ObjectNode.php | 8 ++++++++ 3 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/Editor/Editor.php b/src/Editor/Editor.php index e65bcc8..97232a1 100644 --- a/src/Editor/Editor.php +++ b/src/Editor/Editor.php @@ -2,6 +2,7 @@ namespace NoccyLabs\JsonEdit\Editor; +use Exception; use NoccyLabs\JsonEdit\List\TreeList; use NoccyLabs\JsonEdit\Settings; use NoccyLabs\JsonEdit\Terminal\Terminal; @@ -590,10 +591,14 @@ class Editor if ($parent->node instanceof ObjectNode) { $newVal = $this->ask("\e[0;33mnew key:\e[0m ", $entry->key); if (!empty($newVal)) { - $parent->node->rename($entry->key, $newVal); - $entry->key = $newVal; - $this->list->parseTree(); - $this->redrawEditor(); + try { + $parent->node->rename($entry->key, $newVal); + $entry->key = $newVal; + $this->redrawEditor(); + } catch (Exception $e) { + $this->redrawEditor(); + $this->showMessage("\e[97;41m".$e->getMessage()); + } } } else { // $this->term->setCursor(1, $h); @@ -679,6 +684,10 @@ class Editor $this->redrawInfoBar(); return; } + if ($node->hasKey($key)) { + $this->showMessage("\e[97;41mThe key {$key} already exists"); + return; + } } if ($value === null) diff --git a/src/List/TreeList.php b/src/List/TreeList.php index 08a2871..581cb97 100644 --- a/src/List/TreeList.php +++ b/src/List/TreeList.php @@ -131,19 +131,6 @@ class TreeList implements Countable, IteratorAggregate $path = dirname($path); } - // $depth = $this->getEntryForIndex($index)->depth; - // if ($ignoreSelf) $depth = max(0, $depth - 1); - // echo "{start={$depth}}"; sleep(1); - // while ($index >= 0) { - // $entry = $this->getEntryForIndex($index); - // if ($entry->depth < $depth) { - // $node = $entry->node; - // if ($node instanceof ArrayNode || $node instanceof ObjectNode) { - // return $index; - // } - // } - // $index--; - // } return null; } diff --git a/src/Tree/ObjectNode.php b/src/Tree/ObjectNode.php index ed4513f..0c51807 100644 --- a/src/Tree/ObjectNode.php +++ b/src/Tree/ObjectNode.php @@ -15,8 +15,16 @@ class ObjectNode extends Node implements CollapsibleNode $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;