ViewInclusion.php in Context 8
File
src/Plugin/Condition/ViewInclusion.php
View source
<?php
namespace Drupal\context\Plugin\Condition;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ViewInclusion extends ConditionPluginBase implements ContainerFactoryPluginInterface {
private $entityTypeManager;
private $currentRouteMatch;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManager $entityTypeManager, CurrentRouteMatch $currentRouteMatch) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entityTypeManager;
$this->currentRouteMatch = $currentRouteMatch;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('current_route_match'));
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$views = $this->entityTypeManager
->getStorage('view')
->loadMultiple();
$options = [];
foreach ($views as $key => $view) {
foreach ($view
->get('display') as $display) {
if ($display['display_plugin'] === 'page') {
$viewRoute = 'view-' . $key . '-' . $display['id'];
$options[$viewRoute] = $view
->label() . ' - ' . $display['display_title'];
}
}
}
$configuration = $this
->getConfiguration();
$form['views_pages'] = [
'#title' => $this
->t('Views pages'),
'#type' => 'select',
'#options' => $options,
'#multiple' => TRUE,
'#default_value' => isset($configuration['view_inclusion']) && !empty($configuration['view_inclusion']) ? array_keys($configuration['view_inclusion']) : [],
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['view_inclusion'] = array_filter($form_state
->getValue('views_pages'));
parent::submitConfigurationForm($form, $form_state);
}
public function summary() {
return t('Select views pages');
}
public function evaluate() {
$route = str_replace('.', '-', $this->currentRouteMatch
->getRouteName());
$configuration = $this
->getConfiguration();
if (array_key_exists('view_inclusion', $configuration) && !empty($configuration['view_inclusion'])) {
return in_array($route, $configuration['view_inclusion']);
}
return FALSE;
}
}