46 lines
1.6 KiB
PHP
46 lines
1.6 KiB
PHP
<?php declare(strict_types = 1);
|
|
|
|
namespace Drupal\opencase;
|
|
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
|
|
|
final class TimeBasedFieldUpdater {
|
|
|
|
private EntityTypeManagerInterface $entityTypeManager;
|
|
private string $date_field;
|
|
private string $entity_type;
|
|
private string $date_format;
|
|
private string $bundle;
|
|
|
|
final public function __construct(
|
|
EntityTypeManagerInterface $entityTypeManager,
|
|
string $entity_type, string $bundle, string $date_field, string $date_format = 'Y-m-d'
|
|
)
|
|
{
|
|
$this->entityTypeManager = $entityTypeManager;
|
|
$this->date_field = $date_field;
|
|
$this->date_format = $date_format;
|
|
$this->entity_type = $entity_type;
|
|
$this->bundle = $bundle;
|
|
}
|
|
|
|
final public function update(array $conditions, string $time_elapsed, array $new_values): void {
|
|
$query = $this->entityTypeManager->getStorage($this->entity_type)->getQuery();
|
|
$conditions[] = [$this->date_field, date($this->date_format, strtotime('-'.$time_elapsed)), "<"];
|
|
$conditions[] = ['type', $this->bundle, '='];
|
|
|
|
foreach ($conditions as $condition) {
|
|
$query->condition($condition[0], $condition[1], $condition[2] ?? "=");
|
|
}
|
|
foreach($query->execute() as $id) {
|
|
$this->updateEntity($id, $new_values);
|
|
}
|
|
}
|
|
private function updateEntity(string $entity_id, array $new_values): void {
|
|
$entity = $this->entityTypeManager->getStorage($this->entity_type)->load($entity_id);
|
|
foreach($new_values as $new_field=>$new_value) {
|
|
$entity->$new_field = $new_value;
|
|
}
|
|
$entity->save();
|
|
}
|
|
}
|