getKernel example

new Dotenv())->usePutenv()->bootEnv($projectRoot . '/.env');
}

$returnKernel = $returnKernel ?? false;

$env = $env ?? 'dev';

$kernel = new class($env$env !== 'prod', $classLoader) extends HttpKernel {
    protected static string $kernelClass = ScriptKernel::class;
};

$kernel->getKernel()->boot();

return $kernel;
abstract class AbstractConfigCommand extends ContainerDebugCommand
{
    /** * @return void */
    protected function listBundles(OutputInterface|StyleInterface $output)
    {
        $title = 'Available registered bundles with their extension alias if available';
        $headers = ['Bundle name', 'Extension alias'];
        $rows = [];

        $bundles = $this->getApplication()->getKernel()->getBundles();
        usort($bundlesfn ($bundleA$bundleB) => strcmp($bundleA->getName()$bundleB->getName()));

        foreach ($bundles as $bundle) {
            $extension = $bundle->getContainerExtension();
            $rows[] = [$bundle->getName()$extension ? $extension->getAlias() : ''];
        }

        if ($output instanceof StyleInterface) {
            $output->title($title);
            $output->table($headers$rows);
        } else {
            
$kernel = $this->getHttpKernel($dispatcherfn ($content) => new Response($content), null, ['foo']);

        $this->assertResponseEquals(new Response('foo', 200, ['X-Id' => 'bar'])$kernel->handle(new Request()));
    }

    public function testTerminate()
    {
        $dispatcher = new EventDispatcher();
        $kernel = $this->getHttpKernel($dispatcher);
        $dispatcher->addListener(KernelEvents::TERMINATE, function D$event) use (&$called, &$capturedKernel, &$capturedRequest, &$capturedResponse) {
            $called = true;
            $capturedKernel = $event->getKernel();
            $capturedRequest = $event->getRequest();
            $capturedResponse = $event->getResponse();
        });

        $kernel->terminate($request = Request::create('/')$response = new Response());
        $this->assertTrue($called);
        $this->assertEquals($kernel$capturedKernel);
        $this->assertEquals($request$capturedRequest);
        $this->assertEquals($response$capturedResponse);
    }

    

