DataBag example


class ReviewFormEventTest extends TestCase
{
    public function testInstance(): void
    {
        $context = Context::createDefaultContext();
        $salesChannelId = 'foo';
        $mailRecipientStruct = new MailRecipientStruct(['foo' => 'bar']);
        $data = new DataBag(['baz']);
        $productId = 'bar';
        $customerId = 'bar';

        $event = new ReviewFormEvent($context$salesChannelId$mailRecipientStruct$data$productId$customerId);

        static::assertEquals($context$event->getContext());
        static::assertEquals($salesChannelId$event->getSalesChannelId());
        static::assertEquals($mailRecipientStruct$event->getMailStruct());
        static::assertEquals($data->all()$event->getReviewFormData());
        static::assertEquals($productId$event->getProductId());
        static::assertEquals($customerId$event->getCustomerId());
    }
$validationEventName = 'framework.validation.contact_form.create';

        $this->addEventListener($dispatcher$validationEventName$validationListenerClosure);

        $systemConfig = $this->getContainer()->get(SystemConfigService::class);
        $systemConfig->set('core.basicInformation.firstNameFieldRequired', true);
        $systemConfig->set('core.basicInformation.lastNameFieldRequired', true);
        $systemConfig->set('core.basicInformation.phoneNumberFieldRequired', true);
        $systemConfig->set('core.basicInformation.email', 'doNotReply@example.com');

        $dataBag = new DataBag();
        $dataBag->add([
            'salutationId' => $this->getValidSalutationId(),
            'firstName' => 'Firstname',
            'lastName' => 'Lastname',
            'email' => 'test@shopware.com',
            'phone' => '12345/6789',
            'subject' => 'Subject',
            'comment' => 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',
        ]);

        $this->contactFormRoute->load($dataBag->toRequestDataBag()$context);

        
$request->attributes->get(SalesChannelRequest::ATTRIBUTE_DOMAIN_CURRENCY_ID),
                null,
                $originalContext
            )
        );

        return $salesChannelContext;
    }

    private function updateCustomerToContext(string $customerId, SalesChannelContext $context): void
    {
        $data = new DataBag();
        $data->set(self::CUSTOMER_ID, $customerId);

        $definition = new DataValidationDefinition('context_switch');
        $parameters = $data->only(
            self::CUSTOMER_ID
        );

        $customerCriteria = new Criteria();
        $customerCriteria->addFilter(new EqualsFilter('customer.id', $parameters[self::CUSTOMER_ID]));

        $definition
            
static::assertCount(0, $renderParams['messages']);
        static::assertArrayHasKey('page', $renderParams);
        static::assertArrayNotHasKey('formViolations', $renderParams);
        static::assertArrayNotHasKey('postedData', $renderParams);
    }

    public function testAddressBookWithConstraintViolation(): void
    {
        $context = Generator::createSalesChannelContext();
        $request = new Request();
        $dataBag = new RequestDataBag();
        $dataBag->set('address', new DataBag(['id' => Uuid::randomHex()]));

        $customer = new CustomerEntity();
        $customer->setId(Uuid::randomHex());

        $this->abstractUpsertAddressRoute
            ->expects(static::once())
            ->method('upsert')
            ->willThrowException(new ConstraintViolationException(new ConstraintViolationList()[]));

        $response = $this->controller->addressBook($request$dataBag$context$customer);
        static::assertEquals(Response::HTTP_OK, $response->getStatusCode());

        

    }

    /** * @throws ConstraintViolationException */
    private function validateOrderData(
        ParameterBag $data,
        SalesChannelContext $context,
        bool $hasVirtualGoods
    ): void {
        $definition = $this->getOrderCreateValidationDefinition(new DataBag($data->all())$context$hasVirtualGoods);
        $violations = $this->dataValidator->getViolations($data->all()$definition);

        if ($violations->count() > 0) {
            throw new ConstraintViolationException($violations$data->all());
        }
    }

    private function getOrderCreateValidationDefinition(
        DataBag $data,
        SalesChannelContext $context,
        bool $hasVirtualGoods
    ):
