From 0019887841161e64f2328b881f239897e1157775 Mon Sep 17 00:00:00 2001 From: Peter Knut Date: Wed, 2 Oct 2024 18:38:21 +0200 Subject: [PATCH] JsonPreview: Always display JSON preview for MySQL JSON field type --- plugins/AdminerJsonPreview.php | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/plugins/AdminerJsonPreview.php b/plugins/AdminerJsonPreview.php index e6d1e8e..b510c5a 100644 --- a/plugins/AdminerJsonPreview.php +++ b/plugins/AdminerJsonPreview.php @@ -139,9 +139,9 @@ public function head() document.addEventListener("DOMContentLoaded", init, false); function init() { - var links = document.querySelectorAll('a.json-icon'); + const links = document.querySelectorAll('a.json-icon'); - for (var i = 0; i < links.length; i++) { + for (let i = 0; i < links.length; i++) { links[i].addEventListener("click", function(event) { event.preventDefault(); toggleJson(this); @@ -150,11 +150,10 @@ function init() { } function toggleJson(button) { - var index = button.dataset.index; + const index = button.dataset.index; - var obj = document.getElementById("json-code-" + index); - if (!obj) - return; + const obj = document.getElementById("json-code-" + index); + if (!obj) return; if (obj.style.display === "none") { button.className += " json-up"; @@ -170,7 +169,7 @@ function toggleJson(button) { isJson($field, $original) && ($json = json_decode($original, true)) !== null) { $val = "JSON " . $val; - $val .= $this->convertJson($json, 1, $counter++); + if (is_array($json)) { + $val .= $this->convertJson($json, 1, $counter++); + } } } - public function editInput($table, $field, $attrs, $value) + public function editInput($table, array $field, $attrs, $value) { static $counter = 1; @@ -192,13 +193,18 @@ public function editInput($table, $field, $attrs, $value) return; } - if (is_string($value) && in_array(substr($value, 0, 1), ['{', '[']) && ($json = json_decode($value, true))) { + if ($this->isJson($field, $value) && ($json = json_decode($value, true)) !== null && is_array($json)) { echo "JSON
"; echo $this->convertJson($json, 1, $counter); } } - private function convertJson($json, $level = 1, $id = 0) + private function isJson(array $field, $value) + { + return $field["type"] == "json" || (is_string($value) && in_array(substr($value, 0, 1), ['{', '['])); + } + + private function convertJson(array $json, $level = 1, $id = 0) { $value = ""; @@ -240,6 +246,10 @@ private function convertJson($json, $level = 1, $id = 0) } } + if (empty($json)) { + $value .= "   "; + } + $value .= ""; return $value;