<?php declare(strict_types=1);
namespace Maxia\MaxiaVariantsTable6\Storefront\Subscriber;
use Shopware\Core\DevOps\Environment\EnvironmentHelper;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Event\ThemeCompilerEnrichScssVariablesEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use function Symfony\Component\String\u;
class ThemeVariablesSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
ThemeCompilerEnrichScssVariablesEvent::class => 'onAddVariables'
];
}
/**
* @var SystemConfigService
*/
protected $systemConfig;
/**
* @var string
*/
protected $namespace;
/**
* @var string
*/
protected $addPrefix;
/**
* @var string
*/
protected $searchPrefix;
protected $types = [
'px' => [
'paddingY', 'paddingX', 'headingPaddingY', 'headingPaddingX', 'cellPaddingY', 'cellPaddingX',
'cellHeight', 'cellProductNumberWidth', 'cellManufacturerNumberWidth', 'cellImageWidth',
'cellDeliveryWidth', 'cellBuyWidth', 'quantityInputHeight', 'quantityInputBorderRadius',
'quantityInputButtonPaddingX', 'quantityInputButtonPaddingXMobile', 'cellImageHeight'
]
];
/**
* @param SystemConfigService $systemConfig
* @param string $namespace
* @param string $addPrefix
* @param string $searchPrefix
*/
public function __construct(
SystemConfigService $systemConfig,
string $namespace,
string $addPrefix = '',
string $searchPrefix = 'scss'
) {
$this->systemConfig = $systemConfig;
$this->namespace = $namespace;
$this->addPrefix = $addPrefix . '-';
$this->searchPrefix = $searchPrefix;
}
/**
* Reads all config options that begin with 'scss' and adds them as SASS variables.
*
* @param ThemeCompilerEnrichScssVariablesEvent $event
*/
public function onAddVariables(ThemeCompilerEnrichScssVariablesEvent $event)
{
$databaseUrl = EnvironmentHelper::getVariable('DATABASE_URL', getenv('DATABASE_URL'));
if (!$databaseUrl || $databaseUrl === "mysql://_placeholder.test") {
// deployment server without database
return;
}
$config = $this->systemConfig->get($this->namespace, $event->getSalesChannelId());
foreach ($config as $key => $value) {
$key = u($key);
if (!$key->startsWith($this->searchPrefix)) {
continue;
}
$value = u((string)$value)->trim();
if ($value->isEmpty()) {
continue;
}
$key = lcfirst($key->slice(strlen($this->searchPrefix))->toString());
$keyDashed = $this->addPrefix . $this->camel2dashed($key);
// auto append unit
foreach ($this->types as $type => $keys) {
if (in_array($key, $keys)) {
if (!$value->endsWith($type)) {
$value = $value->append($type);
}
}
}
$event->addVariable($keyDashed, $value->toString());
}
}
/**
* @param $string
* @return string
*/
protected function camel2dashed($string) {
return strtolower(preg_replace('/([a-zA-Z])(?=[A-Z])/', '$1-', $string));
}
}