        $this->productRepository = $this->getContainer()->get('product.repository');
        $this->connection = $this->getContainer()->get(Connection::class);
        $this->getContainer()->get(AbstractKeyValueStorage::class)->set(ElasticsearchIndexer::ENABLE_MULTILINGUAL_INDEX_KEY, Feature::isActive('ES_MULTILINGUAL_INDEX'));
    }

    /** * @beforeClass */
    public static function startTransactionBefore(): void
    {
        $connection = KernelLifecycleManager::getKernel()
            ->getContainer()
            ->get(Connection::class);

        $connection->beginTransaction();
    }

    /** * @afterClass */
    public static function stopTransactionAfter(): void
    {
        
EOT
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        /** @var KernelInterface $kernel */
        $kernel = $this->getApplication()->getKernel();
        $targetArg = rtrim($input->getArgument('target') ?? '', '/');
        if (!$targetArg) {
            $targetArg = $this->getPublicDirectory($kernel->getContainer());
        }

        if (!is_dir($targetArg)) {
            $targetArg = $kernel->getProjectDir().'/'.$targetArg;

            if (!is_dir($targetArg)) {
                throw new InvalidArgumentException(sprintf('The target directory "%s" does not exist.', $targetArg));
            }
        }

    public function onKernelException(ExceptionEvent $event)
    {
        if (null === $this->controller) {
            return;
        }

        $throwable = $event->getThrowable();
        $request = $this->duplicateRequest($throwable$event->getRequest());

        try {
            $response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, false);
        } catch (\Exception $e) {
            $f = FlattenException::createFromThrowable($e);

            $this->logException($esprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', $f->getClass()$f->getMessage()$e->getFile()$e->getLine()));

            $prev = $e;
            do {
                if ($throwable === $wrapper = $prev) {
                    throw $e;
                }
            } while ($prev = $wrapper->getPrevious());

            


        // check format         $supportedFormats = $this->writer->getFormats();
        if (!\in_array($format$supportedFormats, true)) {
            $errorIo->error(['Wrong output format', 'Supported formats are: '.implode(', ', $supportedFormats).', xlf12 and xlf20.']);

            return 1;
        }

        /** @var KernelInterface $kernel */
        $kernel = $this->getApplication()->getKernel();

        // Define Root Paths         $transPaths = $this->getRootTransPaths();
        $codePaths = $this->getRootCodePaths($kernel);

        $currentName = 'default directory';

        // Override with provided Bundle info         if (null !== $input->getArgument('bundle')) {
            try {
                $foundBundle = $kernel->getBundle($input->getArgument('bundle'));
                
$eventManager = $this->kernel->getContainer()->get('events');

        $collection = new ArrayCollection();
        $collection = $eventManager->collect('Shopware_Console_Add_Command', $collection['subject' => $this]);

        foreach ($collection as $command) {
            if ($command instanceof Command) {
                $this->add($command);
            }

            if ($command instanceof ContainerAwareInterface) {
                $command->setContainer($this->getKernel()->getContainer());
            }
        }
    }

    /** * Register tagged commands in Symfony style * * @see AddConsoleCommandPass */
    protected function registerTaggedServiceIds()
    {
        
$io->success('The container was linted successfully: all services are injected with values that are compatible with their type declarations.');

        return 0;
    }

    private function getContainerBuilder(): ContainerBuilder
    {
        if (isset($this->container)) {
            return $this->container;
        }

        $kernel = $this->getApplication()->getKernel();
        $kernelContainer = $kernel->getContainer();

        if (!$kernel->isDebug() || !$kernelContainer->getParameter('debug.container.dump') || !(new ConfigCache($kernelContainer->getParameter('debug.container.dump'), true))->isFresh()) {
            if (!$kernel instanceof Kernel) {
                throw new RuntimeException(sprintf('This command does not support the application kernel: "%s" does not extend "%s".', get_debug_type($kernel), Kernel::class));
            }

            $buildContainer = \Closure::bind(function D): ContainerBuilder {
                $this->initializeBundles();

                return $this->buildContainer();
            },

#[AsCommand(name: 'lint:xliff', description: 'Lints an XLIFF file and outputs encountered errors')] class XliffLintCommand extends BaseLintCommand
{
    public function __construct()
    {
        $directoryIteratorProvider = function D$directory$default) {
            if (!is_dir($directory)) {
                $directory = $this->getApplication()->getKernel()->locateResource($directory);
            }

            return $default($directory);
        };

        $isReadableProvider = fn ($fileOrDirectory$default) => str_starts_with($fileOrDirectory, '@') || $default($fileOrDirectory);

        parent::__construct(null, $directoryIteratorProvider$isReadableProvider);
    }

    protected function configure(): void
    {
->method('getBundles')
            ->willReturn($bundles);

        $scopeDetector = $this->createMock(TemplateScopeDetector::class);
        $scopeDetector->expects(static::any())
            ->method('getScopes')
            ->willReturn([TemplateScopeDetector::DEFAULT_SCOPE]);

        $templateFinder = new TemplateFinder(
            $twig,
            $loader,
            $this->getKernel()->getCacheDir(),
            new NamespaceHierarchyBuilder([
                new BundleHierarchyBuilder(
                    $kernel,
                    $this->getContainer()->get(Connection::class)
                ),
            ]),
            $scopeDetector,
        );

        return [$twig$templateFinder];
    }
}
class ContextSwitchRouteTest extends TestCase
{
    use IntegrationTestBehaviour;
    use SalesChannelApiTestBehaviour;

    private EntityRepository $customerRepository;

    private EntityRepository $customerAddressRepository;

    protected function setUp(): void
    {
        $kernel = KernelLifecycleManager::getKernel();
        $this->customerRepository = $kernel->getContainer()->get('customer.repository');
        $this->customerAddressRepository = $kernel->getContainer()->get('customer_address.repository');
    }

    public function testUpdateContextWithNonExistingParameters(): void
    {
        $testId = Uuid::randomHex();

        /* * Shipping method */
        
public function testWithNotMatchPath()
    {
        $tester = $this->createCommandTester();
        $ret = $tester->execute(['path_info' => '/test', 'foo']['decorated' => false]);

        $this->assertEquals(1, $ret, 'Returns 1 in case of failure');
        $this->assertStringContainsString('None of the routes match the path "/test"', $tester->getDisplay());
    }

    private function createCommandTester(): CommandTester
    {
        $application = new Application($this->getKernel());
        $application->add(new RouterMatchCommand($this->getRouter()));
        $application->add(new RouterDebugCommand($this->getRouter()));

        return new CommandTester($application->find('router:match'));
    }

    private function getRouter()
    {
        $routeCollection = new RouteCollection();
        $routeCollection->add('foo', new Route('foo'));
        $requestContext = new RequestContext();
        
'frontend.account.guest.login.page' => [],
        'frontend.checkout.cart.page' => [],
        'frontend.checkout.confirm.page' => [],
        'frontend.checkout.finish.page' => [],
        'frontend.account.register.page' => [],
        'frontend.checkout.register.page' => [],
        'frontend.account.customer-group-registration.page' => ['customerGroupId' => 'abc'],
    ];

    public function testHomeController(): void
    {
        $browser = KernelLifecycleManager::createBrowser(KernelLifecycleManager::getKernel());
        $browser->setServerParameter('HTTP_' . PlatformRequest::HEADER_CONTEXT_TOKEN, '1234');
        $browser->setServerParameter('HTTP_' . PlatformRequest::HEADER_VERSION_ID, '1234');
        $browser->setServerParameter('HTTP_' . PlatformRequest::HEADER_LANGUAGE_ID, '1234');
        $browser->request('GET', $_SERVER['APP_URL']);
        $response = $browser->getResponse();

        static::assertFalse($response->headers->has(PlatformRequest::HEADER_CONTEXT_TOKEN));
        static::assertFalse($response->headers->has(PlatformRequest::HEADER_VERSION_ID));
        static::assertFalse($response->headers->has(PlatformRequest::HEADER_LANGUAGE_ID));
    }

    
use Shopware\Core\Kernel;

/** * @internal * * @group skip-paratest */
class KernelLifecycleManagerTest extends TestCase
{
    public function testIfTheKernelClassIsShopware(): void
    {
        static::assertInstanceOf(Kernel::class, KernelLifecycleManager::getKernel());
    }

    public function testARebootIsPossible(): void
    {
        $oldKernel = KernelLifecycleManager::getKernel();
        $oldConnection = Kernel::getConnection();
        $oldContainer = $oldKernel->getContainer();

        KernelLifecycleManager::bootKernel(false);

        $newKernel = KernelLifecycleManager::getKernel();
        
Home | Imprint | This part of the site doesn't use cookies.