getToken example

static::assertArrayHasKey('productNumber', $first->getPayload());

        $this->lineItemRepository->update([
            ['id' => $first->getId(), 'productId' => $secondId, 'referencedId' => $secondId, 'payload' => ['productNumber' => $secondId]],
        ]$context);
    }

    private function orderProduct(string $id, int $quantity, SalesChannelContext $context): string
    {
        $factory = new ProductLineItemFactory(new PriceDefinitionFactory());

        $cart = $this->cartService->getCart($context->getToken()$context);

        $cart = $this->cartService->add($cart$factory->create(['id' => $id, 'referencedId' => $id, 'quantity' => $quantity]$context)$context);

        $item = $cart->get($id);
        static::assertInstanceOf(LineItem::class$item);
        static::assertSame($quantity$item->getQuantity());

        return $this->cartService->order($cart$contextnew RequestDataBag());
    }

    private function createCustomer(): string
    {
$productId2 = Uuid::randomHex();
        $promotionId = Uuid::randomHex();
        $code = 'BF19';

        // add a new sample product         $this->createTestFixtureProduct($productId1, 50, 19, $this->getContainer()$this->context);
        $this->createTestFixtureProduct($productId2, 100, 19, $this->getContainer()$this->context);

        // add a new promotion         $this->createTestFixtureAbsolutePromotion($promotionId$code, 30, $this->getContainer(), PromotionDiscountEntity::SCOPE_CART);

        $cart = $this->cartService->getCart($this->context->getToken()$this->context);

        // create product and add to cart         $cart = $this->addProduct($productId1, 3, $cart$this->cartService, $this->context);
        $cart = $this->addProduct($productId2, 1, $cart$this->cartService, $this->context);

        // create promotion and add to cart         $cart = $this->addPromotionCode($code$cart$this->cartService, $this->context);

        // get discount line item         $discountItem = $cart->getLineItems()->getFlat()[2];

        
$this->tokenStorage = $tokenStorage;
    }

    abstract protected function getKey(): string;

    abstract protected function getToken(): ?TokenInterface;

    private function doInvoke(array|LogRecord $record): array|LogRecord
    {
        $record['extra'][$this->getKey()] = null;

        if (null !== $token = $this->getToken()) {
            $record['extra'][$this->getKey()] = [
                'authenticated' => (bool) $token->getUser(),
                'roles' => $token->getRoleNames(),
            ];

            $record['extra'][$this->getKey()]['user_identifier'] = $token->getUserIdentifier();
        }

        return $record;
    }
}

        $this->appVariable->setEnvironment($environment);
    }

    public function setDebug(bool $debug): void
    {
        $this->appVariable->setDebug($debug);
    }

    public function getToken(): ?TokenInterface
    {
        return $this->appVariable->getToken();
    }

    public function getUser(): ?UserInterface
    {
        return $this->appVariable->getUser();
    }

    public function getSession(): ?Session
    {
        return $this->appVariable->getSession();
    }

    
