08/07/2014 3:05pm
####Problem: While filtering using Zend\Filter\DateTimeFormatter to validate dates in pt_BR format. When inserting '1', it throws an Exception 'Invalid date string provided'.
Checking https://github.com/zendframework/zf2/blob/master/library/Zend/Filter/DateTimeFormatter.php#L77 , Zend\Filter\DateTimeFormatter throws an Exception to prevent \DateTime from crash (maybe?). This is somehow weird because filters shouldn't throw Exceptions IMHO.
Here's the method:
/**
* Normalize the provided value to a formatted string
*
* @param string|int|DateTime $value
* @return string
*/
protected function normalizeDateTime($value)
{
if ($value === '' || $value === null) {
return $value;
}
if (!is_string($value) && !is_int($value) && !$value instanceof DateTime) {
return $value;
}
if (is_int($value)) {
//timestamp
$value = new DateTime('@' . $value);
} elseif (!$value instanceof DateTime) {
$value = new DateTime($value);
}
return $value->format($this->format);
}
BTW it's really cool to see that there's not even a @throw here.
Suggestions:
1.DEPRECATED) Use the same treatment as timestamp, as above:
/**
* Normalize the provided value to a formatted string
*
* @param string|int|DateTime $value
* @return string
*/
protected function normalizeDateTime($value)
{
if ($value === '' || $value === null) {
return $value;
}
if (!is_string($value) && !is_int($value) && !$value instanceof DateTime) {
return $value;
}
if (is_int($value)) {
//timestamp
$value = new DateTime('@' . $value);
} elseif (!$value instanceof DateTime) {
$value = new DateTime('@' . $value);
}
return $value->format($this->format);
}
Just need to check it out a way to avoid the unpleasant duplication here.
###NOTE: this doesn't work. Actually it's required to use the PregReplace filter together to filter '/' to '-', and without any changes to DateTimeFormatter, as above:
array(
'name' => 'PregReplace',
'options' => array(
'pattern' => '/\//',
'replacement' => '-'
)
),
array(
'name' => 'DateTimeFormatter',
'options' => array(
'format' => 'Y-m-d',
),
)