You are here

class OfficeHoursDatetime in Office Hours 8

Provides a one-line HTML5 time element.

Plugin annotation

@FormElement("office_hours_datetime");

Hierarchy

Expanded class hierarchy of OfficeHoursDatetime

5 files declare their use of OfficeHoursDatetime
OfficeHoursDatetimeUnitTest.php in tests/src/Unit/OfficeHoursDatetimeUnitTest.php
OfficeHoursFormatterTrait.php in src/OfficeHoursFormatterTrait.php
OfficeHoursItem.php in src/Plugin/Field/FieldType/OfficeHoursItem.php
OfficeHoursItemList.php in src/Plugin/Field/FieldType/OfficeHoursItemList.php
OfficeHoursWidgetBase.php in src/Plugin/Field/FieldWidget/OfficeHoursWidgetBase.php

File

src/Element/OfficeHoursDatetime.php, line 15

Namespace

Drupal\office_hours\Element
View source
class OfficeHoursDatetime extends Datetime {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $parent_info = parent::getInfo();
    $info = [
      '#process' => [
        [
          static::class,
          'processOfficeHoursTime',
        ],
      ],
      '#element_validate' => [
        [
          static::class,
          'validateOfficeHoursTime',
        ],
      ],
      // @see Drupal\Core\Datetime\Element\Datetime.
      '#date_date_element' => 'none',
      // {'none'|'date'}
      '#date_date_format' => 'none',
      '#date_time_element' => 'time',
      // {'none'|'time'|'text'}
      // @see Drupal\Core\Datetime\Element\DateElementBase.
      '#date_timezone' => '+0000',
    ];

    // #process: bottom-up.
    $info['#process'] = array_merge($parent_info['#process'], $info['#process']);
    return $info + $parent_info;
  }

  /**
   * Callback for office_hours_select element.
   *
   * Takes #default_value and dissects it in hours, minutes and ampm indicator.
   * Mimics the date_parse() function.
   * - g = 12-hour format of an hour without leading zeros 1 through 12
   * - G = 24-hour format of an hour without leading zeros 0 through 23
   * - h = 12-hour format of an hour with leading zeros    01 through 12
   * - H = 24-hour format of an hour with leading zeros    00 through 23
   *
   * @param array $element
   * @param mixed $input
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return array|mixed|null
   *   The value, as entered by the user.
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    $input['time'] = OfficeHoursDatetime::get($element['#default_value'], 'H:i');
    $input = parent::valueCallback($element, $input, $form_state);
    $element['#default_value'] = $input;
    return $input;
  }

  /**
   * Process the office_hours_select element before showing it.
   *
   * @param $element
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param $complete_form
   *
   * @return array
   *   The processed element.
   */
  public static function processOfficeHoursTime(&$element, FormStateInterface $form_state, &$complete_form) {
    $element = parent::processDatetime($element, $form_state, $complete_form);

    // @todo Use $element['#date_time_callbacks'], do not use this function.
    // Adds the HTML5 attributes.
    $element['time']['#attributes'] = [
      // @todo Set a proper from/to title.
      // 'title' => $this->t('Time (e.g. @format)', ['@format' => static::formatExample($time_format)]),
      // Fix the convention: minutes vs. seconds.
      'step' => $element['#date_increment'] * 60,
    ] + $element['time']['#attributes'];
    return $element;
  }

  /**
   * Validate the hours selector element.
   *
   * @param $element
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param $complete_form
   */
  public static function validateOfficeHoursTime(&$element, FormStateInterface $form_state, &$complete_form) {
    $input_exists = FALSE;

    // @todo Call validateDatetime().
    // Get the 'time' sub-array.
    $input = NestedArray::getValue($form_state
      ->getValues(), $element['#parents'], $input_exists);

    // Generate the 'object' sub-array.
    parent::valueCallback($element, $input, $form_state);
  }

  /**
   * Mimic Core/TypedData/ComplexDataInterface.
   */

  /**
   * Returns the data from a widget.
   *
   * There are too many similar functions:
   *  - OfficeHoursWidgetBase::massageFormValues();
   *  - OfficeHoursItem, which requires an object;
   *  - OfficeHoursDateTime::get() (this function).
   *
   * @todo Use Core/TypedData/ComplexDataInterface.
   *
   * @param mixed $element
   *   A string or array for time.
   * @param string $format
   *   Required time format.
   *
   * @return string
   *   Return value.
   */
  public static function get($element, $format = 'Hi') {
    $value = '';

    // Be prepared for Datetime and Numeric input.
    // Numeric input set in validateOfficeHoursSlot().
    if (!isset($element)) {
      return $value;
    }
    if (isset($element['time'])) {

      // Return NULL or time string.
      $value = OfficeHoursDateHelper::format($element['time'], $format);
    }
    elseif (!empty($element['hour'])) {
      $value = OfficeHoursDateHelper::format($element['hour'] * 100 + $element['minute'], $format);
    }
    elseif (!isset($element['hour'])) {
      $value = OfficeHoursDateHelper::format($element, $format);
    }
    return $value;
  }

  /**
   * Determines whether the data structure is empty.
   *
   * @param mixed $element
   *   A string or array for time slot.
   *   Example from HTML5 input, without comments enabled.
   *   @code
   *     array:3 [
   *       "day" => "3"
   *       "starthours" => array:1 [
   *         "time" => "19:30"
   *       ]
   *       "endhours" => array:1 [
   *         "time" => ""
   *       ]
   *     ]
   *   @endcode
   *
   * @return bool
   *   TRUE if the data structure is empty, FALSE otherwise.
   */
  public static function isEmpty($element) {

    // Note: in Week-widget, day is <> '', in List-widget, day can be ''.
    // And in Exception day, day can be ''.
    // Note: test every change with Week/List widget and Select/HTML5 element!
    if ($element === NULL) {
      return TRUE;
    }
    if ($element === '') {
      return TRUE;
    }
    if ($element === '-1') {

      // Empty hours/minutes, but comment enabled.
      return TRUE;
    }
    if (is_array($element)) {
      if (isset($element['time'])) {
        if ($element['time'] === '') {
          return TRUE;
        }
        return FALSE;
      }
      if (!isset($element['day']) && !isset($element['time'])) {
        return TRUE;
      }
      if ($element['day'] !== '' && strlen($element['day']) > 1) {
        if (isset($element['day_delta']) && $element['day_delta'] == 0) {

          // @todo Why is day_delta sometimes not set?
          // First slot is never empty if an Exception date is set.
          return FALSE;
        }
        if (isset($element['starthours']) && OfficeHoursDatetime::isEmpty($element['starthours']) && (isset($element['endhours']) && OfficeHoursDatetime::isEmpty($element['endhours'])) && (!isset($element['comment']) || empty($element['comment']))) {
          return TRUE;
        }
      }

      // Check normal weekday element.
      if (isset($element['day']) && (int) $element['day'] < 7 && (isset($element['starthours']) && OfficeHoursDatetime::isEmpty($element['starthours'])) && (isset($element['endhours']) && OfficeHoursDatetime::isEmpty($element['endhours'])) && (!isset($element['comment']) || empty($element['comment']))) {
        return TRUE;
      }

      // Check HTML5 datetime element.
      if (isset($element['starthours']['time']) && OfficeHoursDatetime::isEmpty($element['starthours']['time']) && (isset($element['endhours']['time']) && OfficeHoursDatetime::isEmpty($element['endhours']['time'])) && (!isset($element['comment']) || empty($element['comment']))) {
        return TRUE;
      }
    }
    return FALSE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DateElementBase::datetimeRangeYears protected static function Specifies the start and end year to use as a date range.
DateElementBase::getElementTitle protected static function Returns the most relevant title of a datetime element.
Datetime::$dateExample protected static property
Datetime::formatExample public static function Creates an example for a date format.
Datetime::getHtml5DateFormat protected static function Retrieves the right format for a HTML5 date element.
Datetime::getHtml5TimeFormat protected static function Retrieves the right format for a HTML5 time element.
Datetime::processAjaxForm public static function Form element processing handler for the #ajax form property. Overrides RenderElement::processAjaxForm
Datetime::processDatetime public static function Expands a datetime element type into date and/or time elements.
Datetime::validateDatetime public static function Validation callback for a datetime element.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormElement::processAutocomplete public static function Adds autocomplete functionality to elements.
FormElement::processPattern public static function #process callback for #pattern form element property.
FormElement::validatePattern public static function #element_validate callback for #pattern form element property.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
OfficeHoursDatetime::get public static function Returns the data from a widget.
OfficeHoursDatetime::getInfo public function Returns the element properties for this element. Overrides Datetime::getInfo
OfficeHoursDatetime::isEmpty public static function Determines whether the data structure is empty.
OfficeHoursDatetime::processOfficeHoursTime public static function Process the office_hours_select element before showing it.
OfficeHoursDatetime::validateOfficeHoursTime public static function Validate the hours selector element.
OfficeHoursDatetime::valueCallback public static function Callback for office_hours_select element. Overrides Datetime::valueCallback
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.