WishlistBlock.php in Commerce Wishlist 8.3
File
src/Plugin/Block/WishlistBlock.php
View source
<?php
namespace Drupal\commerce_wishlist\Plugin\Block;
use Drupal\commerce_wishlist\WishlistProviderInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
class WishlistBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $wishlistProvider;
public function __construct(array $configuration, $plugin_id, $plugin_definition, WishlistProviderInterface $wishlist_provider) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->wishlistProvider = $wishlist_provider;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('commerce_wishlist.wishlist_provider'));
}
public function build() {
$wishlist = $this->wishlistProvider
->getWishlist('default');
$count = $wishlist ? count($wishlist
->getItems()) : 0;
return [
'#theme' => 'commerce_wishlist_block',
'#count' => $count,
'#count_text' => $this
->formatPlural($count, '@count item', '@count items', [], [
'context' => 'wishlist block',
]),
'#wishlist_entity' => $wishlist,
'#url' => Url::fromRoute('commerce_wishlist.page'),
];
}
public function getCacheContexts() {
return Cache::mergeContexts(parent::getCacheContexts(), [
'wishlist',
]);
}
public function getCacheTags() {
$cache_tags = parent::getCacheTags();
$wishlist_cache_tags = [];
$wishlists = $this->wishlistProvider
->getWishlists();
foreach ($wishlists as $wishlist) {
$wishlist_cache_tags = Cache::mergeTags($wishlist_cache_tags, $wishlist
->getCacheTags());
}
return Cache::mergeTags($cache_tags, $wishlist_cache_tags);
}
}