|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * Copyright (C) 2014 - 2026, Biospex |
| 5 | + * biospex@gmail.com |
| 6 | + * |
| 7 | + * This program is free software: you can redistribute it and/or modify |
| 8 | + * it under the terms of the GNU General Public License as published by |
| 9 | + * the Free Software Foundation, either version 3 of the License, or |
| 10 | + * (at your option) any later version. |
| 11 | + * |
| 12 | + * This program is distributed in the hope that it will be useful, |
| 13 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 | + * GNU General Public License for more details. |
| 16 | + * |
| 17 | + * You should have received a copy of the GNU General Public License |
| 18 | + * along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 19 | + */ |
| 20 | + |
| 21 | +namespace App\Filament\Components; |
| 22 | + |
| 23 | +use Filament\Forms\Components\CodeEditor; |
| 24 | +use Filament\Forms\Components\CodeEditor\Enums\Language; |
| 25 | + |
| 26 | +class JsonEditor extends CodeEditor |
| 27 | +{ |
| 28 | + protected function setUp(): void |
| 29 | + { |
| 30 | + parent::setUp(); |
| 31 | + |
| 32 | + $this->language(Language::Json); |
| 33 | + $this->columnSpanFull(); |
| 34 | + |
| 35 | + // Validate that the input is valid JSON |
| 36 | + $this->rule(function () { |
| 37 | + return function (string $attribute, mixed $value, \Closure $fail) { |
| 38 | + if (is_string($value) && ! blank($value)) { |
| 39 | + json_decode($value); |
| 40 | + if (json_last_error() !== JSON_ERROR_NONE) { |
| 41 | + $fail("The {$this->getLabel()} must be a valid JSON string."); |
| 42 | + } |
| 43 | + } |
| 44 | + }; |
| 45 | + }); |
| 46 | + |
| 47 | + // Format array data from database for the UI |
| 48 | + $this->formatStateUsing(function ($state) { |
| 49 | + if (is_string($state)) { |
| 50 | + $decoded = json_decode($state, associative: true); |
| 51 | + |
| 52 | + return json_last_error() === JSON_ERROR_NONE ? json_encode($decoded, JSON_PRETTY_PRINT) : $state; |
| 53 | + } |
| 54 | + |
| 55 | + return is_array($state) ? json_encode($state, JSON_PRETTY_PRINT) : $state; |
| 56 | + }); |
| 57 | + |
| 58 | + // Handle saving back as an array |
| 59 | + $this->dehydrateStateUsing(function (?string $state) { |
| 60 | + if (blank($state)) { |
| 61 | + return null; |
| 62 | + } |
| 63 | + $decoded = json_decode($state, associative: true); |
| 64 | + |
| 65 | + return json_last_error() === JSON_ERROR_NONE ? $decoded : $state; |
| 66 | + }); |
| 67 | + |
| 68 | + // Keep Livewire state in sync |
| 69 | + $this->afterStateUpdated(function (?string $state, $set, $component) { |
| 70 | + $set($component->getStatePath(), $state ? json_decode($state, associative: true) : null); |
| 71 | + }); |
| 72 | + } |
| 73 | +} |
0 commit comments