From 8718558039eb90cbdc79395d99fe68922c44bfae Mon Sep 17 00:00:00 2001 From: Jeroen Thora Date: Fri, 15 Oct 2021 15:55:07 +0200 Subject: [PATCH] Add twig helper functions to check if entrypoint exists --- src/Asset/EntrypointLookup.php | 7 +++++++ src/Twig/EntryFilesTwigExtension.php | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/Asset/EntrypointLookup.php b/src/Asset/EntrypointLookup.php index ef4886aa..e2e98e95 100644 --- a/src/Asset/EntrypointLookup.php +++ b/src/Asset/EntrypointLookup.php @@ -140,4 +140,11 @@ private function getEntriesData(): array return $this->entriesData; } + + public function entryExists(string $entryName): bool + { + $entriesData = $this->getEntriesData(); + + return isset($entriesData['entrypoints'][$entryName]); + } } diff --git a/src/Twig/EntryFilesTwigExtension.php b/src/Twig/EntryFilesTwigExtension.php index 3af01070..253704c0 100644 --- a/src/Twig/EntryFilesTwigExtension.php +++ b/src/Twig/EntryFilesTwigExtension.php @@ -10,6 +10,7 @@ namespace Symfony\WebpackEncoreBundle\Twig; use Psr\Container\ContainerInterface; +use Symfony\WebpackEncoreBundle\Asset\EntrypointLookup; use Symfony\WebpackEncoreBundle\Asset\EntrypointLookupInterface; use Symfony\WebpackEncoreBundle\Asset\TagRenderer; use Twig\Extension\AbstractExtension; @@ -31,6 +32,7 @@ public function getFunctions(): array new TwigFunction('encore_entry_css_files', [$this, 'getWebpackCssFiles']), new TwigFunction('encore_entry_script_tags', [$this, 'renderWebpackScriptTags'], ['is_safe' => ['html']]), new TwigFunction('encore_entry_link_tags', [$this, 'renderWebpackLinkTags'], ['is_safe' => ['html']]), + new TwigFunction('encore_entry_exists', [$this, 'entryExists']), ]; } @@ -58,6 +60,16 @@ public function renderWebpackLinkTags(string $entryName, string $packageName = n ->renderWebpackLinkTags($entryName, $packageName, $entrypointName, $attributes); } + public function entryExists(string $entryName, string $entrypointName = '_default'): bool + { + $entrypointLookup = $this->getEntrypointLookup($entrypointName); + if (!$entrypointLookup instanceof EntrypointLookup) { + throw new \LogicException(sprintf('Cannot use entryExists() unless the entrypoint lookup is an instance of "%s"', EntrypointLookup::class)); + } + + return $entrypointLookup->entryExists($entryName); + } + private function getEntrypointLookup(string $entrypointName): EntrypointLookupInterface { return $this->container->get('webpack_encore.entrypoint_lookup_collection')