commercetools-8.x-1.2-alpha1/modules/commercetools_content/src/Plugin/Block/CommercetoolsContentCartSummaryBlock.php
modules/commercetools_content/src/Plugin/Block/CommercetoolsContentCartSummaryBlock.php
<?php
namespace Drupal\commercetools_content\Plugin\Block;
use Drupal\commercetools\CommercetoolsCarts;
use Drupal\commercetools\Plugin\Block\CommercetoolsBlockBase;
use Drupal\commercetools_content\Form\ContentSettingsForm;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides the Commercetools Content Cart Summary block.
*
* @Block(
* id = "commercetools_content_cart_summary",
* admin_label = @Translation("Cart Summary"),
* )
*/
class CommercetoolsContentCartSummaryBlock extends CommercetoolsBlockBase {
/**
* The container.
*
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
protected ContainerInterface $container;
/**
* The commercetools cart service.
*
* @var \Drupal\commercetools\CommercetoolsCarts
*/
protected CommercetoolsCarts $ctCarts;
/**
* Default number of items to display.
*/
protected const MAX_ITEMS_DEFAULT = 5;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $configuration, $plugin_id, $plugin_definition) {
$instance = new static($configuration, $plugin_id, $plugin_definition);
$instance->container = $container;
$instance->ctCarts = $container->get('commercetools.carts');
return $instance;
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form = parent::blockForm($form, $form_state);
$config = $this->getConfiguration();
$form['max_items'] = [
'#type' => 'number',
'#title' => $this->t('Number of items to display'),
'#description' => $this->t('The number of items to display in the cart summary.'),
'#default_value' => $config['max_items'] ?? self::MAX_ITEMS_DEFAULT,
'#min' => 1,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
parent::blockSubmit($form, $form_state);
$this->setConfigurationValue('max_items', $form_state->getValue('max_items'));
}
/**
* {@inheritdoc}
*/
public function buildSafe(): array {
$cartData = $this->ctCarts->getCurrentCart();
$output = [
'#theme' => 'commercetools_cart_summary_block',
'#cart' => [
'totalLineItemQuantity' => 0,
'lineItems' => [],
],
'#max_items' => $this->getConfiguration()['max_items'] ?? self::MAX_ITEMS_DEFAULT,
];
if ($cartData) {
$output['#cart'] = $cartData->getData();
$cartData->getCacheableMetadata()
->applyTo($output);
}
return $output;
}
/**
* {@inheritdoc}
*/
public function getCacheContexts() {
$cacheContexts = parent::getCacheContexts();
return Cache::mergeContexts($cacheContexts, [
'commercetools_cart',
]);
}
/**
* {@inheritdoc}
*/
public function getCacheTags(): array {
$cacheTags = parent::getCacheTags();
return Cache::mergeTags($cacheTags, [
'config:' . ContentSettingsForm::CONFIGURATION_NAME,
]);
}
}
