Skip to content

Commit

Permalink
feat: implement toLocaleString() method
Browse files Browse the repository at this point in the history
  • Loading branch information
xanaDev committed Oct 16, 2022
1 parent fbf2e51 commit e234332
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -726,4 +726,57 @@ public function isEmpty(): bool
{
return $this->length() === 0;
}

/**
* Returns a string representing the elements of the array
* @return string the string representation
*/
public function toLocaleString($locale = 'en_US.utf8', $timezone = 'UTC'): string
{
if ($this->length() <= 0) {
return '';
}

date_default_timezone_set($timezone);
$currentLocale = setlocale(LC_ALL, $locale);
$localeConfig = localeconv();

$result = $this->map(function ($item) use ($localeConfig) {
if (is_numeric($item)) {
$item = number_format(
$item,
is_float($item) ? 2 : 0,
$localeConfig['decimal_point'] ?? '.',
$localeConfig["thousands_sep"] ?? ','
);
} elseif ($this->isDate($item)) {
$date = date_parse($item);
$item = strftime(
'%c',
mktime($date['hour'], $date['minute'], $date['second'], $date['month'], $date['day'], $date['year'])
);
}

return $item;
});

return $result->toString();
}

/**
* Checks whether a value is a valid date
* @return boolean true if value is a valid date, false otherwise
*/
protected function isDate($value): bool
{
if (!$value) {
return false;
}

$date = date_parse($value);

return $date['error_count'] == 0
&& $date['warning_count'] == 0
&& checkdate($date['month'], $date['day'], $date['year']);
}
}

0 comments on commit e234332

Please sign in to comment.