Prevent duplicate/overwritten keys

This commit is contained in:
Chris 2024-10-07 00:02:15 +02:00
parent 54b00f5925
commit 46bf135446
3 changed files with 21 additions and 17 deletions

View File

@ -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)

View File

@ -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;
}

View File

@ -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;