<?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 an array.
 *
 * @package Snaju\Inception\Http\Request\Validators\Rules
 */
class InArrayRule extends ValidatorRule
{

    public function isValid($dataArray): bool
    {
        $valid = $this->optional;
        $bodyData = $dataArray['body'];
        $arr = array_map(function($val) {
            return trim($val);
        }, explode(',', $this->ruleValue));

        if (array_key_exists($this->field, $bodyData)) {
            if (in_array($bodyData[$this->field], $arr)) {
                $valid = true;
            }
                else {
                    $valid = false;
                }
        }

        return $valid;
    }
    
    public function getErrorMessage(): string
    {
        return "The `{$this->field}` must be a value of one of the following: $this->ruleValue.";
    }

}