pm-4.1.x-dev/src/PmEtag.php
src/PmEtag.php
<?php
declare(strict_types=1);
namespace Drupal\pm;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
use Drupal\pm\Service\PmConfig;
use Drupal\pm\Service\PmHierarchy;
/**
* @todo Add class description.
*/
final class PmEtag implements PmEtagInterface {
/**
* The key-value storage.
*/
private readonly KeyValueStoreInterface $storage;
/**
* Constructs a PmEtag object.
*/
public function __construct(
private readonly EntityTypeManagerInterface $entityTypeManager,
private readonly KeyValueFactoryInterface $keyvalue,
private readonly PmConfig $pmConfig,
private readonly PmHierarchy $pmHierarchy,
) {
$this->storage = $this->keyvalue->get('pm_etag');
}
/**
* {@inheritdoc}
*/
private function get($category): ?int {
return $this->storage->get($category) ?: 0;
}
private function refresh($category): void {
$current_etag = $this->get($category);
$next_etag = $current_etag + 1;
$this->storage->set($category, $next_etag);
}
/**
* {@inheritdoc}
*/
public function handleEntityPresave(EntityInterface $entity): void {
$pm_entity = $entity;
while ($pm_entity instanceof PmContentEntityBaseInterface) {
if ($project = $pm_entity->getProject()) {
$this->updateEtagForEntity($project->getEntityTypeId(), $project->id());
}
$this->updateEtagForEntity($pm_entity->getEntityTypeId(), $pm_entity->id());
$pm_entity = $this->pmHierarchy->getParent($pm_entity);
}
}
private function updateEtagForEntity($entity_type, $entity_id) {
$this->refresh($entity_type . '.' . $entity_id);
}
public function getEtag($entity_type, $entity_id) {
return $this->get($entity_type . '.' . $entity_id);
}
}
