View source
<?php
namespace Drupal\recently_read\Plugin\views\relationship;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\SessionManager;
use Drupal\views\Plugin\views\relationship\RelationshipPluginBase;
use Drupal\Core\Session\AccountProxy;
use Drupal\Core\PageCache\ResponsePolicy\KillSwitch;
use Drupal\Core\Config\CachedStorage;
use Symfony\Component\DependencyInjection\ContainerInterface;
class RecentlyReadRelationship extends RelationshipPluginBase {
protected $currentUser;
protected $killSwitch;
protected $cachedStorage;
protected $sessionManager;
public function __construct(array $configuration, $pluginId, $pluginDefinition, AccountProxy $currentUser, KillSwitch $killSwitch, CachedStorage $cachedStorage, SessionManager $sessionManager) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->currentUser = $currentUser;
$this->killSwitch = $killSwitch;
$this->cachedStorage = $cachedStorage;
$this->sessionManager = $sessionManager;
}
public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
return new static($configuration, $pluginId, $pluginDefinition, $container
->get('current_user'), $container
->get('page_cache_kill_switch'), $container
->get('config.storage'), $container
->get('session_manager'));
}
public function defineOptions() {
$options = parent::defineOptions();
$options['bundles'] = [
'default' => [],
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$entity_type = $this->definition['recently_read_type'];
$typesOptions = FALSE;
$types = $this->cachedStorage
->read('recently_read.recently_read_type.' . $entity_type)['types'];
if (isset($types) && !empty($types)) {
$typesOptions = array_combine($types, $types);
}
if ($typesOptions) {
$form['bundles'] = [
'#type' => 'checkboxes',
'#title' => $this
->t('Bundles'),
'#default_value' => $this->options['bundles'],
'#options' => $typesOptions,
];
}
}
public function query() {
parent::query();
$this
->ensureMyTable();
$basetable = $this->definition['base_table'];
$entity_type = $this->definition['recently_read_type'];
if ($this->options['required']) {
$this->query
->addWhere('recently_read', "recently_read_{$basetable}.type", $entity_type, "=");
}
if ($this->currentUser
->id() === 0) {
$this->killSwitch
->trigger();
$this->query
->addWhere('recently_read', "recently_read_{$basetable}.session_id", $this->sessionManager
->getId(), "=");
}
elseif ($this->options['required']) {
$this->query
->addWhere('recently_read', "recently_read_{$basetable}.user_id", $this->currentUser
->id(), "=");
}
if (!empty(array_filter($this->options['bundles']))) {
$this->query
->addWhere('recently_read', "{$basetable}.bundle", array_filter(array_values($this->options['bundles'])), "IN");
}
}
}