commercetools-8.x-1.2-alpha1/modules/commercetools_content/src/Controller/CommercetoolsOrderController.php
modules/commercetools_content/src/Controller/CommercetoolsOrderController.php
<?php
namespace Drupal\commercetools_content\Controller;
use Drupal\commercetools\CommercetoolsCarts;
use Drupal\commercetools\CommercetoolsCustomers;
use Drupal\Core\Access\AccessException;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Defines a controller for the Commercetools order pages.
*/
class CommercetoolsOrderController extends ControllerBase {
/**
* The commercetools content carts service.
*
* @var \Drupal\commercetools\CommercetoolsCarts
*/
protected CommercetoolsCarts $ctCarts;
/**
* The Commercetools customers service.
*
* @var \Drupal\commercetools\CommercetoolsCustomers
*/
protected CommercetoolsCustomers $ctCustomers;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->ctCarts = $container->get('commercetools.carts');
$instance->ctCustomers = $container->get('commercetools.customers');
$instance->dateFormatter = $container->get('date.formatter');
return $instance;
}
/**
* Displays a page with the details of a Commercetools order.
*
* @param \Drupal\user\UserInterface $user
* The user.
* @param string $orderId
* The order id.
*
* @return array
* A render array.
*/
public function view(UserInterface $user, string $orderId): array {
if ($user->id() != $this->currentUser()->id()) {
throw new NotFoundHttpException();
}
$where = sprintf('id="%s"', $orderId);
if (!$this->currentUser()->isAnonymous()) {
$customer = $this->ctCustomers->getCustomerByUser($user);
$where .= ' and ' . sprintf('customerId="%s"', $customer['id']);
}
$orderListCacheable = $this->ctCarts->getOrders(['where' => $where], TRUE);
$orderList = $orderListCacheable->getData();
if (empty($orderList['results'])) {
throw new NotFoundHttpException();
}
[$order] = $orderList['results'];
if ($this->currentUser()->isAnonymous() && !empty($order['customerId'])) {
throw new AccessException();
}
$createdAt = new DrupalDateTime($order['createdAt'], new \DateTimeZone('UTC'));
$output = [
'#title' => isset($order['orderNumber'])
? $this->t('Order: #@orderNumber', ['@orderNumber' => $order['orderNumber']])
: $this->t('Order at @time', ['@time' => $this->dateFormatter->format($createdAt->getTimestamp())]),
'output' => [
'#theme' => 'commercetools_order_page',
'#order' => $order,
'#attributes' => ['class' => 'order'],
],
];
$orderListCacheable->getCacheableMetadata()->applyTo($output);
return $output;
}
}
