<?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\AdminBundle\Emoji;

use Symfony\Component\Emoji\EmojiTransliterator;

/**
 * Turns the GitHub-style short codes we persist (e.g. ":tada:") back into their
 * Unicode glyph for display in the admin UI.
 */
final class EmojiRenderer
{
    private ?EmojiTransliterator $transliterator = null;

    /**
     * @return string the emoji glyph, or an empty string when no (valid) short code is given
     */
    public function render(?string $shortCode): string
    {
        if (null === $shortCode || '' === $shortCode) {
            return '';
        }

        $emoji = $this->transliterator()->transliterate($shortCode);

        // When the short code is unknown the transliterator returns it verbatim;
        // don't leak the raw ":foo:" into the UI in that case.
        return $emoji === $shortCode ? '' : $emoji;
    }

    private function transliterator(): EmojiTransliterator
    {
        return $this->transliterator ??= EmojiTransliterator::create('github-emoji');
    }
}
