<?php

namespace Velis\Mvc\Validators\Rules;

class Callback implements RuleInterface
{
    private $callback;

    /**
     * @param callable $callback Example: fn ($data) => bool
     */
    public function __construct(
        callable $callback,
        private ?string $errorMessage = null
    ) {
        $this->callback = $callback;
    }

    public function validate(array $data, string $fieldName): bool
    {
        $callback = $this->callback;
        return !array_key_exists($fieldName, $data) || $callback($data);
    }

    public function getErrorMessage($fieldName): string
    {
        return $this->errorMessage ?? "{$fieldName} is invalid";
    }
}
