tv-1.0.x-dev/src/Plugin/Block/TVBlock.php
src/Plugin/Block/TVBlock.php
<?php
namespace Drupal\tv\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\node\Controller\NodeViewController;
use Drupal\node\Entity\Node;
use Drupal\tv\Service\TvChannelServiceInterface;
use Psr\Container\ContainerInterface;
/**
* Provides a 'TV' block.
*
* @Block(
* id = "tv",
* admin_label = @Translation("TV Block"),
* category = @Translation("Media")
* )
*/
class TVBlock extends BlockBase implements ContainerFactoryPluginInterface {
private TvChannelServiceInterface $tvChannelService;
private RouteMatchInterface $routeMatch;
public function __construct(array $configuration,
$plugin_id,
$plugin_definition,
RouteMatchInterface $routeMatch,
TvChannelServiceInterface $tvChannelService)
{
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->tvChannelService = $tvChannelService;
$this->routeMatch = $routeMatch;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_route_match'),
$container->get('tv.channel')
);
}
/**
* {@inheritdoc}
*/
public function build() {
$build = [];
$channel = $this->getChannel();
// Don't show the TV if there are no channel items.
if (!$this->tvChannelService->getItems($channel)) {
return $build;
}
// Build attributes.
$attributes['class'] = 'tv';
$attributes['data-base-url'] = \Drupal::request()->getSchemeAndHttpHost();;
if ($channel) {
$attributes['data-channel'] = $channel->id();
}
// Build the block.
$build[] = [
'#type' => 'container',
'#attributes' => $attributes,
'#attached' => [
'library' => [
'tv/tv_dev',
],
],
];
return $build;
}
private function getChannel(): ?Node {
$controller = $this->routeMatch->getRouteObject()->getDefault('_controller');
if ($controller != '\\' . NodeViewController::class . '::view') {
return NULL;
}
$node = $this->routeMatch->getParameter('node');
$bundle = $node->bundle();
if ($bundle != 'tv_channel') {
return NULL;
}
return $node;
}
private function getChannelNumber(): ?string
{
return $this->getChannel()?->id() ?? NULL;
}
public function getCacheTags() {
if ($node = $this->routeMatch->getParameter('node')) {
return Cache::mergeTags(parent::getCacheTags(), ['node:' . $node->id()]);
} else {
return parent::getCacheTags();
}
}
public function getCacheContexts() {
return Cache::mergeContexts(parent::getCacheContexts(), ['route']);
}
}
