vendor/shopware/core/System/SystemConfig/SystemConfigService.php line 348

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\System\SystemConfig;
  3. use Doctrine\DBAL\Connection;
  4. use Shopware\Core\Framework\Bundle;
  5. use Shopware\Core\Framework\Context;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Field\ConfigJsonField;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  12. use Shopware\Core\Framework\Util\XmlReader;
  13. use Shopware\Core\Framework\Uuid\Exception\InvalidUuidException;
  14. use Shopware\Core\Framework\Uuid\Uuid;
  15. use Shopware\Core\System\SystemConfig\Event\BeforeSystemConfigChangedEvent;
  16. use Shopware\Core\System\SystemConfig\Event\SystemConfigChangedEvent;
  17. use Shopware\Core\System\SystemConfig\Event\SystemConfigDomainLoadedEvent;
  18. use Shopware\Core\System\SystemConfig\Exception\BundleConfigNotFoundException;
  19. use Shopware\Core\System\SystemConfig\Exception\InvalidDomainException;
  20. use Shopware\Core\System\SystemConfig\Exception\InvalidKeyException;
  21. use Shopware\Core\System\SystemConfig\Exception\InvalidSettingValueException;
  22. use Shopware\Core\System\SystemConfig\Util\ConfigReader;
  23. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  24. use function json_decode;
  25. class SystemConfigService
  26. {
  27.     private Connection $connection;
  28.     private EntityRepositoryInterface $systemConfigRepository;
  29.     private ConfigReader $configReader;
  30.     /**
  31.      * @var array<string, bool>
  32.      */
  33.     private array $keys = ['all' => true];
  34.     /**
  35.      * @var array<mixed>
  36.      */
  37.     private array $traces = [];
  38.     private AbstractSystemConfigLoader $loader;
  39.     private EventDispatcherInterface $eventDispatcher;
  40.     /**
  41.      * @internal
  42.      */
  43.     public function __construct(
  44.         Connection $connection,
  45.         EntityRepository $systemConfigRepository,
  46.         ConfigReader $configReader,
  47.         AbstractSystemConfigLoader $loader,
  48.         EventDispatcherInterface $eventDispatcher
  49.     ) {
  50.         $this->connection $connection;
  51.         $this->systemConfigRepository $systemConfigRepository;
  52.         $this->configReader $configReader;
  53.         $this->loader $loader;
  54.         $this->eventDispatcher $eventDispatcher;
  55.     }
  56.     public static function buildName(string $key): string
  57.     {
  58.         return 'config.' $key;
  59.     }
  60.     /**
  61.      * @return array<mixed>|bool|float|int|string|null
  62.      */
  63.     public function get(string $key, ?string $salesChannelId null)
  64.     {
  65.         foreach (array_keys($this->keys) as $trace) {
  66.             $this->traces[$trace][self::buildName($key)] = true;
  67.         }
  68.         $config $this->loader->load($salesChannelId);
  69.         $parts explode('.'$key);
  70.         $pointer $config;
  71.         foreach ($parts as $part) {
  72.             if (!\is_array($pointer)) {
  73.                 return null;
  74.             }
  75.             if (\array_key_exists($part$pointer)) {
  76.                 $pointer $pointer[$part];
  77.                 continue;
  78.             }
  79.             return null;
  80.         }
  81.         return $pointer;
  82.     }
  83.     public function getString(string $key, ?string $salesChannelId null): string
  84.     {
  85.         $value $this->get($key$salesChannelId);
  86.         if (!\is_array($value)) {
  87.             return (string) $value;
  88.         }
  89.         throw new InvalidSettingValueException($key'string'\gettype($value));
  90.     }
  91.     public function getInt(string $key, ?string $salesChannelId null): int
  92.     {
  93.         $value $this->get($key$salesChannelId);
  94.         if (!\is_array($value)) {
  95.             return (int) $value;
  96.         }
  97.         throw new InvalidSettingValueException($key'int'\gettype($value));
  98.     }
  99.     public function getFloat(string $key, ?string $salesChannelId null): float
  100.     {
  101.         $value $this->get($key$salesChannelId);
  102.         if (!\is_array($value)) {
  103.             return (float) $value;
  104.         }
  105.         throw new InvalidSettingValueException($key'float'\gettype($value));
  106.     }
  107.     public function getBool(string $key, ?string $salesChannelId null): bool
  108.     {
  109.         return (bool) $this->get($key$salesChannelId);
  110.     }
  111.     /**
  112.      * @internal should not be used in storefront or store api. The cache layer caches all accessed config keys and use them as cache tag.
  113.      *
  114.      * gets all available shop configs and returns them as an array
  115.      *
  116.      * @return array<mixed>
  117.      */
  118.     public function all(?string $salesChannelId null): array
  119.     {
  120.         return $this->loader->load($salesChannelId);
  121.     }
  122.     /**
  123.      * @internal should not be used in storefront or store api. The cache layer caches all accessed config keys and use them as cache tag.
  124.      *
  125.      * @throws InvalidDomainException
  126.      *
  127.      * @return array<mixed>
  128.      */
  129.     public function getDomain(string $domain, ?string $salesChannelId nullbool $inherit false): array
  130.     {
  131.         $domain trim($domain);
  132.         if ($domain === '') {
  133.             throw new InvalidDomainException('Empty domain');
  134.         }
  135.         $queryBuilder $this->connection->createQueryBuilder()
  136.             ->select(['configuration_key''configuration_value'])
  137.             ->from('system_config');
  138.         if ($inherit) {
  139.             $queryBuilder->where('sales_channel_id IS NULL OR sales_channel_id = :salesChannelId');
  140.         } elseif ($salesChannelId === null) {
  141.             $queryBuilder->where('sales_channel_id IS NULL');
  142.         } else {
  143.             $queryBuilder->where('sales_channel_id = :salesChannelId');
  144.         }
  145.         $domain rtrim($domain'.') . '.';
  146.         $escapedDomain str_replace('%''\\%'$domain);
  147.         $salesChannelId $salesChannelId Uuid::fromHexToBytes($salesChannelId) : null;
  148.         $queryBuilder->andWhere('configuration_key LIKE :prefix')
  149.             ->addOrderBy('sales_channel_id''ASC')
  150.             ->setParameter('prefix'$escapedDomain '%')
  151.             ->setParameter('salesChannelId'$salesChannelId);
  152.         $configs $queryBuilder->executeQuery()->fetchAllNumeric();
  153.         if ($configs === []) {
  154.             return [];
  155.         }
  156.         $merged = [];
  157.         foreach ($configs as [$key$value]) {
  158.             if ($value !== null) {
  159.                 $value json_decode($valuetrue);
  160.                 if ($value === false || !isset($value[ConfigJsonField::STORAGE_KEY])) {
  161.                     $value null;
  162.                 } else {
  163.                     $value $value[ConfigJsonField::STORAGE_KEY];
  164.                 }
  165.             }
  166.             $inheritedValuePresent \array_key_exists($key$merged);
  167.             $valueConsideredEmpty = !\is_bool($value) && empty($value);
  168.             if ($inheritedValuePresent && $valueConsideredEmpty) {
  169.                 continue;
  170.             }
  171.             $merged[$key] = $value;
  172.         }
  173.         $event = new SystemConfigDomainLoadedEvent($domain$merged$inherit$salesChannelId);
  174.         $this->eventDispatcher->dispatch($event);
  175.         return $event->getConfig();
  176.     }
  177.     /**
  178.      * @param array<mixed>|bool|float|int|string|null $value
  179.      */
  180.     public function set(string $key$value, ?string $salesChannelId null): void
  181.     {
  182.         $key trim($key);
  183.         $this->validate($key$salesChannelId);
  184.         $event = new BeforeSystemConfigChangedEvent($key$value$salesChannelId);
  185.         $this->eventDispatcher->dispatch($event);
  186.         $id $this->getId($key$salesChannelId);
  187.         if ($value === null) {
  188.             if ($id) {
  189.                 $this->systemConfigRepository->delete([['id' => $id]], Context::createDefaultContext());
  190.             }
  191.             $this->eventDispatcher->dispatch(new SystemConfigChangedEvent($key$value$salesChannelId));
  192.             return;
  193.         }
  194.         $data = [
  195.             'id' => $id ?? Uuid::randomHex(),
  196.             'configurationKey' => $key,
  197.             'configurationValue' => $event->getValue(),
  198.             'salesChannelId' => $salesChannelId,
  199.         ];
  200.         $this->systemConfigRepository->upsert([$data], Context::createDefaultContext());
  201.         $this->eventDispatcher->dispatch(new SystemConfigChangedEvent($key$event->getValue(), $salesChannelId));
  202.     }
  203.     public function delete(string $key, ?string $salesChannel null): void
  204.     {
  205.         $this->set($keynull$salesChannel);
  206.     }
  207.     /**
  208.      * Fetches default values from bundle configuration and saves it to database
  209.      */
  210.     public function savePluginConfiguration(Bundle $bundlebool $override false): void
  211.     {
  212.         try {
  213.             $config $this->configReader->getConfigFromBundle($bundle);
  214.         } catch (BundleConfigNotFoundException $e) {
  215.             return;
  216.         }
  217.         $prefix $bundle->getName() . '.config.';
  218.         $this->saveConfig($config$prefix$override);
  219.     }
  220.     /**
  221.      * @param array<mixed> $config
  222.      */
  223.     public function saveConfig(array $configstring $prefixbool $override): void
  224.     {
  225.         $relevantSettings $this->getDomain($prefix);
  226.         foreach ($config as $card) {
  227.             foreach ($card['elements'] as $element) {
  228.                 $key $prefix $element['name'];
  229.                 if (!isset($element['defaultValue'])) {
  230.                     continue;
  231.                 }
  232.                 $value XmlReader::phpize($element['defaultValue']);
  233.                 if ($override || !isset($relevantSettings[$key]) || $relevantSettings[$key] === null) {
  234.                     $this->set($key$value);
  235.                 }
  236.             }
  237.         }
  238.     }
  239.     public function deletePluginConfiguration(Bundle $bundle): void
  240.     {
  241.         try {
  242.             $config $this->configReader->getConfigFromBundle($bundle);
  243.         } catch (BundleConfigNotFoundException $e) {
  244.             return;
  245.         }
  246.         $this->deleteExtensionConfiguration($bundle->getName(), $config);
  247.     }
  248.     /**
  249.      * @param array<mixed> $config
  250.      */
  251.     public function deleteExtensionConfiguration(string $extensionName, array $config): void
  252.     {
  253.         $prefix $extensionName '.config.';
  254.         $configKeys = [];
  255.         foreach ($config as $card) {
  256.             foreach ($card['elements'] as $element) {
  257.                 $configKeys[] = $prefix $element['name'];
  258.             }
  259.         }
  260.         if (empty($configKeys)) {
  261.             return;
  262.         }
  263.         $criteria = new Criteria();
  264.         $criteria->addFilter(new EqualsAnyFilter('configurationKey'$configKeys));
  265.         $systemConfigIds $this->systemConfigRepository->searchIds($criteriaContext::createDefaultContext())->getIds();
  266.         if (empty($systemConfigIds)) {
  267.             return;
  268.         }
  269.         $ids array_map(static function ($id) {
  270.             return ['id' => $id];
  271.         }, $systemConfigIds);
  272.         $this->systemConfigRepository->delete($idsContext::createDefaultContext());
  273.     }
  274.     /**
  275.      * @return mixed|null All kind of data could be cached
  276.      */
  277.     public function trace(string $key\Closure $param)
  278.     {
  279.         $this->traces[$key] = [];
  280.         $this->keys[$key] = true;
  281.         $result $param();
  282.         unset($this->keys[$key]);
  283.         return $result;
  284.     }
  285.     /**
  286.      * @return array<mixed>
  287.      */
  288.     public function getTrace(string $key): array
  289.     {
  290.         $trace = isset($this->traces[$key]) ? array_keys($this->traces[$key]) : [];
  291.         unset($this->traces[$key]);
  292.         return $trace;
  293.     }
  294.     /**
  295.      * @throws InvalidKeyException
  296.      * @throws InvalidUuidException
  297.      */
  298.     private function validate(string $key, ?string $salesChannelId): void
  299.     {
  300.         $key trim($key);
  301.         if ($key === '') {
  302.             throw new InvalidKeyException('key may not be empty');
  303.         }
  304.         if ($salesChannelId && !Uuid::isValid($salesChannelId)) {
  305.             throw new InvalidUuidException($salesChannelId);
  306.         }
  307.     }
  308.     private function getId(string $key, ?string $salesChannelId null): ?string
  309.     {
  310.         $criteria = new Criteria();
  311.         $criteria->addFilter(
  312.             new EqualsFilter('configurationKey'$key),
  313.             new EqualsFilter('salesChannelId'$salesChannelId)
  314.         );
  315.         /** @var array<string> $ids */
  316.         $ids $this->systemConfigRepository->searchIds($criteriaContext::createDefaultContext())->getIds();
  317.         /** @var string|null $id */
  318.         $id array_shift($ids);
  319.         return $id;
  320.     }
  321. }