|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Setono\SyliusNavigationPlugin\Renderer; |
| 6 | + |
| 7 | +use Psr\Log\LoggerAwareInterface; |
| 8 | +use Psr\Log\LoggerInterface; |
| 9 | +use Psr\Log\NullLogger; |
| 10 | +use Setono\SyliusNavigationPlugin\Model\NavigationInterface; |
| 11 | +use Setono\SyliusNavigationPlugin\Repository\NavigationRepositoryInterface; |
| 12 | +use Sylius\Component\Channel\Context\ChannelContextInterface; |
| 13 | +use Sylius\Component\Channel\Model\ChannelInterface; |
| 14 | +use Sylius\Component\Locale\Context\LocaleContextInterface; |
| 15 | +use Twig\Environment; |
| 16 | + |
| 17 | +// todo cache this |
| 18 | +final class NavigationRenderer implements NavigationRendererInterface, LoggerAwareInterface |
| 19 | +{ |
| 20 | + private LoggerInterface $logger; |
| 21 | + |
| 22 | + public function __construct( |
| 23 | + private readonly NavigationRepositoryInterface $navigationRepository, |
| 24 | + private readonly ChannelContextInterface $channelContext, |
| 25 | + private readonly LocaleContextInterface $localeContext, |
| 26 | + private readonly Environment $twig, |
| 27 | + private readonly string $template = '@SetonoSyliusNavigationPlugin/navigation/navigation.html.twig', |
| 28 | + ) { |
| 29 | + $this->logger = new NullLogger(); |
| 30 | + } |
| 31 | + |
| 32 | + public function render( |
| 33 | + NavigationInterface|string $navigation, |
| 34 | + ChannelInterface $channel = null, |
| 35 | + string $localeCode = null, |
| 36 | + ): string { |
| 37 | + $channel = $channel ?? $this->channelContext->getChannel(); |
| 38 | + $localeCode = $localeCode ?? $this->localeContext->getLocaleCode(); |
| 39 | + |
| 40 | + if (is_string($navigation)) { |
| 41 | + $navigation = $this->navigationRepository->findOneEnabledByCode($navigation, $channel); |
| 42 | + if (null === $navigation) { |
| 43 | + $this->logger->error('Could not find navigation with code {code} on channel "{channel}"', [ |
| 44 | + 'code' => $navigation, |
| 45 | + 'channel' => $channel->getCode(), |
| 46 | + ]); |
| 47 | + |
| 48 | + return ''; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return $this->twig->render($this->template, [ |
| 53 | + 'navigation' => $navigation, |
| 54 | + 'channel' => $channel, |
| 55 | + 'localeCode' => $localeCode, |
| 56 | + ]); |
| 57 | + } |
| 58 | + |
| 59 | + public function setLogger(LoggerInterface $logger): void |
| 60 | + { |
| 61 | + $this->logger = $logger; |
| 62 | + } |
| 63 | +} |
0 commit comments