RuntimeException example


    private function getSnippetsByLocale(SnippetFileCollection $snippetFileCollection, string $locale): array
    {
        $files = $snippetFileCollection->getSnippetFilesByIso($locale);
        $snippets = [];

        foreach ($files as $file) {
            $json = json_decode(file_get_contents($file->getPath()) ?: '', true);

            $jsonError = json_last_error();
            if ($jsonError !== 0) {
                throw new \RuntimeException(sprintf('Invalid JSON in snippet file at path \'%s\' with code \'%d\'', $file->getPath()$jsonError));
            }

            $flattenSnippetFileSnippets = $this->flatten($json);

            $snippets = array_replace_recursive(
                $snippets,
                $flattenSnippetFileSnippets
            );
        }

        return $snippets;
    }
/** * {@inheritdoc} */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $outputIsVerbose = $output->isVerbose();
        $io = new SymfonyStyle($input$output);

        $realCacheDir = $this->getContainer()->getParameter('kernel.cache_dir');

        if (!\is_string($realCacheDir)) {
            throw new RuntimeException('Parameter kernel.cache_dir needs to be a string');
        }

        // the old cache dir name must not be longer than the real one to avoid exceeding         // the maximum length of a directory or file path within it (esp. Windows MAX_PATH)         $oldCacheDir = substr($realCacheDir, 0, -1) . (substr($realCacheDir, -1) === '~' ? '+' : '~');
        $filesystem = $this->getContainer()->get('file_system');

        if (!is_writable($realCacheDir)) {
            throw new RuntimeException(sprintf('Unable to write into directory "%s"', $realCacheDir));
        }

        
private readonly MessageBusInterface $messageBus
    ) {
    }

    public function clear(): void
    {
        foreach ($this->adapters as $adapter) {
            $adapter->clear();
        }

        if (!is_writable($this->cacheDir)) {
            throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $this->cacheDir));
        }

        $this->cacheClearer->clear($this->cacheDir);

        if ($this->clusterMode) {
            // In cluster mode we can't delete caches on the filesystem             // because this only runs on one node in the cluster             return;
        }

        $this->filesystem->remove($this->cacheDir . '/twig');
        
