/** * Convert localized string representations to integer, float or date values * * Subclasses can support localized input formats by calling this method * from a filter. * * Non-string values get trimmed and converted to integer, float or * \DateTime, depending on $type. Invalid values are returned as string. The * input filter should validate filtered data by checking the datatype via * validateType(). * * @param string $value Localized input string * @param string $type Data type (integer, float, date). Any other value will be ignored. * @return mixed Normalized value or input string */ public function normalize($value, $type) { // Integers and floats are validated first to prevent successful parsing // of strings containing invalid characters with the invalid part simply // cut off. switch ($type) { case 'integer': $value = trim($value); if (\Zend\Validator\StaticValidator::execute($value, 'Zend\\I18n\\Validator\\IsInt')) { $value = \Zend\Filter\StaticFilter::execute($value, 'Zend\\I18n\\Filter\\NumberParse', array('type' => \NumberFormatter::TYPE_INT32)); } break; case 'float': $value = trim($value); if (\Zend\Validator\StaticValidator::execute($value, 'Zend\\I18n\\Validator\\IsFloat')) { $value = \Zend\Filter\StaticFilter::execute($value, 'Zend\\I18n\\Filter\\NumberParse', array('type' => \NumberFormatter::TYPE_DOUBLE)); } break; case 'date': $value = trim($value); $validator = new \Zend\I18n\Validator\DateTime(); $validator->setDateType(\IntlDateFormatter::SHORT); if ($validator->isValid($value)) { // Some systems accept invalid date separators, like '/' // with a de_DE locale which should accept only '.'. // An extra comparision of the locale-specific pattern and // the input string is necessary. // This also enforces 4-digit years to avoid any confusion // with 2-digit year input. $pattern = preg_quote($validator->getPattern(), '#'); // Get the year part out of the way first. $pattern = preg_replace('/y+/', '§', $pattern); // Remaining letters are placeholders for digits. $pattern = preg_replace('/[a-zA-Z]+/', '\\d+', $pattern); // Set the year pattern. $pattern = str_replace('§', '\\d{4}', $pattern); if (preg_match("#^{$pattern}\$#", $value)) { $formatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE, 'UTC'); $value = \DateTime::createFromFormat('U', $formatter->parse($value)); } } break; } return $value; }