<?php
namespace Boldr\Shop\ShopBundle\Twig;
use Twig\Extension\AbstractExtension;
use Symfony\Component\HttpFoundation\RequestStack;
use Boldr\Shop\ShopBundle\ShopContext;
use Boldr\Shop\ShopBundle\CurrencyFormatter;
use Boldr\Shop\ShopBundle\Presenter\Order\{ OrderPresenter, OrderView };
use Boldr\Shop\ShopBundle\Presenter\Currency\{ CurrencyPresenter, CurrencyView };
use Boldr\Shop\ShopBundle\Presenter\Customer\{ CustomerPresenter, CustomerView };
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Psr\Container\ContainerInterface;
use Twig\{ TwigFunction, TwigFilter };
class Extension extends AbstractExtension implements ServiceSubscriberInterface
{
private ContainerInterface $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public static function getSubscribedServices()
{
return [
RequestStack::class,
ShopContext::class,
CurrencyFormatter::class,
OrderPresenter::class,
CurrencyPresenter::class,
CustomerPresenter::class,
];
}
public function getFunctions()
{
return [
new TwigFunction('boldr_shop_get_cart', [$this, 'createCartView']),
new TwigFunction('boldr_shop_get_customer', [$this, 'createCustomerView']),
new TwigFunction('boldr_shop_get_currencies', [$this, 'getCurrencies']),
new TwigFunction('boldr_shop_get_currency', [$this, 'getCurrency']),
new TwigFunction('boldr_shop_format_currency', [$this->container->get(CurrencyFormatter::class), 'format']),
];
}
public function createCartView(): OrderView
{
$locale = $this->container->get(RequestStack::class)->getCurrentRequest()->getLocale();
$currentOrder = $this->container->get(ShopContext::class)->getCurrentOrder();
return $this->container->get(OrderPresenter::class)->createOrderView($currentOrder, $locale);
}
public function createCustomerView(): ?CustomerView
{
$customer = $this->container->get(ShopContext::class)->getCustomer();
if ($customer === null)
return null;
$locale = $this->container->get(RequestStack::class)->getCurrentRequest()->getLocale();
return $this->container->get(CustomerPresenter::class)->createCustomerView($customer, $locale);
}
/**
* @return CurrencyView[]
*/
public function getCurrencies(): array
{
$currencyPresenter = $this->container->get(CurrencyPresenter::class);
return array_map(
fn($currency) => $currencyPresenter->createCurrencyView($currency),
array_keys($this->container->get(ShopContext::class)->getCurrencies())
);
}
public function getCurrency(): CurrencyView
{
return $this->container->get(CurrencyPresenter::class)->createCurrencyView($this->container->get(ShopContext::class)->getCurrency());
}
}