Files
DomFramework/convert.php
2017-05-05 18:35:14 +00:00

60 lines
2.2 KiB
PHP

<?php
/** DomFramework
@package domframework
@author Dominique Fournier <dominique@fournier38.fr> */
/** Convert a format to another one
*/
class convert
{
/** Convert Date received in one format to another.
* If the provided string is not corresponding to the format, generate an
* exception or return the original string
* Format used http://php.net/manual/en/datetime.createfromformat.php
* Do not accept the locale ! The language of the dates is always in english
* @param string $inputDate The date to modify
* @param string $inputFormat The input format of the date
* @param string $outputFormat The output format of the date
* @param boolean|null $exception If set, generate an exception if the
* provided date is invalid
* @return string
*/
public static function convertDate ($inputDate, $inputFormat, $outputFormat,
$exception = true)
{
if (! is_string ($inputDate))
throw new \Exception ("The date to convert is not a string", 500);
if (! is_string ($inputFormat))
throw new \Exception ("The convert input format is not a string", 500);
if (! is_string ($outputFormat))
throw new \Exception ("The convert output format is not a string", 500);
$date = \DateTime::CreateFromFormat ($inputFormat, $inputDate);
if ($date === false)
{
if ($exception === true)
throw new \Exception (
"Invalid date provided or not matching the format", 500);
return $inputDate;
}
$errors = $date->getLastErrors();
if ($errors["warning_count"] > 0 || $errors["error_count"] > 0)
{
if ($exception === true)
throw new \Exception (
"Invalid date provided or not matching the format", 500);
return $inputDate;
}
return $date->format ($outputFormat);
}
/** Convert the first char to capital and the rest of the sentence in
* lowercase (like ucfirst, but UTF8 compliant
* @param string $str The string to convert
*/
public static function ucfirst ($str)
{
$a = mb_strtoupper (mb_substr ($str, 0, 1, 'UTF-8'), 'UTF-8');
return $a . mb_substr ($str, 1, null, 'UTF-8');
}
}