RequestDataBag example

$email = Uuid::randomHex() . '@example.com';
        $this->createCustomer($email);

        $contextToken = Random::getAlphanumericString(32);

        $salesChannelContext = $this->getContainer()->get(SalesChannelContextFactory::class)->create(
            $contextToken,
            TestDefaults::SALES_CHANNEL,
            []
        );

        $request = new RequestDataBag(['email' => $email, 'password' => 'shopware']);
        $loginResponse = $this->getContainer()->get(LoginRoute::class)->login($request$salesChannelContext);

        $customerId = $this->createCustomer();
        $customer = $this->getContainer()
            ->get('customer.repository')
            ->search(new Criteria(), Context::createDefaultContext())
            ->get($customerId);
        static::assertInstanceOf(CustomerEntity::class$customer);
        $customer->setGuest(false);
        $salesChannelContext->assign([
            'token' => $loginResponse->getToken(),
            

        $context = $event->getContext();
        $salesChannelContext = $this->restorer->restoreByCustomer($customerId$context);

        if (!$customer = $salesChannelContext->getCustomer()) {
            return;
        }

        $customerChangePaymentMethodEvent = new CustomerChangedPaymentMethodEvent(
            $salesChannelContext,
            $customer,
            new RequestDataBag()
        );

        $this->dispatcher->dispatch($customerChangePaymentMethodEvent);
    }
}
$dispatcher = $this->getContainer()->get('event_dispatcher');

        $phpunit = $this;
        $eventDidRun = false;
        $listenerClosure = function DMailSentEvent $event) use (&$eventDidRun$phpunit): void {
            $eventDidRun = true;
            $phpunit->assertStringContainsString('Shipping costs: €0.00', $event->getContents()['text/html']);
        };

        $this->addEventListener($dispatcher, MailSentEvent::class$listenerClosure);

        $cartService->order($cart$contextnew RequestDataBag());

        $dispatcher->removeListener(MailSentEvent::class$listenerClosure);

        static::assertTrue($eventDidRun, 'The mail.sent Event did not run');
    }

    public function testCartCreatedWithGivenToken(): void
    {
        $salesChannelContextFactory = $this->getContainer()->get(SalesChannelContextFactory::class);
        $context = $salesChannelContextFactory->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL);

        
