|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Bridge\Twig\Extension; |
| 13 | + |
| 14 | +use Symfony\Component\Emoji\EmojiTransliterator; |
| 15 | +use Twig\Extension\AbstractExtension; |
| 16 | +use Twig\TwigFilter; |
| 17 | + |
| 18 | +/** |
| 19 | + * @author Grégoire Pineau <[email protected]> |
| 20 | + */ |
| 21 | +final class EmojiExtension extends AbstractExtension |
| 22 | +{ |
| 23 | + private static array $transliterators = []; |
| 24 | + |
| 25 | + public function __construct( |
| 26 | + private readonly string $defaultCatalog = 'text', |
| 27 | + ) { |
| 28 | + if (!class_exists(EmojiTransliterator::class)) { |
| 29 | + throw new \LogicException('You cannot use the "emojify" filter as the "Emoji" component is not installed. Try running "composer require symfony/emoji".'); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public function getFilters(): array |
| 34 | + { |
| 35 | + return [ |
| 36 | + new TwigFilter('emojify', $this->emojify(...)), |
| 37 | + ]; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Converts emoji short code (:wave:) to real emoji (👋) |
| 42 | + */ |
| 43 | + public function emojify(string $string, ?string $catalog = null): string |
| 44 | + { |
| 45 | + $catalog ??= $this->defaultCatalog; |
| 46 | + |
| 47 | + try { |
| 48 | + $tr = self::$transliterators[$catalog] ??= EmojiTransliterator::create($catalog, EmojiTransliterator::REVERSE); |
| 49 | + } catch (\IntlException $e) { |
| 50 | + throw new \LogicException(sprintf('The emoji catalog "%s" is not available.', $catalog), previous: $e); |
| 51 | + } |
| 52 | + |
| 53 | + return (string) $tr->transliterate($string); |
| 54 | + } |
| 55 | +} |
0 commit comments