3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\I18n\Validator
;
15 use Zend\I18n\Exception
as I18nException
;
16 use Zend\Stdlib\ArrayUtils
;
17 use Zend\Validator\AbstractValidator
;
18 use Zend\Validator\Exception
;
20 class Float extends AbstractValidator
22 const INVALID
= 'floatInvalid';
23 const NOT_FLOAT
= 'notFloat';
28 protected $messageTemplates = array(
29 self
::INVALID
=> "Invalid type given. String, integer or float expected",
30 self
::NOT_FLOAT
=> "The input does not appear to be a float",
41 * Constructor for the integer validator
43 * @param array|Traversable $options
44 * @throws Exception\ExtensionNotLoadedException if ext/intl is not present
46 public function __construct($options = array())
48 if (!extension_loaded('intl')) {
49 throw new I18nException\
ExtensionNotLoadedException(sprintf(
50 '%s component requires the intl PHP extension',
55 if ($options instanceof Traversable
) {
56 $options = ArrayUtils
::iteratorToArray($options);
59 if (array_key_exists('locale', $options)) {
60 $this->setLocale($options['locale']);
63 parent
::__construct($options);
67 * Returns the set locale
71 public function getLocale()
73 if (null === $this->locale
) {
74 $this->locale
= Locale
::getDefault();
80 * Sets the locale to use
82 * @param string|null $locale
85 public function setLocale($locale)
87 $this->locale
= $locale;
93 * Returns true if and only if $value is a floating-point value
95 * @param string $value
97 * @throws Exception\InvalidArgumentException
99 public function isValid($value)
101 if (!is_string($value) && !is_int($value) && !is_float($value)) {
102 $this->error(self
::INVALID
);
106 $this->setValue($value);
108 if (is_float($value)) {
112 $locale = $this->getLocale();
113 $format = new NumberFormatter($locale, NumberFormatter
::DECIMAL
);
114 if (intl_is_failure($format->getErrorCode())) {
115 throw new Exception\
InvalidArgumentException("Invalid locale string given");
118 $parsedFloat = $format->parse($value, NumberFormatter
::TYPE_DOUBLE
);
119 if (intl_is_failure($format->getErrorCode())) {
120 $this->error(self
::NOT_FLOAT
);
124 $decimalSep = $format->getSymbol(NumberFormatter
::DECIMAL_SEPARATOR_SYMBOL
);
125 $groupingSep = $format->getSymbol(NumberFormatter
::GROUPING_SEPARATOR_SYMBOL
);
127 $valueFiltered = str_replace($groupingSep, '', $value);
128 $valueFiltered = str_replace($decimalSep, '.', $valueFiltered);
130 while (strpos($valueFiltered, '.') !== false
131 && (substr($valueFiltered, -1) == '0' ||
substr($valueFiltered, -1) == '.')
133 $valueFiltered = substr($valueFiltered, 0, strlen($valueFiltered) - 1);
136 if (strval($parsedFloat) !== $valueFiltered) {
137 $this->error(self
::NOT_FLOAT
);