<?php

namespace Openguru\OpenCartFramework\Validator\ValidationRules;

use Closure;

class Required implements ValidationRuleInterface
{
    public function validateRequired($value): bool
    {
        if (is_null($value)) {
            return false;
        }

        if (is_string($value) && trim($value) === '') {
            return false;
        }

        if (is_countable($value) && count($value) < 1) {
            return false;
        }

        return true;
    }

    public function validate(string $field, array $input, Closure $fail): void
    {
        $value = $input[$field] ?? null;

        if ($this->validateRequired($value) === false) {
            $fail(':field is required');
        }
    }
}