new ClosureLoader($container),
        ]);

        $configLoader = new DelegatingLoader($resolver);

        $confDir = $this->getPath() . '/Resources/config';

        $configLoader->load($confDir . '/{packages}/*' . Kernel::CONFIG_EXTS, 'glob');

        $env = $container->getParameter('kernel.environment');
        if (!\is_string($env)) {
            throw new \RuntimeException('Container parameter "kernel.environment" needs to be a string');
        }
        $configLoader->load($confDir . '/{packages}/' . $env . '/*' . Kernel::CONFIG_EXTS, 'glob');
    }
}
private readonly InstanceService $instanceService,
    ) {
    }

    /** * @return array{firstRunWizardUserToken: array{token: string, expirationDate: string}} */
    public function frwLogin(string $shopwareId, string $password, Context $context): array
    {
        if (!$context->getSource() instanceof AdminApiSource
            || $context->getSource()->getUserId() === null) {
            throw new \RuntimeException('First run wizard requires a logged in user');
        }

        $response = $this->client->request(
            Request::METHOD_POST,
            '/swplatform/firstrunwizard/login',
            [
                'json' => [
                    'shopwareId' => $shopwareId,
                    'password' => $password,
                ],
                'query' => $this->optionsProvider->getDefaultQueryParameters($context),
            ]
public function getEntity(string $entity): AbstractEntitySerializer
    {
        foreach ($this->entitySerializers as $serializer) {
            if ($serializer->supports($entity)) {
                $serializer->setRegistry($this);

                return $serializer;
            }
        }

        throw new \RuntimeException('There should be a fallback serializer');
    }

    public function getFieldSerializer(Field $field): AbstractFieldSerializer
    {
        foreach ($this->fieldSerializers as $serializer) {
            if ($serializer->supports($field)) {
                $serializer->setRegistry($this);

                return $serializer;
            }
        }

        

    public function __construct(ModelManager $modelManager, array $pluginDirectories, array $snippetConfig, ?string $themeDir = null)
    {
        $this->snippetConfig = $snippetConfig;
        $this->modelManager = $modelManager;
        $this->pluginDirectories = $pluginDirectories;

        $fallbackLocale = $this->modelManager->getRepository(Locale::class)->findOneBy(['locale' => 'en_GB']);
        if (!$fallbackLocale instanceof Locale) {
            throw new RuntimeException('Required fallback locale "en_GB" not found');
        }
        $this->fallbackLocale = $fallbackLocale;

        if ($this->snippetConfig['readFromIni']) {
            $configDir = $this->getConfigDirs($themeDir);
            $this->fileAdapter = new Enlight_Config_Adapter_File([
                'configDir' => $configDir,
                'allowWrites' => $snippetConfig['writeToIni'],
            ]);
        }

        
private function updateToManyAssociations(EntityDefinition $definition, array $ids, FieldCollection $associations, Context $context): void
    {
        $bytes = array_map(fn ($id) => Uuid::fromHexToBytes($id)$ids);

        /** @var AssociationField $association */
        foreach ($associations as $association) {
            $reference = $association->getReferenceDefinition();

            $flag = $association->getFlag(Inherited::class);

            if (!$flag instanceof Inherited) {
                throw new \RuntimeException(\sprintf('Association %s is not marked as inherited', $definition->getEntityName() . '.' . $association->getPropertyName()));
            }

            $foreignKey = $flag->getForeignKey() ?: ($definition->getEntityName() . '_id');

            $versionKey = \substr($foreignKey, 0, -3) . '_version_id';

            $sql = sprintf(
                'UPDATE #root# SET #property# = IFNULL( ( SELECT #reference#.#entity_id# FROM #reference# WHERE #reference#.#entity_id# = #root#.id %s LIMIT 1 ), IFNULL(#root#.parent_id, #root#.id) ) WHERE #root#.id IN (:ids) %s',

    private function prepareShopData(array $params, ?ShopModel $shop = null): array
    {
        $requiredParams = ['name', 'localeId', 'currencyId', 'customerGroupId', 'categoryId'];
        foreach ($requiredParams as $param) {
            if (!$shop) {
                if (!isset($params[$param]) || empty($params[$param])) {
                    throw new ParameterMissingException($param);
                }
            } else {
                if (isset($params[$param]) && empty($params[$param])) {
                    throw new RuntimeException(sprintf('param %s may not be empty', $param));
                }
            }
        }

        if (isset($params['currencyId'])) {
            $currency = Shopware()->Models()->find(Currency::class$params['currencyId']);
            if ($currency !== null) {
                $params['currency'] = $currency;
            } else {
                throw new RuntimeException(sprintf('%s is not a valid currency id', $params['currencyId']));
            }
        }
return $this->definitionInstanceRegistry->getRepository($profile->getSourceEntity());
    }

    private function getPipe(ImportExportLogEntity $logEntity): AbstractPipe
    {
        foreach ($this->pipeFactories as $factory) {
            if ($factory->supports($logEntity)) {
                return $factory->create($logEntity);
            }
        }

        throw new \RuntimeException('No pipe factory found');
    }

    private function getReader(ImportExportLogEntity $logEntity): AbstractReader
    {
        foreach ($this->readerFactories as $factory) {
            if ($factory->supports($logEntity)) {
                return $factory->create($logEntity);
            }
        }

        throw new \RuntimeException('No reader factory found');
    }
public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): HttpKernelResult
    {
        try {
            return $this->doHandle($request$type$catch);
        } catch (Exception $e) {
            /** @var Params|array{url?: string} $connectionParams */
            $connectionParams = self::getConnection()->getParams();

            $message = str_replace([$connectionParams['url'] ?? null, $connectionParams['password'] ?? null, $connectionParams['user'] ?? null], '******', $e->getMessage());

            throw new \RuntimeException(sprintf('Could not connect to database. Message from SQL Server: %s', $message));
        }
    }

    public function getKernel(): KernelInterface
    {
        return $this->createKernel();
    }

    /** * Allows to switch the plugin loading. */
    

class UpdateControllerTest extends TestCase
{
    public function testRedirectWhenNotInstalled(): void
    {
        $recoveryManager = $this->createMock(RecoveryManager::class);

        $recoveryManager
            ->method('getShopwareLocation')
            ->willThrowException(new \RuntimeException('Could not find Shopware installation'));

        $controller = new UpdateController(
            $recoveryManager,
            $this->createMock(ReleaseInfoProvider::class),
            $this->createMock(FlexMigrator::class),
            $this->createMock(StreamedCommandResponseGenerator::class),
        );

        $controller->setContainer($this->getContainer());

        $request = new Request();
        
public function resolve(Request $request, ArgumentMetadata $argument): \Generator
    {
        if ($argument->getType() !== CustomerEntity::class) {
            return;
        }

        $loginRequired = $request->attributes->get(PlatformRequest::ATTRIBUTE_LOGIN_REQUIRED);

        if ($loginRequired !== true) {
            $route = $request->attributes->get('_route');

            throw new \RuntimeException('Missing @LoginRequired annotation for route: ' . $route);
        }

        $context = $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
        if (!$context instanceof SalesChannelContext) {
            $route = $request->attributes->get('_route');

            throw new \RuntimeException('Missing sales channel context for route ' . $route);
        }

        yield $context->getCustomer();
    }
}
protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new ShopwareStyle($input$output);

        $username = $input->getArgument('username');
        $password = $input->getOption('password');

        if (!$password) {
            $passwordQuestion = new Question('Enter password for user');
            $passwordQuestion->setValidator(static function D$value): string {
                if ($value === null || trim($value) === '') {
                    throw new \RuntimeException('The password cannot be empty');
                }

                return $value;
            });
            $passwordQuestion->setHidden(true);
            $passwordQuestion->setMaxAttempts(3);

            $password = $io->askQuestion($passwordQuestion);
        }

        $additionalData = [];
        
/** * @throws ThemeCompileException * @throws InvalidThemeBundleException */
    private function createConfigFromClassName(string $pluginPath, string $className): StorefrontPluginConfiguration
    {
        /** @var Plugin $plugin */
        $plugin = new $className(true, $pluginPath$this->projectDirectory);

        if (!$plugin instanceof Plugin) {
            throw new \RuntimeException(
                sprintf('Plugin class "%s" must extend "%s"', $plugin::class, Plugin::class)
            );
        }

        return $this->pluginConfigurationFactory->createFromBundle($plugin);
    }

    private function doPostActivate(PluginLifecycleEvent $event): void
    {
        if (!($event instanceof PluginPostActivateEvent) && !($event instanceof PluginPostDeactivationFailedEvent)) {
            return;
        }
Home | Imprint | This part of the site doesn't use cookies.