<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Twig;

use Twig\Extra\Markdown\MarkdownInterface;
use Twig\Extra\Markdown\MarkdownRuntime;

/**
 * Null-safe drop-in for twig/markdown-extra's {@see MarkdownRuntime}.
 *
 * The stock runtime types its argument `convert(string $body)`, so any
 * `{{ x|markdown_to_html }}` where `x` is null throws a TypeError mid-render —
 * a 500 on the whole page/component (Sentry 7251148302: a consent with no
 * text). Nullable copy (consent text, offer/host descriptions, email bodies)
 * is rendered in many templates, not all of which guard the value. Widening
 * the parameter to `?string` and coalescing null to '' makes every call site
 * safe by default — the same graceful "render nothing" the template-level
 * `{% if %}` guards already give.
 *
 * Wired in config/services.php: the `twig.runtime.markdown` service keeps its
 * declared class (MarkdownRuntime) so Twig's class-keyed runtime map still
 * resolves it, but is instantiated through {@see self::fromConverter()}.
 */
final class NullSafeMarkdownRuntime extends MarkdownRuntime
{
    public static function fromConverter(MarkdownInterface $converter): self
    {
        return new self($converter);
    }

    public function convert(?string $body): string
    {
        return parent::convert($body ?? '');
    }
}
