<?php declare(strict_types=1);
namespace MoorlForms\Core\Framework\Twig;
use MoorlForms\Core\Content\Element\ElementEntity;
use MoorlForms\Core\Content\Form\FormEntity;
use MoorlForms\Core\Service\FbService;
use Shopware\Core\Framework\Adapter\Twig\TemplateFinder;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class FbExtension extends AbstractExtension
{
/**
* @var string[]
*/
private array $caseCache = [];
private TemplateFinder $finder;
private FbService $fbService;
public function __construct(
TemplateFinder $finder,
FbService $fbService
) {
$this->finder = $finder;
$this->fbService = $fbService;
}
public function getTokenParsers(): array
{
return [
new FbTokenParser()
];
}
public function getFunctions(): array
{
return [
new TwigFunction('fb_form', [$this, 'getForm'], ['needs_context' => true]),
new TwigFunction('fb_date', [$this, 'getDate']),
new TwigFunction('fb_stylesheet', [$this, 'getStyleSheet'])
];
}
/**
* @param null|FormEntity|ElementEntity $element
* @return array
*/
public function getStyleSheet($element = null): array
{
$arr = [];
if (!$element) {
return $arr;
}
$config = $element->getConfig();
if (isset($config['css']) && is_array($config['css'])) {
$config['css'] = array_filter($config['css'], 'strlen');
foreach ($config['css'] as $key => $value) {
$arr[] = sprintf("%s:%s", $this->camelCaseToSnailCase($key), $value);
}
if ($element->getMedia()) {
$arr[] = sprintf("background-image:url(%s);background-size:cover;background-position: center center", $element->getMedia()->getUrl());
}
}
return $arr;
}
public function getFinder(): TemplateFinder
{
return $this->finder;
}
public function getDate(?string $value = null): string
{
if (empty($value)) {
return "";
}
$date = new \DateTimeImmutable($value);
return $date->format("Y-m-d");
}
public function getForm(array $twigContext, string $action): FormEntity
{
if (!$action) {
throw new \RuntimeException("Missing form technical name in Twig snippet");
}
return $this->fbService->initForm($action, $this->getContext($twigContext));
}
private function getContext(array $context): SalesChannelContext
{
if (!isset($context['context'])) {
throw new \RuntimeException('Missing sales channel context object');
}
$context = $context['context'];
if (!$context instanceof SalesChannelContext) {
throw new \RuntimeException('Missing sales channel context object');
}
return $context;
}
private function camelCaseToSnailCase(string $input): string
{
if (isset($this->caseCache[$input])) {
return $this->caseCache[$input];
}
$input = str_replace('_', '-', $input);
return $this->caseCache[$input] = ltrim(mb_strtolower(preg_replace('/[A-Z]/', '-$0', $input)), '-');
}
}