use Symfony\Component\HttpFoundation\Exception\BadRequestException;

/** * @internal * * @covers \Shopware\Core\Framework\Validation\DataBag\DataBag */
class DataBagTest extends TestCase
{
    public function testConversion(): void
    {
        $bag = new DataBag([
            '1' => 'a',
            '2' => 1,
            '3' => true,
            '4' => new DataBag(['a' => 'b']),
        ]);

        static::assertEquals([
            '1' => 'a',
            '2' => 1,
            '3' => true,
            '4' => ['a' => 'b'],
        ],
$this->validateBillingAddress($billingAddress$cart$context);
        $this->validateShippingAddress($shippingAddress$billingAddress$cart$context);
    }

    private function validateBillingAddress(
        ?CustomerAddressEntity $billingAddress,
        Cart $cart,
        SalesChannelContext $context
    ): void {
        $validation = $this->addressValidationFactory->create($context);
        $validationEvent = new BuildValidationEvent($validationnew DataBag()$context->getContext());
        $this->eventDispatcher->dispatch($validationEvent);

        if ($billingAddress === null) {
            return;
        }

        $violations = $this->validator->getViolations($billingAddress->jsonSerialize()$validation);

        if ($violations->count() > 0) {
            $cart->getErrors()->add(new AddressValidationError(true, $violations));
        }
    }
$definition->set('lastName', new NotBlank()new Regex([
                'pattern' => self::DOMAIN_NAME_REGEX,
                'match' => false,
            ]));
        }

        $required = $this->systemConfigService->get('core.basicInformation.phoneNumberFieldRequired', $context->getSalesChannel()->getId());
        if ($required) {
            $definition->add('phone', new NotBlank());
        }

        $validationEvent = new BuildValidationEvent($definitionnew DataBag()$context->getContext());
        $this->eventDispatcher->dispatch($validationEvent$validationEvent->getName());

