EntityAccessByField.php in Open Social 10.3.x
File
modules/custom/entity_access_by_field/src/Plugin/search_api/processor/EntityAccessByField.php
View source
<?php
namespace Drupal\entity_access_by_field\Plugin\search_api\processor;
use Drupal\Core\Session\AnonymousUserSession;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\LoggerTrait;
use Drupal\search_api\Plugin\search_api\processor\ContentAccess;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EntityAccessByField extends ContentAccess {
use LoggerTrait;
protected $database;
protected $currentUser;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$processor = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$processor
->setLogger($container
->get('logger.channel.search_api'));
$processor
->setDatabase($container
->get('database'));
$processor
->setCurrentUser($container
->get('current_user'));
return $processor;
}
public function addFieldValues(ItemInterface $item) {
static $anonymous_user;
if (!isset($anonymous_user)) {
$anonymous_user = new AnonymousUserSession();
}
$entity_type_id = $item
->getDatasource()
->getEntityTypeId();
if (!in_array($entity_type_id, [
'node',
])) {
return;
}
$node = $this
->getNode($item
->getOriginalObject());
if (!$node) {
return;
}
$field_definitions = $node
->getFieldDefinitions();
foreach ($field_definitions as $field_name => $field_definition) {
if ($field_definition
->getType() === 'entity_access_field') {
$realm = [
'view',
'node',
$node
->getType(),
$field_name,
];
$realm = implode('_', $realm);
$fields = $item
->getFields();
$fields = $this
->getFieldsHelper()
->filterForPropertyPath($fields, NULL, 'search_api_node_grants');
foreach ($fields as $field) {
$sql = 'SELECT gid, realm FROM {node_access} WHERE (nid = 0 OR nid = :nid) AND grant_view = 1 AND realm LIKE :realm';
$args = [
':nid' => $node
->id(),
':realm' => $this
->getDatabase()
->escapeLike($realm) . '%',
];
$grant_records = $this
->getDatabase()
->query($sql, $args)
->fetchAll();
if ($grant_records) {
foreach ($grant_records as $grant) {
$field
->addValue("node_access_{$grant->realm}:{$grant->gid}");
}
}
}
}
}
}
}