clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,56 @@
<?php
namespace Drupal\farm_group\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Checks access for displaying Views of group members.
*/
class FarmGroupMembersViewsAccessCheck implements AccessInterface {
/**
* The asset storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $assetStorage;
/**
* FarmGroupMembersViewsAccessCheck constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->assetStorage = $entity_type_manager->getStorage('asset');
}
/**
* A custom access check.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
*/
public function access(RouteMatchInterface $route_match) {
// If there is no "asset" parameter, bail.
$asset_id = $route_match->getParameter('asset');
if (empty($asset_id)) {
return AccessResult::allowed();
}
// Allow access if the asset is a group.
/** @var \Drupal\asset\Entity\AssetInterface $asset */
$asset = $this->assetStorage->load($asset_id);
$access = AccessResult::allowedIf($asset->bundle() == 'group');
// Invalidate the access result when assets are changed.
$access->addCacheTags(["asset_list"]);
return $access;
}
}
@@ -0,0 +1,216 @@
<?php
namespace Drupal\farm_group\EventSubscriber;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\asset\Entity\AssetInterface;
use Drupal\farm_group\GroupMembershipInterface;
use Drupal\farm_location\EventSubscriber\LogEventSubscriber as LocationLogEventSubscriber;
use Drupal\log\Entity\LogInterface;
use Drupal\log\Event\LogEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Invalidate asset cache when group membership and group location changes.
*/
class LogEventSubscriber implements EventSubscriberInterface {
/**
* Cache tag invalidator service.
*
* @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
*/
protected CacheTagsInvalidatorInterface $cacheTagsInvalidator;
/**
* Datetime time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* Group membership service.
*
* @var \Drupal\farm_group\GroupMembershipInterface
*/
protected $groupMembership;
/**
* LogEventSubscriber Constructor.
*
* @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator
* Cache tag invalidator service.
* @param \Drupal\Component\Datetime\TimeInterface $date_time
* Datetime time service.
* @param \Drupal\farm_group\GroupMembershipInterface $group_membership
* Group membership service.
*/
public function __construct(CacheTagsInvalidatorInterface $cache_tags_invalidator, TimeInterface $date_time, GroupMembershipInterface $group_membership) {
$this->time = $date_time;
$this->cacheTagsInvalidator = $cache_tags_invalidator;
$this->groupMembership = $group_membership;
}
/**
* {@inheritdoc}
*
* @return array
* The event names to listen for, and the methods that should be executed.
*/
public static function getSubscribedEvents() {
return [
LogEvent::DELETE => 'logDelete',
LogEvent::PRESAVE => 'logPresave',
];
}
/**
* Perform actions on log delete.
*
* @param \Drupal\log\Event\LogEvent $event
* The log event.
*/
public function logDelete(LogEvent $event) {
$this->invalidateAssetCacheOnGroupAssignment($event->log);
$this->invalidateGroupMemberAssetCacheOnMovement($event->log);
}
/**
* Perform actions on log presave.
*
* @param \Drupal\log\Event\LogEvent $event
* The log event.
*/
public function logPresave(LogEvent $event) {
$this->invalidateAssetCacheOnGroupAssignment($event->log);
$this->invalidateGroupMemberAssetCacheOnMovement($event->log);
}
/**
* Invalidate asset caches when assets group membership changes.
*
* @param \Drupal\log\Entity\LogInterface $log
* The Log entity.
*/
protected function invalidateAssetCacheOnGroupAssignment(LogInterface $log): void {
// Keep track if we need to invalidate the cache of referenced assets so
// the computed 'group' field is updated.
$update_asset_cache = FALSE;
// If the log is an active group assignment, invalidate the cache.
if ($this->isActiveGroupAssignment($log)) {
$update_asset_cache = TRUE;
}
// If updating an existing group assignment log, invalidate the cache.
// This catches group assignment logs changing from done to pending.
if (!empty($log->original) && $this->isActiveGroupAssignment($log->original)) {
$update_asset_cache = TRUE;
}
// If an update is not necessary, bail.
if (!$update_asset_cache) {
return;
}
// Build a list of cache tags.
// @todo Only invalidate cache if the log changes the asset's current group. This might be different for each asset.
$tags = [];
// Include assets that were previously referenced.
if (!empty($log->original)) {
foreach ($log->original->get('asset')->referencedEntities() as $asset) {
array_push($tags, ...$asset->getCacheTags());
}
}
// Include assets currently referenced by the log.
foreach ($log->get('asset')->referencedEntities() as $asset) {
array_push($tags, ...$asset->getCacheTags());
}
// Invalidate the cache tags.
$this->cacheTagsInvalidator->invalidateTags($tags);
}
/**
* Invalidate group member cache when a group's location changes.
*
* @param \Drupal\log\Entity\LogInterface $log
* The Log entity.
*/
protected function invalidateGroupMemberAssetCacheOnMovement(LogInterface $log) {
// Keep track if we need to invalidate the cache of referenced assets so
// the computed 'location' and 'geometry' fields are updated.
$update_asset_cache = FALSE;
// If the log is a 'done' movement log, invalidate the cache.
if (LocationLogEventSubscriber::isActiveMovementLog($log)) {
$update_asset_cache = TRUE;
}
// If updating an existing 'done' movement log, invalidate the cache.
// This catches any movement logs changing from done to pending.
if (!empty($log->original) && LocationLogEventSubscriber::isActiveMovementLog($log->original)) {
$update_asset_cache = TRUE;
}
// If an update is not necessary, bail.
if (!$update_asset_cache) {
return;
}
// Build a list of cache tags.
// @todo Only invalidate cache if the movement log changes the group's current location. This might be different for each asset.
$tags = [];
// Include group assets that were previously referenced.
if (!empty($log->original)) {
// Get all group assets.
$group_assets = array_filter($log->original->get('asset')->referencedEntities(), function (AssetInterface $asset) {
return $asset->bundle() === 'group';
});
// Collect group member cache tags.
$member_tags = array_map(function (AssetInterface $asset) {
return $asset->getCacheTags();
}, $this->groupMembership->getGroupMembers($group_assets));
array_push($tags, ...array_merge(...$member_tags));
}
// Include group assets currently referenced by the log.
$group_assets = array_filter($log->get('asset')->referencedEntities(), function (AssetInterface $asset) {
return $asset->bundle() === 'group';
});
// Collect group member cache tags.
$member_tags = array_map(function (AssetInterface $asset) {
return $asset->getCacheTags();
}, $this->groupMembership->getGroupMembers($group_assets));
array_push($tags, ...array_merge(...$member_tags));
// Invalidate the cache tags.
$this->cacheTagsInvalidator->invalidateTags($tags);
}
/**
* Helper funtion to determine if a log is an active group assignment.
*
* Logs are an active group assignment if status = done,
* is_group_assignment = true, and the timestamp is not in the future.
*
* @param \Drupal\log\Entity\LogInterface $log
* The log to check.
*
* @return bool
* Boolean indicating if the log is an active group assignment.
*/
protected function isActiveGroupAssignment(LogInterface $log): bool {
return $log->get('status')->value == 'done' && $log->get('is_group_assignment')->value && $log->get('timestamp')->value <= $this->time->getCurrentTime();
}
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\farm_group;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Symfony\Component\DependencyInjection\Reference;
/**
* Override the asset.location service with our own class.
*/
class FarmGroupServiceProvider extends ServiceProviderBase implements ServiceProviderInterface {
/**
* {@inheritdoc}
*/
public function alter(ContainerBuilder $container) {
$definition = $container->getDefinition('asset.location');
$definition->addArgument(new Reference('group.membership'));
$definition->setClass('Drupal\farm_group\GroupAssetLocation');
}
}
@@ -0,0 +1,36 @@
<?php
namespace Drupal\farm_group\Field;
use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;
/**
* Computes the current group value for assets.
*/
class AssetGroupItemList extends EntityReferenceFieldItemList {
use ComputedItemListTrait;
/**
* Computes the current group value for the asset.
*/
protected function computeValue() {
// Get the asset entity.
$entity = $this->getEntity();
// Get the asset's current groups.
$groups = \Drupal::service('group.membership')->getGroup($entity);
// Update the assets current group values to match.
// @todo Cache this field computation.
foreach ($groups as $delta => $group) {
if (!empty($group->id())) {
$value = ['target_id' => $group->id()];
$this->list[$delta] = $this->createItem($delta, $value);
}
}
}
}
@@ -0,0 +1,151 @@
<?php
namespace Drupal\farm_group;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\asset\Entity\AssetInterface;
use Drupal\farm_location\AssetLocation;
use Drupal\farm_location\AssetLocationInterface;
use Drupal\farm_location\LogLocationInterface;
use Drupal\farm_log\LogQueryFactoryInterface;
use Drupal\log\Entity\LogInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Asset location logic, accounting for group membership.
*/
class GroupAssetLocation extends AssetLocation implements AssetLocationInterface {
/**
* Group membership service.
*
* @var \Drupal\farm_group\GroupMembershipInterface
*/
protected GroupMembershipInterface $groupMembership;
/**
* Class constructor.
*
* @param \Drupal\farm_location\LogLocationInterface $log_location
* Log location service.
* @param \Drupal\farm_log\LogQueryFactoryInterface $log_query_factory
* Log query factory.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* Entity type manager.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\Core\Database\Connection $database
* The database service.
* @param \Drupal\farm_group\GroupMembershipInterface $group_membership
* The group membership service.
*/
public function __construct(LogLocationInterface $log_location, LogQueryFactoryInterface $log_query_factory, EntityTypeManagerInterface $entity_type_manager, TimeInterface $time, Connection $database, GroupMembershipInterface $group_membership) {
parent::__construct($log_location, $log_query_factory, $entity_type_manager, $time, $database);
$this->groupMembership = $group_membership;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('log.location'),
$container->get('farm.log_query'),
$container->get('entity_type.manager'),
$container->get('datetime.time'),
$container->get('database'),
$container->get('group.membership')
);
}
/**
* {@inheritdoc}
*/
public function getMovementLog(AssetInterface $asset, $timestamp = NULL): ?LogInterface {
// Delegate to the parent service to get the latest movement log that
// references this asset.
$latest_movement = parent::getMovementLog($asset, $timestamp);
// Remember the latest movement id and timestamp.
$latest_id = 0;
$latest_timestamp = 0;
if (!empty($latest_movement)) {
$latest_id = $latest_movement->id();
$latest_timestamp = $latest_movement->get('timestamp')->value;
}
// Get the groups that this asset is assigned to.
$groups = $this->groupMembership->getGroup($asset, $timestamp);
// If there are groups, iterate through them.
if (!empty($groups)) {
foreach ($groups as $group) {
// Get the latest movement log that references the group.
$group_movement = parent::getMovementLog($group, $timestamp);
// If the group doesn't have a movement, skip it.
if (empty($group_movement)) {
continue;
}
// If the group's movement is the latest, replace the latest movement.
$group_movement_id = $group_movement->id();
$group_movement_timestamp = $group_movement->get('timestamp')->value;
if (($group_movement_timestamp > $latest_timestamp) || ($group_movement_timestamp == $latest_timestamp && $group_movement_id > $latest_id)) {
$latest_movement = $group_movement;
$latest_id = $group_movement_id;
$latest_timestamp = $group_movement_timestamp;
}
}
}
// Return the latest movement log.
return $latest_movement;
}
/**
* {@inheritdoc}
*/
public function getAssetsByLocation(array $locations, $timestamp = NULL): array {
// First delegate to the parent function to get assets in the location.
/** @var \Drupal\asset\Entity\AssetInterface[] $assets */
$assets = parent::getAssetsByLocation($locations, $timestamp);
// Recursively load all group members and add them to the list of assets.
$groups = array_filter($assets, function (AssetInterface $asset) {
return $asset->bundle() === 'group';
});
$assets += $this->groupMembership->getGroupMembers($groups, TRUE, $timestamp);
// Get location ids.
$location_ids = array_map(function (AssetInterface $location) {
return $location->id();
}, $locations);
// It is possible for a group member asset to be in a different location
// than the group, if it has a movement log that is more recent than the
// group's. So iterate through all the assets and remove any that are not in
// one of the specified locations. The asset may be in multiple locations
// (including this one), so we only want to remove it if none of its
// locations match.
$assets = array_filter($assets, function (AssetInterface $asset) use ($location_ids, $timestamp) {
// Get asset location ids.
$asset_location_ids = array_map(function (AssetInterface $location) {
return $location->id();
}, $this->getLocation($asset, $timestamp));
// Only include the asset if it is in one of the specified locations.
return !empty(array_intersect($location_ids, $asset_location_ids));
});
// Return the assets.
return $assets;
}
}
@@ -0,0 +1,230 @@
<?php
namespace Drupal\farm_group;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\asset\Entity\AssetInterface;
use Drupal\farm_log\LogQueryFactoryInterface;
use Drupal\log\Entity\LogInterface;
/**
* Asset group membership logic.
*/
class GroupMembership implements GroupMembershipInterface {
/**
* The name of the log group reference field.
*
* @var string
*/
const LOG_FIELD_GROUP = 'group';
/**
* Log query factory.
*
* @var \Drupal\farm_log\LogQueryFactoryInterface
*/
protected LogQueryFactoryInterface $logQueryFactory;
/**
* Entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected EntityTypeManagerInterface $entityTypeManager;
/**
* The time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* The database service.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* Class constructor.
*
* @param \Drupal\farm_log\LogQueryFactoryInterface $log_query_factory
* Log query factory.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* Entity type manager.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\Core\Database\Connection $database
* The database service.
*/
public function __construct(LogQueryFactoryInterface $log_query_factory, EntityTypeManagerInterface $entity_type_manager, TimeInterface $time, Connection $database) {
$this->logQueryFactory = $log_query_factory;
$this->entityTypeManager = $entity_type_manager;
$this->time = $time;
$this->database = $database;
}
/**
* {@inheritdoc}
*/
public function hasGroup(AssetInterface $asset, $timestamp = NULL): bool {
// Load the group assignment log. Bail if empty.
$log = $this->getGroupAssignmentLog($asset, $timestamp);
if (empty($log)) {
return FALSE;
}
// Return emptiness of the group references.
return !$log->get(static::LOG_FIELD_GROUP)->isEmpty();
}
/**
* {@inheritdoc}
*/
public function getGroup(AssetInterface $asset, $timestamp = NULL): array {
// Load the group assignment log. Bail if empty.
$log = $this->getGroupAssignmentLog($asset, $timestamp);
if (empty($log)) {
return [];
}
// Return referenced entities.
return $log->{static::LOG_FIELD_GROUP}->referencedEntities() ?? [];
}
/**
* {@inheritdoc}
*/
public function getGroupAssignmentLog(AssetInterface $asset, $timestamp = NULL): ?LogInterface {
// If the asset is new, no group assignment logs will reference it.
if ($asset->isNew()) {
return NULL;
}
// If $timestamp is NULL, use the current time.
if (is_null($timestamp)) {
$timestamp = $this->time->getRequestTime();
}
// Query for group assignment logs that reference the asset.
// We do not check access on the logs to ensure that none are filtered out.
$options = [
'asset' => $asset,
'timestamp' => $timestamp,
'status' => 'done',
'limit' => 1,
];
$query = $this->logQueryFactory->getQuery($options);
$query->condition('is_group_assignment', TRUE);
$query->accessCheck(FALSE);
$log_ids = $query->execute();
// Bail if no logs are found.
if (empty($log_ids)) {
return NULL;
}
// Load the first log.
/** @var \Drupal\log\Entity\LogInterface $log */
$log = $this->entityTypeManager->getStorage('log')->load(reset($log_ids));
// Return the log, if available.
if (!is_null($log)) {
return $log;
}
// Otherwise, return NULL.
return NULL;
}
/**
* {@inheritdoc}
*/
public function getGroupMembers(array $groups, bool $recurse = TRUE, $timestamp = NULL): array {
// Get group ids.
$group_ids = array_map(function (AssetInterface $group) {
return $group->id();
}, $groups);
// Bail if there are no group ids.
if (empty($group_ids)) {
return [];
}
// If $timestamp is NULL, use the current time.
if (is_null($timestamp)) {
$timestamp = $this->time->getRequestTime();
}
// Build query for group members.
$query = "
-- Select asset IDs from the asset base table.
SELECT a.id
FROM {asset} a
-- Inner join logs that reference the assets.
INNER JOIN {asset_field_data} afd ON afd.id = a.id
INNER JOIN {log__asset} la ON a.id = la.asset_target_id AND la.deleted = 0
INNER JOIN {log_field_data} lfd ON lfd.id = la.entity_id
-- Inner join group assets referenced by the logs.
INNER JOIN {log__group} lg ON lg.entity_id = lfd.id AND lg.deleted = 0
-- Left join ANY future group assignment logs for the same asset.
-- In the WHERE clause we'll exclude all records that have future logs,
-- leaving only the 'current' log entry.
LEFT JOIN (
{log_field_data} lfd2
INNER JOIN {log__asset} la2 ON la2.entity_id = lfd2.id AND la2.deleted = 0
) ON lfd2.is_group_assignment = 1 AND la2.asset_target_id = a.id
-- Future log entries have either a higher timestamp, or an equal timestamp and higher log ID.
AND (lfd2.timestamp > lfd.timestamp OR (lfd2.timestamp = lfd.timestamp AND lfd2.id > lfd.id))
-- Don't include future logs beyond the given timestamp.
-- These conditions should match the values in the WHERE clause.
AND (lfd2.status = 'done') AND (lfd2.timestamp <= :timestamp)
-- Limit results to completed membership assignment logs to the desired
-- group that took place before the given timestamp.
WHERE (lfd.is_group_assignment = 1) AND (lfd.status = 'done') AND (lfd.timestamp <= :timestamp) AND (lg.group_target_id IN (:group_ids[]))
-- Exclude records with future log entries.
AND lfd2.id IS NULL";
$args = [
':timestamp' => $timestamp,
':group_ids[]' => $group_ids,
];
$result = $this->database->query($query, $args)->fetchAll();
$asset_ids = [];
foreach ($result as $row) {
if (!empty($row->id)) {
$asset_ids[] = $row->id;
}
}
if (empty($asset_ids)) {
return [];
}
$asset_ids = array_unique($asset_ids);
/** @var \Drupal\asset\Entity\AssetInterface[] $assets */
$assets = $this->entityTypeManager->getStorage('asset')->loadMultiple($asset_ids);
if ($recurse) {
// Iterate through the assets to check if any of them are groups.
$groups = array_filter($assets, function (AssetInterface $asset) {
return $asset->bundle() === 'group';
});
// Use array_replace so that numeric keys are preserved.
$assets = array_replace($assets, $this->getGroupMembers($groups, $recurse, $timestamp));
}
return $assets;
}
}
@@ -0,0 +1,72 @@
<?php
namespace Drupal\farm_group;
use Drupal\asset\Entity\AssetInterface;
use Drupal\log\Entity\LogInterface;
/**
* Asset group membership logic.
*/
interface GroupMembershipInterface {
/**
* Check if an asset is a member of a group.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The Asset entity.
* @param int|null $timestamp
* Include logs with a timestamp less than or equal to this.
* If this is NULL (default), the current time will be used.
*
* @return bool
* Returns TRUE if the asset is a member of a group, FALSE otherwise.
*/
public function hasGroup(AssetInterface $asset, $timestamp = NULL): bool;
/**
* Get group assets that an asset is a member of.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The Asset entity.
* @param int|null $timestamp
* Include logs with a timestamp less than or equal to this.
* If this is NULL (default), the current time will be used.
*
* @return array
* Returns an array of assets.
*/
public function getGroup(AssetInterface $asset, $timestamp = NULL): array;
/**
* Find the latest group assignment log that references an asset.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The asset entity.
* @param int|null $timestamp
* Include logs with a timestamp less than or equal to this.
* If this is NULL (default), the current time will be used.
*
* @return \Drupal\log\Entity\LogInterface|null
* A log entity, or NULL if no logs were found.
*/
public function getGroupAssignmentLog(AssetInterface $asset, $timestamp = NULL): ?LogInterface;
/**
* Get assets that are members of groups.
*
* @param \Drupal\asset\Entity\AssetInterface[] $groups
* An array of group assets to lookup.
* @param bool $recurse
* Boolean: whether or not to recurse and load members of sub-groups.
* Defaults to TRUE.
* @param int|null $timestamp
* Include logs with a timestamp less than or equal to this.
* If this is NULL (default), the current time will be used.
*
* @return \Drupal\asset\Entity\AssetInterface[]
* An array of asset objects indexed by their IDs.
*/
public function getGroupMembers(array $groups, bool $recurse = TRUE, $timestamp = NULL): array;
}
@@ -0,0 +1,17 @@
<?php
namespace Drupal\farm_group\Plugin\Asset\AssetType;
use Drupal\farm_entity\Plugin\Asset\AssetType\FarmAssetType;
/**
* Provides the group asset type.
*
* @AssetType(
* id = "group",
* label = @Translation("Group"),
* )
*/
class Group extends FarmAssetType {
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\farm_group\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* Checks that a log is not creating a circular group membership.
*
* @Constraint(
* id = "CircularGroupMembership",
* label = @Translation("Circular group membership", context = "Validation"),
* )
*/
class CircularGroupMembershipConstraint extends Constraint {
/**
* The default violation message.
*
* @var string
*/
public $message = '%asset cannot be a member of itself.';
}
@@ -0,0 +1,107 @@
<?php
namespace Drupal\farm_group\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\farm_group\GroupMembershipInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the CircularGroupMembership constraint.
*/
class CircularGroupMembershipConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* Group membership service.
*
* @var \Drupal\farm_group\GroupMembershipInterface
*/
protected $groupMembership;
/**
* CircularGroupMembershipConstraintValidator constructor.
*
* @param \Drupal\farm_group\GroupMembershipInterface $group_membership
* Group membership service.
*/
public function __construct(GroupMembershipInterface $group_membership) {
$this->groupMembership = $group_membership;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('group.membership'),
);
}
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $value */
/** @var \Drupal\farm_group\Plugin\Validation\Constraint\CircularGroupMembershipConstraint $constraint */
// Get the log that this field is on.
$log = $value->getParent()->getValue();
// If the log is not a group assignment, we have nothing to validate.
if (empty($log->get('is_group_assignment')->value)) {
return;
}
// Get the group(s) that asset(s) are being made members of.
$groups = $log->get('group')->referencedEntities();
// If there are no groups, we have nothing to validate.
if (empty($groups)) {
return;
}
// Get the log's timestamp.
$timestamp = $log->get('timestamp')->value;
// Iterate through referenced entities.
foreach ($value->referencedEntities() as $delta => $asset) {
// If this asset is not a group, skip it.
if ($asset->bundle() != 'group') {
continue;
}
// Load members of this group (recursively).
$members = $this->groupMembership->getGroupMembers([$asset], TRUE, $timestamp);
// Iterate through the groups and look for violations.
$violation = FALSE;
foreach ($groups as $group) {
// Make sure that the asset and group are not the same.
if ($group->id() == $asset->id()) {
$violation = TRUE;
}
// Make sure that none of the group(s) are members of this asset.
foreach ($members as $member) {
if ($group->id() == $member->id()) {
$violation = TRUE;
break;
}
}
}
// If a violation was found, flag it.
if ($violation) {
$this->context->buildViolation($constraint->message, ['%asset' => $asset->label()])
->atPath((string) $delta . '.target_id')
->setInvalidValue($asset->id())
->addViolation();
}
}
}
}
@@ -0,0 +1,101 @@
<?php
namespace Drupal\farm_group\Plugin\views\argument;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\farm_group\GroupMembershipInterface;
use Drupal\views\Plugin\views\argument\ArgumentPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* An argument for filtering assets by their current group.
*
* @ingroup views_argument_handlers
*
* @ViewsArgument("asset_group")
*/
class AssetGroup extends ArgumentPluginBase {
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The group membership service.
*
* @var \Drupal\farm_group\GroupMembershipInterface
*/
protected $groupMembership;
/**
* Constructs an AssetGroup object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* @param \Drupal\farm_group\GroupMembershipInterface $group_membership
* The group membership service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, GroupMembershipInterface $group_membership) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->groupMembership = $group_membership;
}
/**
* {@inheritdoc}
*/
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('group.membership'),
);
}
/**
* {@inheritdoc}
*
* @see \Drupal\farm_location\Plugin\views\argument\AssetLocation
*/
public function query($group_by = FALSE) {
// First query for a list of asset IDs in the group, then use this list to
// filter the current View.
// We do this in two separate queries for a few reasons:
// 1. The Drupal and Views query APIs do not support the kind of compound
// JOIN that we use in the group.membership service's getMembers().
// 2. We need to allow other modules to override the group.membership
// service to provide their own location logic. They shouldn't have to
// override this Views argument handler as well.
// 3. It keeps this Views argument handler's query modifications very
// simple. It only needs the condition: "WHERE asset.id IN (:asset_ids)".
// See https://www.drupal.org/project/farm/issues/3217184 for more info.
$group = $this->entityTypeManager->getStorage('asset')->load($this->argument);
$assets = $this->groupMembership->getGroupMembers([$group]);
$asset_ids = [];
foreach ($assets as $asset) {
$asset_ids[] = $asset->id();
}
// If there are no asset IDs, add 0 to ensure the array is not empty.
if (empty($asset_ids)) {
$asset_ids[] = 0;
}
// Filter to only include assets with those IDs.
$this->ensureMyTable();
$this->query->addWhere(0, "$this->tableAlias.id", $asset_ids, 'IN');
}
}
@@ -0,0 +1,16 @@
<?php
namespace Drupal\farm_group\Plugin\views\field;
use Drupal\views\Plugin\views\field\EntityField;
/**
* A field that displays asset group.
*
* @ingroup views_field_handlers
*
* @ViewsField("asset_group")
*/
class AssetGroup extends EntityField {
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\farm_group\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Alter routes for the farm_group module.
*
* @ingroup farm
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
public function alterRoutes(RouteCollection $collection) {
// Add our _group_members_access requirement to
// view.farm_group_members.page.
if ($route = $collection->get('view.farm_group_members.page')) {
$route->setRequirement('_group_members_access', 'Drupal\farm_group\Access\FarmGroupMembersViewsAccessCheck::access');
}
}
}