Last active
March 28, 2024 22:36
-
-
Save aklump/6e0286b26f674d0199922eb3e69933a1 to your computer and use it in GitHub Desktop.
Query conditions for dates with automatic timezone handling.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\se_core\Helpers; | |
use DateTimeInterface; | |
use DateTimeZone; | |
use Drupal\Core\Entity\Query\QueryInterface; | |
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface; | |
use Drupal\field\Entity\FieldStorageConfig; | |
use RuntimeException; | |
/** | |
* @code | |
* $now = date_create(); | |
* $date_condition = new \Drupal\se_core\Helpers\QueryAddDateCondition($query); | |
* $date_condition('field_dates.value', '<=', $now); | |
* $date_condition('field_dates.end_value', '>=', $now); | |
* @endcode | |
*/ | |
class QueryAddDateCondition { | |
/** | |
* @var \Drupal\Core\Entity\Query\QueryInterface | |
*/ | |
private QueryInterface $query; | |
public function __construct(QueryInterface $query) { | |
$this->query = $query; | |
} | |
/** | |
* Add a date query with automatic timezone handling. | |
* | |
* @param string $field_name | |
* @param \DateTimeInterface $date | |
* @param string $operator | |
* | |
* @return void | |
* | |
* @see \Drupal\datetime\Plugin\migrate\field\DateField | |
*/ | |
public function __invoke(string $field_name, string $operator, DateTimeInterface $date) { | |
$timezone = new DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE); | |
$format = $this->getStringFormat($field_name); | |
$value = (clone $date)->setTimeZone($timezone)->format($format); | |
$this->query->condition($field_name, $value, $operator); | |
} | |
private function getStringFormat(string $field_name): string { | |
list($base_field_name) = explode('.', $field_name); | |
$definition = FieldStorageConfig::loadByName($this->query->getEntityTypeId(), $base_field_name); | |
$date_type = $definition->getSetting('datetime_type'); | |
switch ($date_type) { | |
case 'date': | |
return DateTimeItemInterface::DATE_STORAGE_FORMAT; | |
case 'datetime': | |
return DateTimeItemInterface::DATETIME_STORAGE_FORMAT; | |
default: | |
throw new RuntimeException(sprintf("Cannot determine datetime_type for field: %s", $field_name)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment