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

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