<?php

namespace App\Support;

use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
use Symfony\Component\HtmlSanitizer\Visitor\AttributeSanitizer\AttributeSanitizerInterface;

/**
 * Allows only `style="text-align: left|center|right|justify"` (as emitted by
 * Tiptap's TextAlign extension) through the sanitizer's `style` attribute.
 */
class TextAlignAttributeSanitizer implements AttributeSanitizerInterface
{
    public function getSupportedElements(): ?array
    {
        return ['p', 'h2', 'h3'];
    }

    public function getSupportedAttributes(): ?array
    {
        return ['style'];
    }

    public function sanitizeAttribute(string $element, string $attribute, string $value, HtmlSanitizerConfig $config): ?string
    {
        if (preg_match('/^text-align:\s*(left|center|right|justify);?$/i', trim($value)) === 1) {
            return $value;
        }

        return null;
    }
}
