Skip to content

Instantly share code, notes, and snippets.

@devdrops
Last active August 29, 2015 14:05
Show Gist options
  • Save devdrops/d9c0c976df9eb2520f55 to your computer and use it in GitHub Desktop.
Save devdrops/d9c0c976df9eb2520f55 to your computer and use it in GitHub Desktop.
Zend\Filter\DateTimeFormatter throws Exception when receives invalid date

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',
    ),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment