Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Render timezone listbox dynamically #1672

Merged
merged 17 commits into from
Aug 14, 2018
Next Next commit
Render timezone listbox dynamically
  • Loading branch information
asbiin committed Aug 8, 2018
commit d1ca62c4a01ae8340f0644f9bad053583ab3adf3
96 changes: 96 additions & 0 deletions app/Helpers/TimezoneHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

namespace App\Helpers;

use DateTimeZone;

class TimezoneHelper
{
/**
* Get a list of all timezones
*
* @return array
*/
public static function listTimezones() : array
{
$list = [];
$timezones = DateTimeZone::listIdentifiers();

foreach ($timezones as $timezone) {
list($tz, $name) = self::formatTimezone($timezone);
array_push($list, [
'id' => $tz,
'timezone' => $timezone,
'name' => $name
]);
}

return array_values(array_sort($list, function ($value) {
return $value['id'];
}));
}

private static function formatTimezone($timezone) : array
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Description of this method?

{
$time = now($timezone);

$offset = $time->format('P');

if ($timezone == 'UTC') {
$formatted = '(UTC) Universal Time Coordinated';
} else {
$i = strstr($time->tzName, '/');
if ($i > 0) {
$timezone = substr(strstr($time->tzName, '/'), 1);
}
$timezone = str_replace('St_', 'St. ', $timezone);
$timezone = str_replace('_', ' ', $timezone);

$formatted = '(UTC ' . $offset . ') ' . $timezone;
}

$tz = str_replace(':', '', $offset);
$tz = intval($tz);

return [$tz, $formatted];
}

/**
* Render listbox of timezones.
*
* @param string $name
* @param string $selected
* @param mixed $attr
* @return string
**/
public static function list($name, $selected='', $attr='') : string
{
// Attributes for select element
$attrSet = null;
if (!empty($attr)) {
if (is_array($attr)) {
foreach ($attr as $attr_name => $attr_value) {
$attrSet .= ' ' .$attr_name. '="' .$attr_value. '"';
}
} else {
$attrSet = ' ' .$attr;
}
}

$listbox = '<select name="' .$name. '"' .$attrSet. '>';

$list = self::listTimezones();

foreach ($list as $key => $timezone) {
$selected_attr = ($selected == $timezone['timezone']) ? ' selected="selected"' : '';

$listbox .= '<option value="' .$timezone['timezone']. '"' .$selected_attr. '>';
$listbox .= $timezone['name'];
$listbox .= '</option>';
}

$listbox .= '</select>';

return $listbox;
}
}
Loading