<?php

namespace Snaju\Inception\Http\Request\Validators\Rules;

use Snaju\Inception\Http\Request\Validators\ValidatorRule;

/**
 * Validates that the value provided for the specified field is a valid JSON object. May be provided as a string or actual JSON object -- both are valid and evaluate to true.
 *
 * @package Snaju\Inception\Http\Request\Validators\Rules
 */
class JsonRule extends ValidatorRule
{

    public function isValid($dataArray): bool
    {
        $valid = $this->optional;
        $bodyData = $dataArray['body'];

        if (array_key_exists($this->field, $bodyData)) {
            $fieldValue = $bodyData[$this->field];

            if (is_string($fieldValue)) {
                json_decode($fieldValue);
                $valid = (json_last_error() === JSON_ERROR_NONE);
            }
                else if (is_object($fieldValue) || is_array($fieldValue)) {
                    $valid = true;
                }
                else {
                    $valid = false;
                }

        }

        return $valid;
    }
    
    public function getErrorMessage(): string
    {
        return "The `{$this->field}` must be a json string.";
    }

}