ErrorCollection example

/** * @internal * * @param ValidatorInterface[] $validators */
    public function __construct(private readonly iterable $validators)
    {
    }

    public function validate(ProductExportEntity $productExportEntity, string $productExportContent): array
    {
        $errors = new ErrorCollection();
        foreach ($this->validators as $validator) {
            $validator->validate($productExportEntity$productExportContent$errors);
        }

        return array_values($errors->getElements());
    }
}
class ManifestValidator
{
    /** * @param AbstractManifestValidator[] $validators */
    public function __construct(private readonly iterable $validators)
    {
    }

    public function validate(Manifest $manifest, Context $context): void
    {
        $errors = new ErrorCollection();
        foreach ($this->validators as $validator) {
            $errors->addErrors($validator->validate($manifest$context));
        }

        if ($errors->count() === 0) {
            return;
        }

        throw new AppValidationException($manifest->getMetadata()->getName()$errors);
    }
}
$idSearchResult = new IdSearchResult(
            1,
            [['data' => $country->getId(), 'primaryKey' => $country->getId()]],
            new Criteria(),
            Context::createDefaultContext()
        );
        $this->repository->method('searchIds')->willReturn($idSearchResult);

        $shippingLocation = new ShippingLocation($country, null, null);
        $context->method('getShippingLocation')->willReturn($shippingLocation);

        $errorCollection = new ErrorCollection();
        $this->validator->validate($cart$errorCollection$context);

        static::assertEquals(0, $errorCollection->count());

        $cart->add((new LineItem('b', 'test'))->setStates([State::IS_PHYSICAL]));

        $errorCollection = new ErrorCollection();
        $this->validator->validate($cart$errorCollection$context);

        static::assertEquals(1, $errorCollection->count());
    }

    
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\Log\Package;

