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

41 lines
1.6 KiB
PHP
Raw Normal View History

<?php declare(strict_types = 1);
namespace Drupal\opencase;
use Drupal;
use Drupal\Core\Entity\EntityTypeManagerInterface;
final class TimeBasedFieldUpdater {
private EntityTypeManagerInterface $entityTypeManager;
private string $date_field;
private string $entity_type;
private array $conditions;
private string $date_format;
final public function __construct(EntityTypeManagerInterface $entityTypeManager, string $entity_type, string $date_field, array $conditions = [], string $date_format = 'Y-m-d')
{
$this->entityTypeManager = $entityTypeManager;
$this->date_field = $date_field;
$this->conditions = $conditions;
$this->date_format = $date_format;
$this->entity_type = $entity_type;
}
final public function update(string $time_elapsed, array $old_values, array $new_values): void {
$query = $this->entityTypeManager->getStorage($this->entity_type)->getQuery();
foreach($this->conditions as $cond_field=>$cond_value) {
$query->condition($cond_field, $cond_value);
}
foreach($old_values as $old_field=>$old_value) {
$query->condition($old_field, $old_value);
}
$query->condition($this->date_field, date($this->date_format, strtotime('-'.$time_elapsed)), "<");
foreach($query->execute() as $id) {
$entity = $this->entityTypeManager->getStorage($this->entity_type)->load($id);
foreach($new_values as $new_field=>$new_value) {
$entity->$new_field = $new_value;
}
$entity->save();
}
}
}