static::markTestSkipped('No redis server configured');
        }

        $this->getContainer()->get(Connection::class)->executeStatement('DELETE FROM cart');

        $redisCart = new Cart(Uuid::randomHex());
        $redisCart->add(
            (new LineItem('A', 'test'))
                ->setPrice(new CalculatedPrice(0, 0, new CalculatedTaxCollection()new TaxRuleCollection()))
        );

        $context = $this->getSalesChannelContext($redisCart->getToken());

        $factory = new RedisConnectionFactory('test-prefix-');
        $redis = $factory->create((string) $url);
        static::assertInstanceOf(\Redis::class$redis);
        $redis->flushAll();

        $persister = new RedisCartPersister($redis$this->getContainer()->get('event_dispatcher')$this->getContainer()->get(CartSerializationCleaner::class), false, 90);
        $persister->save($redisCart$context);

        $command = new CartMigrateCommand($redis$this->getContainer()->get(Connection::class), false, 90, $factory);
        $command->run(new ArrayInput(['from' => 'redis'])new NullOutput());

        


        if (!$this->maintenanceResolver->shouldBeCached($request)) {
            return;
        }

        $route = $request->attributes->get('_route');
        if ($route === 'frontend.checkout.configure') {
            $this->setCurrencyCookie($request$response);
        }

        $cart = $this->cartService->getCart($context->getToken()$context);

        $states = $this->updateSystemState($cart$context$request$response);

        // We need to allow it on login, otherwise the state is wrong         if (!($route === 'frontend.account.login' || $request->getMethod() === Request::METHOD_GET)) {
            return;
        }

        if ($context->getCustomer() || $cart->getLineItems()->count() > 0) {
            $newValue = $this->buildCacheHash($context);

            
$profile->setStatusCode($response->getStatusCode());
        try {
            $profile->setIp($request->getClientIp());
        } catch (ConflictingHeadersException) {
            $profile->setIp('Unknown');
        }

        if ($prevToken = $response->headers->get('X-Debug-Token')) {
            $response->headers->set('X-Previous-Debug-Token', $prevToken);
        }

        $response->headers->set('X-Debug-Token', $profile->getToken());

        foreach ($this->collectors as $collector) {
            $collector->collect($request$response$exception);

            // we need to clone for sub-requests             $profile->addCollector(clone $collector);
        }

        return $profile;
    }

    

    use ExpectDeprecationTrait;

    /** * @group legacy */
    public function testGetSetTokenLegacy()
    {
        $tokenStorage = new TokenStorage();
        $token = new UsernamePasswordToken(new InMemoryUser('username', 'password'), 'provider');
        $tokenStorage->setToken($token);
        $this->assertSame($token$tokenStorage->getToken());

        $this->expectDeprecation('Since symfony/security-core 6.2: Calling "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage::setToken()" without any arguments is deprecated, pass null explicitly instead.');

        $tokenStorage->setToken();
        $this->assertNull($tokenStorage->getToken());
    }

    public function testGetSetToken()
    {
        $tokenStorage = new TokenStorage();
        $this->assertNull($tokenStorage->getToken());
        
private function loginByCustomer(CustomerEntity $customer, SalesChannelContext $context): string
    {
        $this->customerRepository->update([
            [
                'id' => $customer->getId(),
                'lastLogin' => new \DateTimeImmutable(),
            ],
        ]$context->getContext());

        $context = $this->restorer->restore($customer->getId()$context);
        $newToken = $context->getToken();

        $event = new CustomerLoginEvent($context$customer$newToken);
        $this->eventDispatcher->dispatch($event);

        return $newToken;
    }

    /** * @throws CustomerNotFoundException */
    private function getCustomerByEmail(string $email, SalesChannelContext $context, bool $includeGuest = false): CustomerEntity
    {
public function setStates(ControllerEvent $event): void
    {
        $request = $event->getRequest();

        if (!$request->attributes->has(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)) {
            return;
        }

        /** @var SalesChannelContext $context */
        $context = $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);

        $cart = $this->cartService->getCart($context->getToken()$context);

        $context->removeState(self::STATE_LOGGED_IN);

        $context->removeState(self::STATE_CART_FILLED);

        if ($cart->getLineItems()->count() > 0) {
            $context->addState(self::STATE_CART_FILLED);
        }

        if ($context->getCustomer() !== null) {
            $context->addState(self::STATE_LOGGED_IN);
        }

            $promotionCodes
        );

        $orders = [];

        for ($i = 1; $i <= $numberOfItems; ++$i) {
            $customerId = $context->getFaker()->randomElement($customerIds);

            $salesChannelContext = $this->getContext($customerId$salesChannelIds);

            $cart = $this->cartService->createNew($salesChannelContext->getToken());
            foreach ($this->faker->randomElements($productLineItemsrandom_int(3, 5)) as $lineItem) {
                $cart->add($lineItem);
            }
            foreach ($this->faker->randomElements($promotionLineItemsrandom_int(0, 3)) as $lineItem) {
                $cart->add($lineItem);
            }

            $cart = $this->cartCalculator->calculate($cart$salesChannelContext);
            $tempOrder = $this->orderConverter->convertToOrder($cart$salesChannelContextnew OrderConversionContext());

            $tempOrder['orderDateTime'] = (new \DateTime())->modify('-' . random_int(0, 30) . ' days')->format(Defaults::STORAGE_DATE_TIME_FORMAT);
            
->willReturn('dump');

        return $dumpDataCollector;
    }

    private function assertDefaultPanel(string $expectedPanel, Profile $profile)
    {
        $profiler = $this->createMock(Profiler::class);
        $profiler
            ->expects($this->atLeastOnce())
            ->method('loadProfile')
            ->with($profile->getToken())
            ->willReturn($profile);

        $collectorsNames = array_keys($profile->getCollectors());

        $profiler
            ->expects($this->atLeastOnce())
            ->method('has')
            ->with($this->logicalXor(...$collectorsNames))
            ->willReturn(true);

        $expectedTemplate = 'expected_template.html.twig';

        


        throw new AccessDeniedHttpException('PageController can\'t be requested via XmlHttpRequest.');
    }

    // used to switch session token - when the context token expired     public function replaceContextToken(SalesChannelContextResolvedEvent $event): void
    {
        $context = $event->getSalesChannelContext();

        // only update session if token expired and switched         if ($event->getUsedToken() === $context->getToken()) {
            return;
        }

        $this->updateSession($context->getToken());
    }

    public function setCanonicalUrl(BeforeSendResponseEvent $event): void
    {
        if (!$event->getResponse()->isSuccessful()) {
            return;
        }

        
return $session;
            });

            return $requestStack;
        }]) implements ContainerInterface {
            use ServiceLocatorTrait;
        };
        $tokenStorage = new TokenStorage();
        $trackingStorage = new UsageTrackingTokenStorage($tokenStorage$sessionLocator);

        $this->assertNull($trackingStorage->getToken());
        $token = new NullToken();

        $trackingStorage->setToken($token);
        $this->assertSame($token$trackingStorage->getToken());
        $this->assertSame($token$tokenStorage->getToken());
        $this->assertSame(0, $sessionAccess);

        $trackingStorage->enableUsageTracking();
        $this->assertSame($token$trackingStorage->getToken());
        $this->assertSame(1, $sessionAccess);

        
#[Route(path: '/account/login', name: 'frontend.account.login', defaults: ['XmlHttpRequest' => true], methods: ['POST'])]     public function login(Request $request, RequestDataBag $data, SalesChannelContext $context): Response
    {
        $customer = $context->getCustomer();

        if ($customer !== null && $customer->getGuest() === false) {
            return $this->createActionResponse($request);
        }

        try {
            $token = $this->loginRoute->login($data$context)->getToken();
            $cartBeforeNewContext = $this->cartFacade->get($token$context);

            $newContext = $this->salesChannelContextService->get(
                new SalesChannelContextServiceParameters(
                    $context->getSalesChannelId(),
                    $token,
                    $context->getLanguageIdChain()[0],
                    $context->getCurrencyId(),
                    $context->getDomainId(),
                    $context->getContext()
                )
            );
Home | Imprint | This part of the site doesn't use cookies.