<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

/**
 * Valid JSON. Checked both client-side (JSON.parse) and server-side
 * (json_decode) so a JSON/config field can never store malformed text.
 */
class JsonRule implements ValidationPlugin
{
    public static function id(): string { return 'json'; }
    public static function label(): string { return 'Valid JSON'; }
    public static function group(): string { return 'Data'; }
    public static function paramsSchema(): array { return []; }
    public static function appliesTo(): array { return ['json', 'textarea', 'text']; }
    public static function defaultMessage(): string { return 'Enter valid JSON.'; }

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        if (is_array($value)) return true;          // already structured
        json_decode((string) $value);
        return json_last_error() === JSON_ERROR_NONE;
    }

    public static function clientRule(array $params): array
    {
        return ['json' => true];
    }
}
