Skip to content

Commit 0fc00dd

Browse files
committed
Make it more robust
1 parent c46d739 commit 0fc00dd

1 file changed

Lines changed: 11 additions & 31 deletions

File tree

src/Form/Extension/AddToCartTypeExtension.php

Lines changed: 11 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,10 @@
1919

2020
final class AddToCartTypeExtension extends AbstractTypeExtension
2121
{
22-
private GiftCardFactoryInterface $giftCardFactory;
23-
24-
private EntityManagerInterface $giftCardManager;
25-
2622
public function __construct(
27-
GiftCardFactoryInterface $giftCardFactory,
28-
EntityManagerInterface $giftCardManager,
23+
private readonly GiftCardFactoryInterface $giftCardFactory,
24+
private readonly EntityManagerInterface $giftCardManager,
2925
) {
30-
$this->giftCardFactory = $giftCardFactory;
31-
$this->giftCardManager = $giftCardManager;
3226
}
3327

3428
public static function getExtendedTypes(): iterable
@@ -41,7 +35,6 @@ public static function getExtendedTypes(): iterable
4135
public function buildForm(FormBuilderInterface $builder, array $options): void
4236
{
4337
$builder->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'reworkFormForGiftCard']);
44-
4538
$builder->addEventListener(FormEvents::POST_SUBMIT, [$this, 'populateCartItem']);
4639
}
4740

@@ -53,42 +46,29 @@ public function reworkFormForGiftCard(FormEvent $event): void
5346
return;
5447
}
5548

56-
$variant = $data->getCartItem()->getVariant();
57-
if (null === $variant) {
58-
return;
59-
}
60-
61-
/** @var ProductInterface|null $product */
62-
$product = $variant->getProduct();
63-
if (null === $product) {
49+
$product = $data->getCartItem()->getVariant()?->getProduct();
50+
if (!$product instanceof ProductInterface || !$product->isGiftCard()) {
6451
return;
6552
}
6653

67-
// If the product is a gift card, we add the GiftCardInformation fields
68-
if ($product->isGiftCard()) {
69-
$form = $event->getForm();
70-
$form->add('giftCardInformation', AddToCartGiftCardInformationType::class, [
71-
'product' => $product,
72-
]);
73-
}
54+
$form = $event->getForm();
55+
$form->add('giftCardInformation', AddToCartGiftCardInformationType::class, [
56+
'product' => $product,
57+
]);
7458
}
7559

7660
public function populateCartItem(FormEvent $event): void
7761
{
7862
/** @var AddToCartCommandInterface|null $data */
7963
$data = $event->getData();
80-
if (null === $data) {
64+
if (!$data instanceof AddToCartCommandInterface) {
8165
return;
8266
}
8367

8468
$cartItem = $data->getCartItem();
85-
/** @var ProductInterface|null $product */
86-
$product = $cartItem->getProduct();
87-
if (null === $product) {
88-
return;
89-
}
9069

91-
if (!$product->isGiftCard()) {
70+
$product = $cartItem->getVariant()?->getProduct();
71+
if (!$product instanceof ProductInterface || !$product->isGiftCard()) {
9272
return;
9373
}
9474

0 commit comments

Comments
 (0)