        return $definition;
    }
}
public function testLoginBeforeEventNotDispatchedIfNoCredentialsGiven(): void
    {
        /** @var TraceableEventDispatcher $dispatcher */
        $dispatcher = $this->getContainer()->get('event_dispatcher');

        $eventDidRun = false;

        $listenerClosure = $this->getEmailListenerClosure($eventDidRun);
        $this->addEventListener($dispatcher, CustomerBeforeLoginEvent::class$listenerClosure);

        $dataBag = new DataBag();
        $dataBag->add([
            'username' => '',
            'password' => 'shopware',
        ]);

        try {
            $this->loginRoute->login($dataBag->toRequestDataBag()$this->salesChannelContext);
            $this->accountService->login('', $this->salesChannelContext);
        } catch (BadCredentialsException) {
            // nth         }
        
return;
        }

        $mailTemplate = $this->getMailTemplate($eventConfig['mailTemplateId']$flow->getContext());

        if ($mailTemplate === null) {
            return;
        }

        $injectedTranslator = $this->injectTranslator($flow->getContext()$flow->getData(MailAware::SALES_CHANNEL_ID));

        $data = new DataBag();

        /** @var MailRecipientStruct $mailStruct */
        $mailStruct = $flow->getData(MailAware::MAIL_STRUCT);

        $recipients = $this->getRecipients(
            $eventConfig['recipient'],
            $mailStruct->getRecipients(),
            $flow->getData(FlowMailVariables::CONTACT_FORM_DATA, []),
        );

        if (empty($recipients)) {
            

    private ReviewFormDataStorer $storer;

    protected function setUp(): void
    {
        Feature::skipTestIfActive('v6.6.0.0', $this);
        $this->storer = new ReviewFormDataStorer();
    }

    public function testStoreAware(): void
    {
        $event = new ReviewFormEvent(Context::createDefaultContext(), '', new MailRecipientStruct([])new DataBag(), '', '');
        $stored = [];
        $stored = $this->storer->store($event$stored);
        static::assertArrayHasKey(ReviewFormDataAware::REVIEW_FORM_DATA, $stored);
    }

    public function testStoreNotAware(): void
    {
        $event = $this->createMock(TestFlowBusinessEvent::class);
        $stored = [];
        $stored = $this->storer->store($event$stored);
        static::assertArrayNotHasKey(ReviewFormDataAware::REVIEW_FORM_DATA, $stored);
    }
$config = [
            'mailTemplateId' => $mailTemplateId,
            'recipient' => [
                'type' => 'admin',
                'data' => [
                    'phuoc.cao@shopware.com' => 'shopware',
                    'phuoc.cao.x@shopware.com' => 'shopware',
                ],
            ],
        ];

        $event = new ContactFormEvent($context, TestDefaults::SALES_CHANNEL, new MailRecipientStruct(['test@example.com' => 'Shopware ag'])new DataBag());

        $mailService = new TestEmailService();
        $subscriber = new SendMailAction(
            $mailService,
            $this->getContainer()->get('mail_template.repository'),
            $this->getContainer()->get('logger'),
            $this->getContainer()->get('event_dispatcher'),
            $this->getContainer()->get('mail_template_type.repository'),
            $this->getContainer()->get(Translator::class),
            $this->getContainer()->get(Connection::class),
            $this->getContainer()->get(LanguageLocaleCodeProvider::class),
            

#[Package('buyers-experience')] class ContactFormEventTest extends TestCase
{
    public function testScalarValuesCorrectly(): void
    {
        $event = new ContactFormEvent(
            Context::createDefaultContext(),
            'sales-channel-id',
            new MailRecipientStruct(['foo', 'bar']),
            new DataBag(['foo' => 'bar', 'bar' => 'baz'])
        );

        $storer = new ScalarValuesStorer();

        $stored = $storer->store($event[]);

        $flow = new StorableFlow('foo', Context::createDefaultContext()$stored);

        $storer->restore($flow);

        static::assertArrayHasKey('contactFormData', $flow->data());
        
private MockObject&EventDispatcherInterface $dispatcher;

    protected function setUp(): void
    {
        $this->repository = $this->createMock(EntityRepository::class);
        $this->dispatcher = $this->createMock(EventDispatcherInterface::class);
        $this->storer = new ProductStorer($this->repository, $this->dispatcher);
    }

    public function testStoreWithAware(): void
    {
        $event = new ReviewFormEvent(Context::createDefaultContext(), '', new MailRecipientStruct([])new DataBag(), '', '');
        $stored = [];
        $stored = $this->storer->store($event$stored);
        static::assertArrayHasKey(ProductAware::PRODUCT_ID, $stored);
    }

    public function testStoreWithNotAware(): void
    {
        $event = $this->createMock(CustomerRegisterEvent::class);
        $stored = [];
        $stored = $this->storer->store($event$stored);
        static::assertArrayNotHasKey(ProductAware::PRODUCT_ID, $stored);
    }
class FlowSendMailActionEventTest extends TestCase
{
    public function testGetContextWithFlowEvent(): void
    {
        $event = $this->createMock(StorableFlow::class);
        $event->expects(static::once())
            ->method('getContext')
            ->willReturn(Context::createDefaultContext());

        $mailTemplate = new MailTemplateEntity();

        $mailEvent = new FlowSendMailActionEvent(new DataBag()$mailTemplate$event);
        $context = $mailEvent->getContext();

        static::assertEquals($context, Context::createDefaultContext());
    }

    public function testGetDataBag(): void
    {
        $mailTemplate = new MailTemplateEntity();
        $flowEvent = $this->createMock(StorableFlow::class);

        $expectDataBag = new DataBag(['data' => 'data']);
        
Home | Imprint | This part of the site doesn't use cookies.