<?php


namespace AutoAdmin\Bundle\Cache\Entity;

use AutoAdmin\Bundle\Content\Entity\AbstractUntranslated;
use AutoAdmin\Bundle\Content\Entity\Interfaces\CacheRuleInterface;
use Doctrine\DBAL\Types\Types;
use Exception;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

#[ORM\Entity(repositoryClass: "AutoAdmin\Bundle\Cache\Repository\CacheRuleRepository")]
class CacheRule extends AbstractUntranslated implements CacheRuleInterface
{
    #[ORM\Column(name: "pattern", type: Types::STRING, length: 255)]
    protected string $pattern;

    /**
     * Reverse: if true, the rule will be excluded from the cache
     */
    #[ORM\Column(name: "is_excluded", type: Types::BOOLEAN)]
    protected bool $isExcluded = false;

    /**
     * For using exact match string (===) instead of PCRE regex
     */
    #[ORM\Column(name: "exact_match", type: Types::BOOLEAN)]
    protected bool $exactMatch = false;

    #[Assert\Callback]
    public function validate(ExecutionContextInterface $context, $payload): void
    {
        /**
         * Check if pattern is valid PCRE regex is exactMath is disabled
         */
        if (!$this->exactMatch) {
            try {
                preg_match('#' . $this->pattern . '#', '');
            } catch (Exception $e) {
                $context->buildViolation('Invalid PCRE regex')
                    ->atPath('pattern')
                    ->addViolation();
            }
        }
    }

    public function isExcluded(): bool
    {
        return $this->isExcluded;
    }

    public function setIsExcluded(bool $isExcluded): self
    {
        $this->isExcluded = $isExcluded;

        return $this;
    }

    public function getPattern(): ?string
    {
        return $this->pattern;
    }

    public function setPattern(string $pattern): self
    {
        $this->pattern = $pattern;

        return $this;
    }

    public function isExactMatch(): bool
    {
        return $this->exactMatch;
    }

    public function setExactMatch(bool $exactMatch): self
    {
        $this->exactMatch = $exactMatch;

        return $this;
    }
}
