You are here

protected function SamlauthConfigureForm::parseReadableDuration in SAML Authentication 4.x

Same name and namespace in other branches
  1. 8.3 src/Form/SamlauthConfigureForm.php \Drupal\samlauth\Form\SamlauthConfigureForm::parseReadableDuration()

Parses a human readable 'duration' string.

Parameters

string $expression: The human readable duration description (e.g. "5 hours 3 minutes").

Return value

int The number of seconds; 0 implies invalid duration.

2 calls to SamlauthConfigureForm::parseReadableDuration()
SamlauthConfigureForm::submitForm in src/Form/SamlauthConfigureForm.php
Form submission handler.
SamlauthConfigureForm::validateForm in src/Form/SamlauthConfigureForm.php
Form validation handler.

File

src/Form/SamlauthConfigureForm.php, line 1672

Class

SamlauthConfigureForm
Provides a configuration form for samlauth module settings and IdP/SP info.

Namespace

Drupal\samlauth\Form

Code

protected function parseReadableDuration($expression) {
  $calculation = [
    'week' => 3600 * 24 * 7,
    'day' => 3600 * 24,
    'hour' => 3600,
    'minute' => 60,
    'second' => 1,
  ];
  $expression = strtolower(trim($expression));
  if (substr($expression, -1) === '.') {
    $expression = rtrim(substr($expression, 0, strlen($expression) - 1));
  }
  $seconds = 0;
  $seen = [];

  // Numbers must be numeric. Valid: "X hours Y minutes" possibly separated
  // by comma or "and". Months/years are not accepted because their length is
  // ambiguous.
  $parts = preg_split('/(\\s+|\\s*,\\s*|\\s+and\\s+)(?=\\d)/', $expression);
  foreach ($parts as $part) {
    if (!preg_match('/^(\\d+)\\s*((?:week|day|hour|min(?:ute)?|sec(?:ond)?)s?)$/', $part, $matches)) {
      return 0;
    }
    if (substr($matches[2], -1) === 's') {
      $matches[2] = substr($matches[2], 0, strlen($matches[2]) - 1);
    }
    elseif ($matches[1] != 1 && !in_array($matches[2], [
      'min',
      'sec',
    ], TRUE)) {

      // We allow "1 min", "1 mins", "2 min", not "2 minute".
      return 0;
    }
    $unit = $matches[2] === 'min' ? 'minute' : ($matches[2] === 'sec' ? 'second' : $matches[2]);
    if (!isset($calculation[$unit])) {
      return 0;
    }
    if (isset($seen[$unit])) {
      return 0;
    }
    $seen[$unit] = TRUE;
    $seconds += $calculation[$unit] * $matches[1];
  }
  return $seconds;
}