depcalc-8.x-1.x-dev/tests/modules/depcalc_test/src/EventSubscriber/CalculateHash/SkipHashCalculation.php
tests/modules/depcalc_test/src/EventSubscriber/CalculateHash/SkipHashCalculation.php
<?php
namespace Drupal\depcalc_test\EventSubscriber\CalculateHash;
use Drupal\depcalc\DependencyCalculatorEvents;
use Drupal\depcalc\Event\CalculateHashEvent;
use Drupal\node\NodeInterface;
use Drupal\user\RoleInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Skip HashCalculation for fields under certain scenario.
*
* This is an example event subscriber which depicts, how
* particular fields from an entity can be skipped from
* hash calculation.
*/
class SkipHashCalculation implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events[DependencyCalculatorEvents::HASH_CALCULATION][] =
['onHashCalculation', 100];
return $events;
}
/**
* Removes fields of entity from hash calculation.
*
* @param \Drupal\depcalc\Event\CalculateHashEvent $event
* Hash calculation event.
*/
public function onHashCalculation(CalculateHashEvent $event): void {
// Removes label field of 'authenticated' user role from hash calculation.
if ($event->getEntity() instanceof RoleInterface && $event->getEntity()->id() === 'authenticated') {
$fields = $event->getHashSource();
unset($fields['label']);
$event->setHashSource($fields);
$event->stopPropagation();
}
// Removes title field of node entity from hash calculation.
if ($event->getEntity() instanceof NodeInterface) {
$fields = $event->getHashSource();
unset($fields['title']);
$event->setHashSource($fields);
$event->stopPropagation();
}
}
}
