pm-4.1.x-dev/src/Service/PmKey.php
src/Service/PmKey.php
<?php
declare(strict_types=1);
namespace Drupal\pm\Service;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
use Drupal\pm\PmContentEntityBase;
/**
* @todo Add class description.
*/
final class PmKey implements PmKeyInterface {
/**
* The key-value storage.
*/
private readonly KeyValueStoreInterface $storage;
/**
* Constructs a PmKey object.
*/
public function __construct(
private readonly KeyValueFactoryInterface $keyValueFactory,
) {
$this->storage = $keyValueFactory->get('pm_key');
}
/**
* {@inheritdoc}
*/
public function generateNextKey(string $prefix): string {
$current_key = $this->storage->get($prefix);
if (empty($current_key)) {
$current_key = 0;
}
$next_key = $current_key + 1;
$this->storage->set($prefix, $next_key);
return $prefix . '-' . $next_key;
}
/**
* {@inheritdoc}
*/
public function handleEntityPresave(\Drupal\Core\Entity\EntityInterface $entity): void {
if (!$entity instanceof PmContentEntityBase) {
return;
}
if (!($entity->hasField('pm_key') && $entity->hasField('pm_project'))) {
return ;
}
$current_key = $entity->get('pm_key')->value;
$project = $entity->get('pm_project')->entity;
$project_key = trim($project->get('project_key')->value ?? '') ;
if ($current_key && str_starts_with($current_key, $project_key . '-')) {
// Bail out if current key is already following valid pattern.
return ;
}
$next_key = $this->generateNextKey($project_key);
$entity->set('pm_key', $next_key);
}
}
