Context example

$this->expectException(StoreSessionExpiredException::class);
        $middleware($response);
    }

    public function testLogsOutUserAndThrowsIfApiRespondsWithTokenExpiredException(): void
    {
        $response = new Response(401, [], '{"code":"ShopwarePlatformException-1"}');

        $adminUser = new UserEntity();
        $adminUser->setId('592d9499bea4417e929622ed0e92ba8b');

        $context = new Context(new AdminApiSource($adminUser->getId()));

        $request = new Request(
            [],
            [],
            [
                'sw-context' => $context,
            ]
        );

        $requestStack = new RequestStack();
        $requestStack->push($request);

        
public function __construct(private readonly Connection $connection)
    {
    }

    public function getAppContext(Hook $hook, Script $script): Context
    {
        $scriptAppInformation = $script->getScriptAppInformation();
        if (!$scriptAppInformation) {
            return $hook->getContext();
        }

        return new Context(
            $this->getAppContextSource($scriptAppInformation),
            $hook->getContext()->getRuleIds(),
            $hook->getContext()->getCurrencyId(),
            $hook->getContext()->getLanguageIdChain(),
            $hook->getContext()->getVersionId(),
            $hook->getContext()->getCurrencyFactor(),
            $hook->getContext()->considerInheritance(),
            $hook->getContext()->getTaxState(),
            $hook->getContext()->getRounding()
        );
    }

    

class FirstRunWizardClientTest extends TestCase
{
    private Context $context;

    protected function setUp(): void
    {
        $this->context = new Context(new AdminApiSource(Uuid::randomHex()));
    }

    public function testFrwLogin(): void
    {
        $firstRunWizardUserToken = [
            'firstRunWizardUserToken' => [
                'token' => 'frw-us3r-t0k3n',
                'expirationDate' => (new \DateTimeImmutable('2021-01-01 00:00:00'))->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            ],
        ];

        
protected function setUp(): void
    {
        $this->decorated = $this->createMock(AbstractShippingMethodRoute::class);
        $this->executor = $this->createMock(ScriptExecutor::class);
        $salesChannel = new SalesChannelEntity();
        $salesChannel->setId(Uuid::randomHex());
        $salesChannel->setShippingMethodId(Uuid::randomHex());
        $shippingMethod = new ShippingMethodEntity();
        $shippingMethod->setId($salesChannel->getShippingMethodId());
        $this->context = new SalesChannelContext(
            new Context(new SalesChannelApiSource(Uuid::randomHex())),
            Uuid::randomHex(),
            null,
            $salesChannel,
            new CurrencyEntity(),
            new CustomerGroupEntity(),
            new TaxCollection(),
            new PaymentMethodEntity(),
            $shippingMethod,
            new ShippingLocation(new CountryEntity(), null, null),
            new CustomerEntity(),
            new CashRoundingConfig(1, 1.1, true),
            

class FirstRunWizardServiceTest extends TestCase
{
    private Context $context;

    protected function setUp(): void
    {
        $this->context = new Context(new AdminApiSource(Uuid::randomHex()));
    }

    public function testTracksAndDispatchesEventWhenFrwIsStarted(): void
    {
        $firstRunWizardStartedEvent = new FirstRunWizardStartedEvent(FrwState::openState()$this->context);

        $eventDispatcher = $this->createMock(EventDispatcherInterface::class);
        $eventDispatcher->expects(static::once())
            ->method('dispatch')
            ->with($firstRunWizardStartedEvent);

        
private ProductListingRouteResponse $response;

    protected function setUp(): void
    {
        $this->decorated = $this->createMock(AbstractProductListingRoute::class);
        $this->cache = $this->createMock(CacheInterface::class);
        $this->eventDispatcher = new EventDispatcher();
        $salesChannel = new SalesChannelEntity();
        $salesChannel->setId(Uuid::randomHex());
        $this->context = new SalesChannelContext(
            new Context(new SalesChannelApiSource(Uuid::randomHex())),
            Uuid::randomHex(),
            null,
            $salesChannel,
            new CurrencyEntity(),
            new CustomerGroupEntity(),
            new TaxCollection(),
            new PaymentMethodEntity(),
            new ShippingMethodEntity(),
            new ShippingLocation(new CountryEntity(), null, null),
            new CustomerEntity(),
            new CashRoundingConfig(1, 1.1, true),
            
public function deriveContextsFromRoute($value$definition$name, array $defaults) {
    $contexts = [];

    if ($entity = $this->extractEntityFromRoute($value$defaults)) {
      $contexts['entity'] = EntityContext::fromEntity($entity);
      // @todo Expand to work for all view modes in       // https://www.drupal.org/node/2907413.       $view_mode = 'full';
      // Retrieve the actual view mode from the returned view display as the       // requested view mode may not exist and a fallback will be used.       $view_mode = LayoutBuilderEntityViewDisplay::collectRenderDisplay($entity$view_mode)->getMode();
      $contexts['view_mode'] = new Context(new ContextDefinition('string')$view_mode);
    }
    return $contexts;
  }

  /** * Extracts an entity from the route values. * * @param mixed $value * The raw value from the route. * @param array $defaults * The route defaults array. * * @return \Drupal\Core\Entity\EntityInterface|null * The entity for the route, or NULL if none exist. * * @see \Drupal\layout_builder\SectionStorageInterface::deriveContextsFromRoute() * @see \Drupal\Core\ParamConverter\ParamConverterInterface::convert() */
$this->validator = $this->getContainer()->get(AclCriteriaValidator::class);
    }

    /** * @dataProvider criteriaProvider */
    public function testValidateCriteria(array $privileges, Criteria $criteria, bool $pass): void
    {
        $source = new AdminApiSource(null, null);
        $source->setPermissions($privileges);

        $context = new Context(
            $source,
            [],
            Defaults::CURRENCY,
            [Defaults::LANGUAGE_SYSTEM]
        );

        $missing = $this->validator->validate(ProductDefinition::ENTITY_NAME, $criteria$context);

        if ($pass) {
            static::assertEmpty($missing);

            
private CountryRouteResponse $response;

    protected function setUp(): void
    {
        $this->decorated = $this->createMock(AbstractCountryRoute::class);
        $this->cache = $this->createMock(CacheInterface::class);
        $this->eventDispatcher = new EventDispatcher();
        $salesChannel = new SalesChannelEntity();
        $salesChannel->setId(Uuid::randomHex());
        $this->context = new SalesChannelContext(
            new Context(new SalesChannelApiSource(Uuid::randomHex())),
            Uuid::randomHex(),
            null,
            $salesChannel,
            new CurrencyEntity(),
            new CustomerGroupEntity(),
            new TaxCollection(),
            new PaymentMethodEntity(),
            new ShippingMethodEntity(),
            new ShippingLocation(new CountryEntity(), null, null),
            new CustomerEntity(),
            new CashRoundingConfig(1, 1.1, true),
            

        $response = new Response(401, [], '{"code":"ShopwarePlatformException-1"}');

        $userRepository = $this->getContainer()->get('user.repository');
        /** @var UserEntity $adminUser */
        $adminUser = $userRepository->search(new Criteria(), Context::createDefaultContext())->first();
        $userRepository->update([[
            'id' => $adminUser->getId(),
            'store_token' => 's3cr3t',
        ]], Context::createDefaultContext());

        $context = new Context(new AdminApiSource($adminUser->getId()));

        $request = new Request(
            [],
            [],
            [
                'sw-context' => $context,
            ]
        );

        $requestStack = new RequestStack();
        $requestStack->push($request);

        
private function getAdminContext($userId): Context
    {
        $source = new AdminApiSource($userId);
        $source->setPermissions([
            'order:list',
            'order:create',
            'order:update',
            'order_customer:create',
            'order_address:create',
        ]);

        return new Context($source);
    }

    private function createOrderPayload(): array
    {
        $addressId = Uuid::randomHex();

        return [
            'id' => Uuid::randomHex(),
            'itemRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'totalRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'orderDateTime' => (new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            
$value = $node;
      }
      elseif ($this->routeMatch->getRouteName() == 'node.add') {
        $node_type = $this->routeMatch->getParameter('node_type');
        $value = Node::create(['type' => $node_type->id()]);
      }
    }

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['route']);

    $context = new Context($context_definition$value);
    $context->addCacheableDependency($cacheability);
    $result['node'] = $context;

    return $result;
  }

  /** * {@inheritdoc} */
  public function getAvailableContexts() {
    $context = EntityContext::fromEntityTypeId('node', $this->t('Node from URL'));
    
'customTranslated' => null,
                ],
            ],
        ];

        $chain = [$this->getDeDeLanguageId(), Defaults::LANGUAGE_SYSTEM];
        $repo = $this->getTestRepository();

        $context = Context::createDefaultContext();
        $repo->create([$entity]$context);

        $context = new Context(new SystemSource()[], Defaults::CURRENCY, $chain);

        $result = $repo->search(new Criteria([$id])$context)->first();
        static::assertInstanceOf(Entity::class$result);

        static::assertNull($result->get('customTranslated'));
        static::assertNotNull($result->getTranslation('customTranslated'));
    }

    public function testTranslatedCustomFields(): void
    {
        $this->addCustomFields([
            
private function getAdminContext($userId): Context
    {
        $source = new AdminApiSource($userId);
        $source->setPermissions([
            'order:list',
            'order:create',
            'order:update',
            'order_customer:create',
            'order_address:create',
        ]);

        return new Context($source);
    }

    private function createOrderPayload(): array
    {
        $addressId = Uuid::randomHex();

        return [
            'id' => Uuid::randomHex(),
            'itemRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'totalRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'orderDateTime' => (new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            
$productRepository->create($products, Context::createDefaultContext());

        $notGreenFilter = new NotFilter('AND', [new EqualsFilter('product.name', 'green')]);

        $enGbContext = Context::createDefaultContext();
        $criteria = (new Criteria($ids))->addFilter($notGreenFilter);

        /** @var string[] $ids */
        $ids = $productRepository->searchIds($criteria$enGbContext)->getIds();
        static::assertEmpty($ids);

        $rawDeContext = new Context(new SystemSource()[], Defaults::CURRENCY, [$this->getDeDeLanguageId(), Defaults::LANGUAGE_SYSTEM]);
        $criteria = (new Criteria())->addFilter($notGreenFilter);

        /** @var string[] $ids */
        $ids = $productRepository->searchIds($criteria$rawDeContext)->getIds();
        static::assertContains($greenGruenId$ids);
        static::assertCount(1, $ids);

        $deContext = new Context(new SystemSource()[], Defaults::CURRENCY, [$this->getDeDeLanguageId(), Defaults::LANGUAGE_SYSTEM], Defaults::LIVE_VERSION, 1.0, true);
        $criteria = (new Criteria($ids))->addFilter($notGreenFilter);

        /** @var string[] $ids */
        
Home | Imprint | This part of the site doesn't use cookies.