<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use App\Http\Traits\BoardTrait;
use App\Models\BoardMeta;
use DOMDocument;

class BlobDataEscape implements Rule
{
    use BoardTrait;

    protected BoardMeta $boardMeta;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct(int $boardID)
    {
        $this->boardMeta = $this->boardMeta($boardID);
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $doc = new DOMDocument();
        $doc->loadHTML($value);
        $count = trim(strlen($doc->documentElement->textContent));

        return ($count < $this->boardMeta->item('comment_max_length', 0));
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return sprintf(":attribute은 최대 %s 글자 입력 가능합니다.", $this->boardMeta->item('comment_max_length', 0));
    }
}
