Skip to content
Snippets Groups Projects

Add checking for view unpublished … content

Files

<?php
declare(strict_types=1);
namespace Drupal\drupalorg\Plugin\views\filter;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\Entity\NodeType;
use Drupal\node\Plugin\views\filter\Status;
use Drupal\views\Attribute\ViewsFilter;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Filter by published status.
*
* @ingroup views_filter_handlers
*/
#[ViewsFilter("drupalorg_node_status")]
class DrupalOrgNodeStatus extends Status implements ContainerFactoryPluginInterface {
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_user'),
);
}
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, private readonly AccountInterface $currentUser) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
/**
* {@inheritdoc}
*/
public function query() {
$table = $this->ensureMyTable();
$snippet = "$table.status = 1 OR ($table.uid = ***CURRENT_USER*** AND ***CURRENT_USER*** <> 0 AND ***VIEW_OWN_UNPUBLISHED_NODES*** = 1) OR ***BYPASS_NODE_ACCESS*** = 1";
if ($this->moduleHandler->moduleExists('content_moderation')) {
$snippet .= ' OR ***VIEW_ANY_UNPUBLISHED_NODES*** = 1';
}
$args = [
':unpublished_type_access[]' => [],
];
foreach (array_keys(NodeType::loadMultiple()) as $node_type_id) {
if ($this->currentUser->hasPermission("view any unpublished $node_type_id content")) {
$args[':unpublished_type_access[]'][] = $node_type_id;
}
}
if (!empty($args[':unpublished_type_access[]'])) {
$snippet .= ' OR ' . $table . '.type IN (:unpublished_type_access[])';
}
$this->query->addWhereExpression($this->options['group'], $snippet, $args);
}
}
Loading