access_policy-1.0.x-dev/src/AccessRuleQueryHandler/EntityFieldDate.php

src/AccessRuleQueryHandler/EntityFieldDate.php
<?php

namespace Drupal\access_policy\AccessRuleQueryHandler;

/**
 * Entity field date access rule query handler.
 */
class EntityFieldDate extends EntityFieldBase {

  /**
   * {@inheritdoc}
   */
  public function operators() {
    return [
      '=' => [
        'method' => 'opSimple',
      ],
      '!=' => [
        'method' => 'opSimple',
      ],
      '<' => [
        'method' => 'opSimple',
      ],
      '<=' => [
        'method' => 'opSimple',
      ],
      '>=' => [
        'method' => 'opSimple',
      ],
      '>' => [
        'method' => 'opSimple',
      ],
    ];
  }

  /**
   * Simple operator for handling numeric values.
   *
   * @param array $values
   *   The current values.
   * @param \Drupal\access_policy\QueryInterface|\Drupal\Core\Database\Query\ConditionInterface $query
   *   The query or condition object.
   */
  public function opSimple(array $values, $query) {
    $operator = $this->getOperator();

    foreach ($values as $value) {
      switch ($this->definition->getSetting('type')) {
        case 'date':
          $value = $this->getDate($value);
          break;

        case 'relative':
          $value = $this->getRelativeDate($value);
          break;
      }

      $query->condition($this->realField, $value, $operator);
    }
  }

  /**
   * Get the properly formatted date.
   *
   * @param mixed $value
   *   The current value.
   *
   * @return mixed
   *   The date timestamp or string.
   */
  public function getDate($value) {
    if ($this->definition->getFieldType() == 'datetime') {
      return $value;
    }

    return $this->convertToTimestamp($value);
  }

  /**
   * Get the properly formatted relative date.
   *
   * @param mixed $value
   *   The current value.
   *
   * @return mixed
   *   The date timestamp or string.
   */
  public function getRelativeDate($value) {
    $relative_time = time() + $this->convertToTimestamp($value);

    // Datetime field already works by comparing this format.
    if ($this->definition->getFieldType() == 'datetime') {
      return date('Y-m-d H:i:s', $relative_time);
    }

    return $relative_time;
  }

  /**
   * Convert a date to a timestamp for comparison.
   *
   * @param string $date
   *   The string formatted date.
   *
   * @return int
   *   The timestamp.
   */
  protected function convertToTimestamp($date) {
    // Only convert to timestamp if the value is not an integer.
    if (!is_int($date)) {
      return intval(strtotime($date, 0));
    }

    return $date;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc