RefreshPageElementsHelper.php in Commerce Ajax Add to Cart 8
File
src/RefreshPageElementsHelper.php
View source
<?php
namespace Drupal\dc_ajax_add_cart;
use Drupal\Core\Ajax\RemoveCommand;
use Drupal\Core\Ajax\AppendCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\UpdateBuildIdCommand;
use Drupal\block\Entity\Block;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Theme\ThemeManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Block\BlockManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Render\Renderer;
use Drupal\Core\Render\RendererInterface;
class RefreshPageElementsHelper {
protected $response;
protected $themeManager;
protected $entityTypeManager;
protected $blockManager;
protected $renderer;
public function __construct(ThemeManagerInterface $theme_manager, EntityTypeManagerInterface $entity_type_manager, BlockManagerInterface $block_manager, RendererInterface $renderer) {
$this->themeManager = $theme_manager;
$this->entityTypeManager = $entity_type_manager;
$this->blockManager = $block_manager;
$this->renderer = $renderer;
$this->response = new AjaxResponse();
}
public static function create(ContainerInterface $container) {
return new static($container
->get('theme.manager'), $container
->get('entity.query'), $container
->get('plugin.manager.block'), $container
->get('renderer'));
}
public function getStatusMessagesBlockId() {
$active_theme = $this->themeManager
->getActiveTheme()
->getName();
$query = $this->entityTypeManager
->getStorage('block')
->getQuery();
$block_ids = $query
->condition('plugin', 'system_messages_block')
->condition('theme', $active_theme)
->execute();
return array_shift($block_ids);
}
public function updateStatusMessages() {
$block_id = $this
->getStatusMessagesBlockId();
if ($block_id) {
$block = Block::load($block_id);
$elements = [
'#type' => 'status_messages',
];
$this->response
->addCommand(new RemoveCommand('.messages__wrapper'));
$this->response
->addCommand(new AppendCommand(".region-{$block->getRegion()}", $this->renderer
->renderRoot($elements)));
}
return $this;
}
protected function getCartBlock() {
$block = $this->blockManager
->createInstance('commerce_cart', []);
return $block;
}
public function updateCart() {
$block = $this
->getCartBlock();
$this->response
->addCommand(new ReplaceCommand('.cart--cart-block', $block
->build()));
return $this;
}
public function updateFormBuildId(array $form) {
if (isset($form['#build_id_old']) && $form['#build_id_old'] !== $form['#build_id']) {
$this->response
->addCommand(new UpdateBuildIdCommand($form['#build_id_old'], $form['#build_id']));
}
return $this;
}
public function updatePageElements(array $form) {
return $this
->updateFormBuildId($form)
->updateStatusMessages()
->updateCart();
}
public function getResponse() {
return $this->response;
}
}