commercetools-8.x-1.2-alpha1/src/Controller/CommercetoolsCheckoutController.php
src/Controller/CommercetoolsCheckoutController.php
<?php
declare(strict_types=1);
namespace Drupal\commercetools\Controller;
use Drupal\commercetools\CommercetoolsCarts;
use Drupal\commercetools\CommercetoolsCustomers;
use Drupal\commercetools\Event\CommercetoolsOrderCreate;
use Drupal\Core\Access\AccessException;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
/**
* Returns responses for commercetools routes.
*/
final class CommercetoolsCheckoutController extends ControllerBase {
/**
* The controller constructor.
*/
public function __construct(
private readonly EventDispatcherInterface $eventDispatcher,
private readonly CommercetoolsCarts $ctCarts,
private readonly CommercetoolsCustomers $ctCustomers,
) {}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container): self {
return new self(
$container->get('event_dispatcher'),
$container->get('commercetools.carts'),
$container->get('commercetools.customers'),
);
}
/**
* Builds the response.
*/
public function checkoutComplete(Request $request): RedirectResponse|array {
if (!$request->query->has('orderId')) {
throw new AccessException();
}
$where = sprintf('id="%s"', $request->query->get('orderId'));
if ($this->currentUser()->isAuthenticated()) {
$customerId = $this->ctCustomers->getCurrentUserCustomerId();
$where .= ' and ' . sprintf('customerId="%s"', $customerId);
}
$orderListCacheable = $this->ctCarts->getOrders(['where' => $where], TRUE);
$orderList = $orderListCacheable->getData();
if (empty($orderList['results'])) {
throw new NotFoundHttpException();
}
[$order] = $orderList['results'];
// Dispatch the order creation event.
$event = new CommercetoolsOrderCreate($order);
$this->eventDispatcher->dispatch($event);
if ($request->query->has('destination')) {
$url = Url::fromUserInput($request->query->get('destination'), [
'absolute' => TRUE,
]);
return new RedirectResponse($url->toString());
}
return [];
}
}