/** * @internal only for use by the app-system */
#[Package('core')] class TranslationValidator extends AbstractManifestValidator
{
    public function validate(Manifest $manifest, ?Context $context): ErrorCollection
    {
        $errors = new ErrorCollection();
        $error = $manifest->getMetadata()->validateTranslations();

        if ($error !== null) {
            $errors->add($error);
        }

        return $errors;
    }
}
->method('getPaymentMethods')
            ->willReturn($collection);

        return $paymentMethodResponse;
    }

    /** * @param array<string> $blockedPaymentMethodNames */
    private function getErrorCollection(array $blockedPaymentMethodNames = []): ErrorCollection
    {
        $errorCollection = new ErrorCollection();

        foreach ($blockedPaymentMethodNames as $name) {
            $errorCollection->add(new PaymentMethodBlockedError($name, 'Payment method blocked'));
        }

        return $errorCollection;
    }

    private function getSalesChannelContext(bool $dontReturnDefaultPaymentMethod = false): SalesChannelContext
    {
        $salesChannel = new SalesChannelEntity();
        
/** * @internal * * @param CartValidatorInterface[] $validators */
    public function __construct(private readonly iterable $validators)
    {
    }

    public function validate(Cart $cart, SalesChannelContext $context): array
    {
        $errors = new ErrorCollection();
        foreach ($this->validators as $validator) {
            $validator->validate($cart$errors$context);
        }

        return array_values($errors->getElements());
    }
}
new LineItem('line-item-id-2', 'line-item-type-2'))
                ->setPrice(new CalculatedPrice(1, 1, new CalculatedTaxCollection()new TaxRuleCollection()))
                ->setLabel('line-item-label-2')
                ->assign(['uniqueIdentifier' => 'line-item-id-2'])
        );

        return $cart;
    }

    private function getCartErrorCollection(bool $blockShippingMethod = false, bool $blockPaymentMethod = false): ErrorCollection
    {
        $cartErrors = new ErrorCollection();
        if ($blockShippingMethod) {
            $cartErrors->add(
                new ShippingMethodBlockedError(
                    'original-shipping-method-name'
                )
            );
        }

        if ($blockPaymentMethod) {
            $cartErrors->add(
                new PaymentMethodBlockedError(
                    

    }

    /** * @return array<array<mixed>> */
    public static function errorDataProvider(): array
    {
        return [
            // One shipping method blocked is expected to be switched             [
                new ErrorCollection(
                    [
                        new ShippingMethodChangedError('Standard', 'Express'),
                    ]
                ),
                [
                    \sprintf(self::SHIPPING_METHOD_CHANGED_ERROR_CONTENT, 'Standard', 'Express'),
                ],
            ],
            // All shipping methods blocked expected to stay blocked             [
                new ErrorCollection(
                    [
public function testOrderCartException(): void
    {
        $request = new Request();
        $request->setSession($this->createMock(Session::class));

        $context = $this->createMock(SalesChannelContext::class);
        $context->method('getCustomer')->willReturn(new CustomerEntity());

        $this->orderServiceMock->expects(static::once())->method('createOrder')->willThrowException(
            CartException::invalidCart(
                new ErrorCollection(
                    [
                        new GenericCartError(
                            Uuid::randomHex(),
                            'message',
                            [],
                            1,
                            true,
                            false
                        ),
                    ]
                )
            )
use Shopware\Core\Checkout\Cart\Facade\ErrorsFacade;

/** * @internal * * @covers \Shopware\Core\Checkout\Cart\Facade\ErrorsFacade */
class ErrorsFacadeTest extends TestCase
{
    public function testPublicApiAvailable(): void
    {
        $facade = new ErrorsFacade(new ErrorCollection());

        $facade->warning('warning');
        $facade->error('error');
        $facade->notice('notice');

        static::assertCount(3, $facade);
        static::assertTrue($facade->has('warning'));
        static::assertTrue($facade->has('error'));
        static::assertTrue($facade->has('notice'));

        $facade->warning('duplicate');
        
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\Log\Package;

/** * @internal only for use by the app-system */
#[Package('core')] class AppNameValidator extends AbstractManifestValidator
{
    public function validate(Manifest $manifest, ?Context $context): ErrorCollection
    {
        $errors = new ErrorCollection();

        $appName = strtolower(substr($manifest->getPath()strrpos($manifest->getPath(), '/') + 1));

        if ($appName !== strtolower($manifest->getMetadata()->getName())) {
            $errors->add(new AppNameError($manifest->getMetadata()->getName()));
        }

        return $errors;
    }
}
$controller->setContainer($this->getContainer());
        $controller->setTemplateFinder($twig->getExtension(NodeExtension::class)->getFinder());

        $rendered = $controller->testRenderViewInheritance('@Storefront/storefront/page/plugin/index.html.twig');

        static::assertEquals('plugin', $rendered);
    }

    public static function cartProvider(): \Generator
    {
        $cart = new Cart('test');
        $cart->setErrors(new ErrorCollection(self::getErrors()));

        yield 'cart with salutation errors' => [
            $cart,
        ];
    }

    /** * @return array{ * 0: 'request_stack', * 1: ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, * 2: Stub&RequestStack * } */

        $mergeableLineItems = $guestCart->getLineItems()->filter(fn (LineItem $item) => ($item->getQuantity() > 0 && $item->isStackable()) || !$customerCart->has($item->getId()));

        $this->eventDispatcher->dispatch(new BeforeCartMergeEvent(
            $customerCart,
            $guestCart,
            $mergeableLineItems,
            $customerContext
        ));

        $errors = $customerCart->getErrors();
        $customerCart->setErrors(new ErrorCollection());

        $customerCartClone = clone $customerCart;
        $customerCart->setErrors($errors);
        $customerCartClone->setErrors($errors);

        $mergedCart = $this->cartService->add($customerCart$mergeableLineItems->getElements()$customerContext);

        $this->eventDispatcher->dispatch(new CartMergedEvent($mergedCart$customerContext$customerCartClone));

        return $mergedCart;
    }

    

  }

  /** * @covers ::normalize */
  public function testNormalizeException() {
    $normalized = $this
      ->container
      ->get('jsonapi.serializer')
      ->normalize(
        new JsonApiDocumentTopLevel(new ErrorCollection([new BadRequestHttpException('Lorem')])new NullIncludedData()new LinkCollection([])),
        'api_json',
        []
      )->getNormalization();
    $this->assertNotEmpty($normalized['errors']);
    $this->assertArrayNotHasKey('data', $normalized);
    $this->assertEquals(400, $normalized['errors'][0]['status']);
    $this->assertEquals('Lorem', $normalized['errors'][0]['detail']);
    $this->assertEquals([
      'info' => [
        'href' => 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1',
      ],
      

#[Package('checkout')] class ShippingMethodValidatorTest extends TestCase
{
    public function testValidateWithEmptyCart(): void
    {
        $cart = new Cart('test');

        $validator = new DeliveryValidator();
        $errors = new ErrorCollection();
        $validator->validate($cart$errors$this->createMock(SalesChannelContext::class));

        static::assertCount(0, $errors);
    }

    public function testValidateWithoutRules(): void
    {
        $deliveryTime = $this->generateDeliveryTimeDummy();

        $cart = new Cart('test');
        $context = $this->createMock(SalesChannelContext::class);
        
Home | Imprint | This part of the site doesn't use cookies.