'id' => Uuid::randomHex(),
        ]);

        $salesChannelContext = $this->createSalesChannelContext(Uuid::randomHex()[
            'id' => Uuid::randomHex(),
        ], null);

        $this->createCustomer($email$salesChannel['id']);

        $loginRoute = $this->getContainer()->get(LoginRoute::class);

        $requestDataBag = new RequestDataBag(['email' => $email, 'password' => 'shopware']);

        $success = $loginRoute->login($requestDataBag$salesChannelContext);
        static::assertInstanceOf(ContextTokenResponse::class$success);

        $loginRoute->login($requestDataBag$salesChannelContext);
    }

    public function testLoginSuccessRestoreCustomerContext(): void
    {
        $email = Uuid::randomHex() . '@example.com';
        $customerId = $this->createCustomer($email);
        
$customer->setEmail('test@test.test');
        $customer->setHash('hash');
        $customer->setGuest(false);
        $customer->setDoubleOptInRegistration(true);
        $customer->setDoubleOptInEmailSentDate(new \DateTime());

        return $customer;
    }

    protected function mockRequestDataBag(): RequestDataBag
    {
        return new RequestDataBag([
            'hash' => 'hash',
            'em' => hash('sha1', 'test@test.test'),
        ]);
    }
}
#[Package('sales-channel')] class StoreApiCustomFieldMapperTest extends TestCase
{
    public function testMapping(): void
    {
        $connection = $this->createMock(Connection::class);
        $connection
            ->method('fetchAllAssociative')
            ->willReturn([['entity_name' => 'customer', 'name' => 'allowed']]);

        $mapper = new StoreApiCustomFieldMapper($connection);
        static::assertSame(['allowed' => 'yes']$mapper->map('customer', new RequestDataBag(['bla' => 'foo', 'allowed' => 'yes'])));
    }

    public function testInternalStorageWorks(): void
    {
        $connection = $this->createMock(Connection::class);
        $connection
            ->expects(static::exactly(2))
            ->method('fetchAllAssociative')
            ->willReturn([]);

        $mapper = new StoreApiCustomFieldMapper($connection);
        
$this->orderTransactionRepository = $this->getRepository(OrderTransactionDefinition::ENTITY_NAME);
        $this->paymentMethodRepository = $this->getRepository(PaymentMethodDefinition::ENTITY_NAME);
        $this->context = Context::createDefaultContext();
    }

    public function testHandlePreOrderPayment(): void
    {
        $paymentMethodId = $this->createPaymentMethod($this->context);
        $cart = Generator::createCart();
        $salesChannelContext = $this->getSalesChannelContext($paymentMethodId);

        $struct = $this->paymentService->handlePreOrderPayment($cartnew RequestDataBag()$salesChannelContext);

        static::assertInstanceOf(ArrayStruct::class$struct);
        static::assertSame(PreparedTestPaymentHandler::TEST_STRUCT_CONTENT, $struct->all());
    }

    public function testHandlePreOrderPaymentFails(): void
    {
        $paymentMethodId = $this->createPaymentMethod($this->context);
        $cart = Generator::createCart();
        $salesChannelContext = $this->getSalesChannelContext($paymentMethodId);
        PreparedTestPaymentHandler::$fail = true;

        
/** @var OrderEntity $order */
        $order = $this->orderRepository->search($criteria$this->salesChannelContext->getContext())->first();
        $deliveries = $order->getDeliveries();
        static::assertNotNull($deliveries);
        $delivery = $deliveries->first();
        static::assertNotNull($delivery);
        $orderDeliveryId = $delivery->getId();

        $this->orderService->orderDeliveryStateTransition(
            $orderDeliveryId,
            'ship',
            new RequestDataBag(),
            $this->salesChannelContext->getContext()
        );

        /** @var OrderEntity $updatedOrder */
        $updatedOrder = $this->orderRepository->search($criteria$this->salesChannelContext->getContext())->first();
        $deliveries = $updatedOrder->getDeliveries();
        static::assertNotNull($deliveries);
        $delivery = $deliveries->first();
        static::assertNotNull($delivery);
        static::assertNotNull($delivery->getStateMachineState());
        $updatedDeliveryState = $delivery->getStateMachineState()->getTechnicalName();

        
throw new DecorationPatternException(self::class);
    }

    #[Route(path: '/store-api/handle-payment', name: 'store-api.payment.handle', methods: ['GET', 'POST'])]     public function load(Request $request, SalesChannelContext $context): HandlePaymentMethodRouteResponse
    {
        $data = [...$request->query->all(), ...$request->request->all()];
        $this->dataValidator->validate($data$this->createDataValidation());

        $response = $this->paymentService->handlePaymentByOrder(
            $request->get('orderId'),
            new RequestDataBag($request->request->all()),
            $context,
            $request->get('finishUrl'),
            $request->get('errorUrl')
        );

        return new HandlePaymentMethodRouteResponse($response);
    }

    private function createDataValidation(): DataValidationDefinition
    {
        return (new DataValidationDefinition())
            
public function getDecorated(): AbstractRegisterRoute
    {
        throw new DecorationPatternException(self::class);
    }

    #[Route(path: '/store-api/account/register', name: 'store-api.account.register', methods: ['POST'])]     public function register(RequestDataBag $data, SalesChannelContext $context, bool $validateStorefrontUrl = true, ?DataValidationDefinition $additionalValidationDefinitions = null): CustomerResponse
    {
        $isGuest = $data->getBoolean('guest');

        if (!$data->has('billingAddress')) {
            $data->set('billingAddress', new RequestDataBag());
        }

        if ($data->has('accountType') && empty($data->get('accountType'))) {
            $data->remove('accountType');
        }

        if (!$data->get('salutationId')) {
            $data->set('salutationId', $this->getDefaultSalutationId($context));
        }

        $this->validateRegistrationData($data$isGuest$context$additionalValidationDefinitions$validateStorefrontUrl);

        
class NewsletterSubscribeRouteTest extends TestCase
{
    private SalesChannelContext $salesChannelContext;

    protected function setUp(): void
    {
        $this->salesChannelContext = $this->createMock(SalesChannelContext::class);
    }

    public function testSubscribeWithDOIEnabled(): void
    {
        $requestData = new RequestDataBag();
        $requestData->add([
            'email' => 'test@example.com',
            'option' => 'direct',
            'firstName' => 'Y',
            'lastName' => 'Tran',
        ]);

        $newsletterRecipientEntity = new NewsletterRecipientEntity();
        $newsletterRecipientEntity->setId(Uuid::randomHex());
        $newsletterRecipientEntity->setConfirmedAt(new \DateTime());

        
/** * @param array<int, string[]>|null $productDownloads */
    private function placeOrder(?array $productDownloads = null): string
    {
        $productDownloads ??= [[]];

        $cart = $this->cartService->createNew($this->salesChannelContext->getToken());
        $cart = $this->addProducts($cart$productDownloads);

        return $this->cartService->order($cart$this->salesChannelContext, new RequestDataBag());
    }

    /** * @param array<int, string[]> $productDownloads */
    private function assertOrderWithoutGrantedAccess(string $orderId, array $productDownloads): string
    {
        $criteria = new Criteria([$orderId]);
        $criteria->addAssociation('lineItems.downloads');
        $criteria->addAssociation('deliveries');

        
/** @var EventDispatcherInterface $dispatcher */
        $dispatcher = $this->getContainer()->get('event_dispatcher');
        $caughtEvent = null;
        $this->addEventListener(
            $dispatcher,
            MailBeforeSentEvent::class,
            static function DMailBeforeSentEvent $event) use (&$caughtEvent): void {
                $caughtEvent = $event;
            }
        );

        $data = new RequestDataBag([
            'title' => 'Lorem ipsum dolor sit amet',
            'content' => 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna',
            'points' => 3,
        ]);
        $this->getContainer()->get(ProductReviewSaveRoute::class)->save(
            $this->ids->get('product'),
            $data,
            $salesChannelContext
        );

        $this->resetEventDispatcher();

        
$response = $this->controller->confirmPage($request$context);

        static::assertEquals(new Response()$response);
    }

    public function testFinishPageNoCustomer(): void
    {
        $context = $this->createMock(SalesChannelContext::class);
        $context->method('getCustomer')->willReturn(null);

        $response = $this->controller->finishPage(new Request()$contextnew RequestDataBag());

        static::assertEquals(new RedirectResponse('url')$response);
    }

    public function testFinishPageOrderNotFound(): void
    {
        $context = $this->createMock(SalesChannelContext::class);
        $context->method('getCustomer')->willReturn(new CustomerEntity());

        $this->finishPageLoaderMock->method('load')->willThrowException(OrderException::orderNotFound('not-found'));

        


    public function testGetCustomerRecoveryNotFound(): void
    {
        $customerRecoveryRoute = $this->getContainer()->get(CustomerRecoveryIsExpiredRoute::class);

        $token = Uuid::randomHex();

        $context = $this->getContainer()->get(SalesChannelContextFactory::class)->create($token, TestDefaults::SALES_CHANNEL);

        static::expectException(CustomerNotFoundByHashException::class);
        $customerRecoveryRoute->load(new RequestDataBag(['hash' => Random::getAlphanumericString(32)])$context);
    }

    public function testGetCustomerRecoveryInvalidHash(): void
    {
        $customerRecoveryRoute = $this->getContainer()->get(CustomerRecoveryIsExpiredRoute::class);

        $token = Uuid::randomHex();

        $context = $this->getContainer()->get(SalesChannelContextFactory::class)->create($token, TestDefaults::SALES_CHANNEL);

        static::expectException(ConstraintViolationException::class);
        
Home | Imprint | This part of the site doesn't use cookies.