You are here

class GranularityService in Duration Field 3.0.x

Same name in this branch
  1. 3.0.x src/Service/GranularityService.php \Drupal\duration_field\Service\GranularityService
  2. 3.0.x tests/src/Unit/Service/GranularityService.php \Drupal\Tests\duration_field\Unit\Service\GranularityService
Same name and namespace in other branches
  1. 8.2 src/Service/GranularityService.php \Drupal\duration_field\Service\GranularityService

Hierarchy

Expanded class hierarchy of GranularityService

1 file declares its use of GranularityService
GranularityService.php in tests/src/Unit/Service/GranularityService.php
1 string reference to 'GranularityService'
duration_field.services.yml in ./duration_field.services.yml
duration_field.services.yml

File

src/Service/GranularityService.php, line 8

Namespace

Drupal\duration_field\Service
View source
class GranularityService implements GranularityServiceInterface {

  /**
   * {@inheritdoc}
   */
  public function convertGranularityArrayToGranularityString(array $granularityArray) {
    $granularities = [];

    // Loop through each of the submitted values.
    foreach (array_keys($granularityArray) as $granularity) {

      // Check if the submitted value evaluates to TRUE.
      if ($granularityArray[$granularity]) {

        // Add the granularity to the granularities to be rendered.
        $granularities[] = $granularity;
      }
    }

    // Build and return the granularity string.
    return implode(':', $granularities);
  }

  /**
   * {@inheritdoc}
   */
  public function convertGranularityStringToGranularityArray($granularityString) {
    $granularities = $this
      ->getDrupalStatic(__CLASS__ . '::' . __FUNCTION__);
    if (!isset($granularities[$granularityString])) {
      $granularities[$granularityString] = [
        'y' => FALSE,
        'm' => FALSE,
        'd' => FALSE,
        'h' => FALSE,
        'i' => FALSE,
        's' => FALSE,
      ];
      foreach (explode(':', $granularityString) as $key) {
        if (strlen($key)) {
          $granularities[$granularityString][$key] = TRUE;
        }
      }
    }
    return $granularities[$granularityString];
  }

  /**
   * {@inheritdoc}
   */
  public function includeGranularityElement($granularityElement, $granularityString) {
    $granularities = $this
      ->convertGranularityStringToGranularityArray($granularityString);
    return $granularities[$granularityElement];
  }

  /**
   * Returns drupal_static().
   *
   * Set as a protected function so it can be overridden for unit tests.
   *
   * @return array
   *   The drupal static array.
   */
  protected function getDrupalStatic($key) {
    $static =& drupal_static($key);
    return $static;
  }

}

Members