2022-04-22 15:25:49 +00:00
|
|
|
<?php declare(strict_types = 1);
|
|
|
|
|
|
|
|
namespace Drupal\opencase;
|
|
|
|
use Drupal;
|
2022-05-15 15:13:53 +00:00
|
|
|
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
2022-05-15 17:49:02 +00:00
|
|
|
use Drupal\opencase\Utils;
|
2022-04-22 15:25:49 +00:00
|
|
|
|
|
|
|
final class TimeBasedFieldUpdater {
|
2022-05-15 15:13:53 +00:00
|
|
|
|
|
|
|
private EntityTypeManagerInterface $entityTypeManager;
|
2022-04-22 15:25:49 +00:00
|
|
|
private string $date_field;
|
|
|
|
private string $entity_type;
|
|
|
|
private array $conditions;
|
|
|
|
private string $date_format;
|
|
|
|
|
2022-05-15 17:49:02 +00:00
|
|
|
final public function __construct(
|
|
|
|
EntityTypeManagerInterface $entityTypeManager,
|
|
|
|
Utils $utils,
|
|
|
|
string $entity_type, string $bundle, string $date_field, string $date_format = 'Y-m-d'
|
|
|
|
)
|
2022-05-15 15:13:53 +00:00
|
|
|
{
|
|
|
|
$this->entityTypeManager = $entityTypeManager;
|
2022-05-15 17:49:02 +00:00
|
|
|
$this->utils = $utils;
|
2022-04-22 15:25:49 +00:00
|
|
|
$this->date_field = $date_field;
|
|
|
|
$this->date_format = $date_format;
|
|
|
|
$this->entity_type = $entity_type;
|
2022-05-15 17:49:02 +00:00
|
|
|
$this->bundle = $bundle;
|
2022-04-22 15:25:49 +00:00
|
|
|
}
|
|
|
|
|
2022-05-15 17:49:02 +00:00
|
|
|
final public function update(array $conditions, string $time_elapsed, array $new_values): void {
|
2022-05-15 15:13:53 +00:00
|
|
|
$query = $this->entityTypeManager->getStorage($this->entity_type)->getQuery();
|
2022-05-15 17:49:02 +00:00
|
|
|
$conditions[] = [$this->date_field, date($this->date_format, strtotime('-'.$time_elapsed)), "<"];
|
|
|
|
$conditions[] = ['type', $this->bundle, '='];
|
|
|
|
$this->utils->addConditionsToQuery($query, $conditions);
|
2022-04-22 15:25:49 +00:00
|
|
|
foreach($query->execute() as $id) {
|
2022-05-15 15:13:53 +00:00
|
|
|
$entity = $this->entityTypeManager->getStorage($this->entity_type)->load($id);
|
2022-04-22 15:25:49 +00:00
|
|
|
foreach($new_values as $new_field=>$new_value) {
|
2022-05-15 15:13:53 +00:00
|
|
|
$entity->$new_field = $new_value;
|
2022-04-22 15:25:49 +00:00
|
|
|
}
|
|
|
|
$entity->save();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|