CartController.php in Commerce Core 8.2
File
modules/cart/src/Controller/CartController.php
View source
<?php
namespace Drupal\commerce_cart\Controller;
use Drupal\commerce_cart\CartProviderInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CartController extends ControllerBase {
protected $cartProvider;
public function __construct(CartProviderInterface $cart_provider) {
$this->cartProvider = $cart_provider;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('commerce_cart.cart_provider'));
}
public function cartPage() {
$build = [];
$cacheable_metadata = new CacheableMetadata();
$cacheable_metadata
->addCacheContexts([
'user',
'session',
]);
$carts = $this->cartProvider
->getCarts();
$carts = array_filter($carts, function ($cart) {
return $cart
->hasItems();
});
if (!empty($carts)) {
$cart_views = $this
->getCartViews($carts);
foreach ($carts as $cart_id => $cart) {
$build[$cart_id] = [
'#prefix' => '<div class="cart cart-form">',
'#suffix' => '</div>',
'#type' => 'view',
'#name' => $cart_views[$cart_id],
'#arguments' => [
$cart_id,
],
'#embed' => TRUE,
];
$cacheable_metadata
->addCacheableDependency($cart);
}
}
else {
$build['empty'] = [
'#theme' => 'commerce_cart_empty_page',
];
}
$build['#cache'] = [
'contexts' => $cacheable_metadata
->getCacheContexts(),
'tags' => $cacheable_metadata
->getCacheTags(),
'max-age' => $cacheable_metadata
->getCacheMaxAge(),
];
return $build;
}
protected function getCartViews(array $carts) {
$order_type_ids = array_map(function ($cart) {
return $cart
->bundle();
}, $carts);
$order_type_storage = $this
->entityTypeManager()
->getStorage('commerce_order_type');
$order_types = $order_type_storage
->loadMultiple(array_unique($order_type_ids));
$cart_views = [];
foreach ($order_type_ids as $cart_id => $order_type_id) {
$order_type = $order_types[$order_type_id];
$cart_views[$cart_id] = $order_type
->getThirdPartySetting('commerce_cart', 'cart_form_view', 'commerce_cart_form');
}
return $cart_views;
}
}