This repository has been archived on 2022-07-12. You can view files and clone it, but cannot push or open issues or pull requests.
opencase/src/TimeBasedFieldUpdater.php

46 lines
1.6 KiB
PHP
Raw Normal View History

<?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;
2022-05-16 16:25:58 +00:00
private string $bundle;
final public function __construct(
2022-05-27 09:24:04 +00:00
EntityTypeManagerInterface $entityTypeManager,
string $entity_type, string $bundle, string $date_field, string $date_format = 'Y-m-d'
)
2022-05-27 09:24:04 +00:00
{
$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, '='];
2022-05-27 09:24:04 +00:00
2022-05-27 08:52:56 +00:00
foreach ($conditions as $condition) {
2022-05-27 09:24:04 +00:00
$query->condition($condition[0], $condition[1], $condition[2] ?? "=");
2022-05-27 08:52:56 +00:00
}
foreach($query->execute() as $id) {
2022-05-16 16:25:58 +00:00
$this->updateEntity($id, $new_values);
2022-05-27 09:24:04 +00:00
}
}
2022-05-16 16:25:58 +00:00
private function updateEntity(int $entity_id, array $new_values): void {
$entity = $this->entityTypeManager->getStorage($this->entity_type)->load($entity_id);
foreach($new_values as $new_field=>$new_value) {
2022-05-27 09:24:04 +00:00
$entity->$new_field = $new_value;
2022-05-16 16:25:58 +00:00
}
$entity->save();
}
2022-05-27 09:24:04 +00:00
}