vendor/shopware/core/Framework/App/ShopId/ShopIdProvider.php line 74

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Framework\App\ShopId;
  3. use Shopware\Core\DevOps\Environment\EnvironmentHelper;
  4. use Shopware\Core\Framework\App\Exception\AppUrlChangeDetectedException;
  5. use Shopware\Core\Framework\Context;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  8. use Shopware\Core\Framework\Log\Package;
  9. use Shopware\Core\Framework\Util\Random;
  10. use Shopware\Core\System\SystemConfig\SystemConfigService;
  11. /**
  12.  * @internal only for use by the app-system, will be considered internal from v6.4.0 onward
  13.  */
  14. #[Package('core')]
  15. class ShopIdProvider
  16. {
  17.     final public const SHOP_ID_SYSTEM_CONFIG_KEY 'core.app.shopId';
  18.     public function __construct(
  19.         private readonly SystemConfigService $systemConfigService,
  20.         private readonly EntityRepository $appRepository
  21.     ) {
  22.     }
  23.     /**
  24.      * @throws AppUrlChangeDetectedException
  25.      */
  26.     public function getShopId(): string
  27.     {
  28.         $shopId $this->systemConfigService->get(self::SHOP_ID_SYSTEM_CONFIG_KEY);
  29.         if (!\is_array($shopId)) {
  30.             $newShopId $this->generateShopId();
  31.             $this->systemConfigService->set(self::SHOP_ID_SYSTEM_CONFIG_KEY, [
  32.                 'app_url' => EnvironmentHelper::getVariable('APP_URL'),
  33.                 'value' => $newShopId,
  34.             ]);
  35.             return $newShopId;
  36.         }
  37.         if (EnvironmentHelper::getVariable('APP_URL') !== ($shopId['app_url'] ?? '')) {
  38.             if ($this->hasApps()) {
  39.                 /** @var string $appUrl */
  40.                 $appUrl EnvironmentHelper::getVariable('APP_URL');
  41.                 throw new AppUrlChangeDetectedException($shopId['app_url'], $appUrl);
  42.             }
  43.             // if the shop does not have any apps we can update the existing shop id value
  44.             // with the new APP_URL as no app knows the shop id
  45.             $this->systemConfigService->set(ShopIdProvider::SHOP_ID_SYSTEM_CONFIG_KEY, [
  46.                 'app_url' => EnvironmentHelper::getVariable('APP_URL'),
  47.                 'value' => $shopId['value'],
  48.             ]);
  49.         }
  50.         return $shopId['value'];
  51.     }
  52.     private function generateShopId(): string
  53.     {
  54.         return Random::getAlphanumericString(16);
  55.     }
  56.     private function hasApps(): bool
  57.     {
  58.         $criteria = new Criteria();
  59.         $criteria->setLimit(1);
  60.         $result $this->appRepository->searchIds($criteriaContext::createDefaultContext());
  61.         return $result->firstId() !== null;
  62.     }
  63. }