Skip to content

Commit 7418098

Browse files
committed
WIP
1 parent d4e5dae commit 7418098

File tree

7 files changed

+119
-17
lines changed

7 files changed

+119
-17
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
"psr/http-client": "^1.0",
1414
"sylius-labs/doctrine-migrations-extra-bundle": "^0.2",
1515
"sylius/sylius": "~2.0.1",
16-
"symfony/mailer": "^6.4 || ^7.1"
16+
"symfony/mailer": "^6.4 || ^7.1",
17+
"symfony/ux-live-component": "v2.22.1"
1718
},
1819
"require-dev": {
1920
"behat/behat": "^3.6.1",

config/routes/shop.yaml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,17 @@ sylius_paypal_shop_payment_error:
7575
methods: [POST]
7676
defaults:
7777
_controller: sylius_paypal.controller.paypal_payment_on_error
78+
79+
sylius_paypal_shop_add_to_cart:
80+
path: /paypal-add-to-cart/{productId}
81+
methods: [POST]
82+
defaults:
83+
_controller: sylius_paypal.controller.add_to_cart
84+
_sylius:
85+
factory:
86+
method: createForProduct
87+
arguments: [ expr:notFoundOnNull(service('sylius.repository.product').find($productId)) ]
88+
form:
89+
type: Sylius\Bundle\CoreBundle\Form\Type\Order\AddToCartType
90+
options:
91+
product: expr:notFoundOnNull(service('sylius.repository.product').find($productId))

config/services/controller.xml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,5 +140,25 @@
140140
<argument type="service" id="request_stack" />
141141
<argument type="service" id="monolog.logger.paypal" />
142142
</service>
143+
144+
<service id="sylius_paypal.controller.add_to_cart" class="Sylius\PayPalPlugin\Controller\AddToCartAction">
145+
<argument type="service" id="sylius.factory.add_to_cart_command" />
146+
<argument type="service" id="sylius.context.cart.new" />
147+
<argument type="service" id="doctrine.orm.entity_manager" />
148+
<argument type="service" id="sylius.factory.order_item" />
149+
<argument type="service" id="form.factory" />
150+
<argument type="service">
151+
<service class="Sylius\Component\Resource\Metadata\MetadataInterface">
152+
<factory service="sylius.resource_registry" method="get" />
153+
<argument type="string">sylius.order_item</argument>
154+
</service>
155+
</argument>
156+
<argument type="service" id="sylius.resource_controller.new_resource_factory" />
157+
<argument type="service" id="sylius.modifier.order_item_quantity" />
158+
<argument type="service" id="sylius.modifier.order" />
159+
<argument type="service" id="sylius.resource_controller.request_configuration_factory" />
160+
<argument type="service" id="router" />
161+
</service>
162+
143163
</services>
144164
</container>

src/Controller/AddToCartAction.php

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Sylius\PayPalPlugin\Controller;
6+
7+
use Doctrine\ORM\EntityManagerInterface;
8+
use Sylius\Bundle\OrderBundle\Controller\AddToCartCommandInterface;
9+
use Sylius\Bundle\OrderBundle\Factory\AddToCartCommandFactoryInterface;
10+
use Sylius\Bundle\ResourceBundle\Controller\NewResourceFactoryInterface;
11+
use Sylius\Bundle\ResourceBundle\Controller\RequestConfigurationFactoryInterface;
12+
use Sylius\Component\Order\Context\CartContextInterface;
13+
use Sylius\Component\Order\Model\OrderItemInterface;
14+
use Sylius\Component\Order\Modifier\OrderItemQuantityModifierInterface;
15+
use Sylius\Component\Order\Modifier\OrderModifierInterface;
16+
use Sylius\Component\Resource\Factory\FactoryInterface;
17+
use Sylius\Resource\Metadata\MetadataInterface;
18+
use Symfony\Component\Form\FormFactoryInterface;
19+
use Symfony\Component\HttpFoundation\RedirectResponse;
20+
use Symfony\Component\HttpFoundation\Request;
21+
use Symfony\Component\HttpFoundation\Response;
22+
use Symfony\Component\Routing\RouterInterface;
23+
24+
final readonly class AddToCartAction
25+
{
26+
public function __construct(
27+
private AddToCartCommandFactoryInterface $addToCartCommandFactory,
28+
private CartContextInterface $cartContext,
29+
private EntityManagerInterface $cartManager,
30+
private FactoryInterface $factory,
31+
private FormFactoryInterface $formFactory,
32+
private MetadataInterface $metadata,
33+
private NewResourceFactoryInterface $newResourceFactory,
34+
private OrderItemQuantityModifierInterface $quantityModifier,
35+
private OrderModifierInterface $orderModifier,
36+
private RequestConfigurationFactoryInterface $requestConfigurationFactory,
37+
private RouterInterface $router,
38+
) {
39+
}
40+
41+
public function __invoke(Request $request): Response
42+
{
43+
$cart = $this->cartContext->getCart();
44+
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
45+
46+
/** @var OrderItemInterface $orderItem */
47+
$orderItem = $this->newResourceFactory->create($configuration, $this->factory);
48+
49+
$this->quantityModifier->modify($orderItem, 1);
50+
/** @var string $formType */
51+
$formType = $configuration->getFormType();
52+
53+
$form = $this->formFactory->create(
54+
$formType,
55+
$this->addToCartCommandFactory->createWithCartAndCartItem($cart, $orderItem),
56+
$configuration->getFormOptions(),
57+
);
58+
59+
$form = $form->handleRequest($request);
60+
61+
if ($form->isSubmitted() && !$form->isValid()) {
62+
return new RedirectResponse((string)$request->headers->get('referer'));
63+
}
64+
65+
/** @var AddToCartCommandInterface $addToCartCommand */
66+
$addToCartCommand = $form->getData();
67+
68+
$this->orderModifier->addToOrder($addToCartCommand->getCart(), $addToCartCommand->getCartItem());
69+
70+
$this->cartManager->persist($cart);
71+
$this->cartManager->flush();
72+
73+
return new RedirectResponse($this->router->generate('sylius_paypal_shop_create_paypal_order_from_cart', ['id' => $cart->getId()]));
74+
}
75+
76+
}

src/Controller/PayPalButtonsController.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ public function renderProductPageButtonsAction(Request $request): Response
5050
'available_countries' => $this->availableCountriesProvider->provide(),
5151
'clientId' => $this->payPalConfigurationProvider->getClientId($channel),
5252
'completeUrl' => $this->router->generate('sylius_shop_checkout_complete'),
53+
'createPayPalOrderFromProductUrl' => $this->router->generate('sylius_paypal_shop_add_to_cart', ['productId' => $request->attributes->getInt('productId')]),
5354
'errorPayPalPaymentUrl' => $this->router->generate('sylius_paypal_shop_payment_error'),
5455
'locale' => $this->localeProcessor->process($this->localeContext->getLocaleCode()),
5556
'processPayPalOrderUrl' => $this->router->generate('sylius_paypal_shop_process_paypal_order'),

templates/pay_from_product_page.html.twig

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
let orderId = null;
66
77
let completeUrl = "{{ completeUrl }}";
8-
let createPayPalOrderFromProductUrl = "{{ path('sylius_shop_live_component', {_live_component: 'sylius_shop:product:add_to_cart_form', _live_action: 'addToCart'}) }}"
8+
let createPayPalOrderFromProductUrl = "{{ createPayPalOrderFromProductUrl }}"
99
let processPayPalOrderUrl = "{{ processPayPalOrderUrl }}";
1010
let cancelPayPalOrderUrl = "{{ path('sylius_paypal_shop_cancel_order') }}";
1111
let errorPayPalPaymentUrl = "{{ errorPayPalPaymentUrl }}";
@@ -18,23 +18,13 @@
1818
label: 'checkout'
1919
},
2020
createOrder: function(data, actions) {
21-
const componentElement = document.querySelector('[data-live-name-value="sylius_shop:product:add_to_cart_form"]');
22-
const componentProps = JSON.parse(componentElement.dataset.livePropsValue);
23-
const requestData = JSON.stringify({
24-
props: componentProps,
25-
args: {routeName: 'sylius_paypal_shop_create_paypal_order_from_cart', idRouteParameter: 'id', addFlashMessage: false}
26-
});
27-
21+
let formData = new FormData(document.getElementsByName('sylius_shop_add_to_cart')[0]);
2822
return fetch(createPayPalOrderFromProductUrl, {
2923
method: 'post',
30-
headers: {
31-
'content-type': 'application/json',
32-
'Accept': 'application/vnd.live-component+html',
33-
'x-csrf-token': componentElement.dataset.liveCsrfValue,
34-
},
35-
body: JSON.stringify({ data: requestData})
24+
body: formData
3625
})
3726
.then(function(res) {
27+
console.log(res);
3828
document.querySelector('[data-live-name-value="sylius_shop:product:add_to_cart_form"] [data-loading]').style.display = 'block';
3929
return res.status === 400 ? window.location.reload() : res.json();
4030
})
@@ -67,7 +57,7 @@
6757
method: 'post',
6858
headers: {},
6959
body: error
70-
}).then(window.location.reload());
60+
}).then(console.log(error));
7161
},
7262
onShippingChange: function(data, actions) {
7363
if (!availableCountries.filter(country => country === data.shipping_address.country_code).length) {
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
<div data-live-ignore>
2-
{{ render(controller('sylius_paypal.controller.paypal_buttons::renderProductPageButtonsAction')) }}
2+
{{ render(controller('sylius_paypal.controller.paypal_buttons::renderProductPageButtonsAction', { productId: hookable_metadata.context.product.id })) }}
33
</div>

0 commit comments

Comments
 (0)