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\Filter
;
14 use Zend\I18n\Exception
;
15 use Zend\Stdlib\ErrorHandler
;
17 class NumberFormat
extends AbstractLocale
19 protected $options = array(
21 'style' => NumberFormatter
::DEFAULT_STYLE
,
22 'type' => NumberFormatter
::TYPE_DOUBLE
26 * @var NumberFormatter
28 protected $formatter = null;
31 * @param array|Traversable|string|null $localeOrOptions
35 public function __construct(
36 $localeOrOptions = null,
37 $style = NumberFormatter
::DEFAULT_STYLE
,
38 $type = NumberFormatter
::TYPE_DOUBLE
)
40 parent
::__construct();
41 if ($localeOrOptions !== null) {
42 if ($localeOrOptions instanceof Traversable
) {
43 $localeOrOptions = iterator_to_array($localeOrOptions);
46 if (!is_array($localeOrOptions)) {
47 $this->setLocale($localeOrOptions);
48 $this->setStyle($style);
49 $this->setType($type);
51 $this->setOptions($localeOrOptions);
57 * @param string|null $locale
58 * @return NumberFormat
60 public function setLocale($locale = null)
62 $this->options
['locale'] = $locale;
63 $this->formatter
= null;
69 * @return NumberFormat
71 public function setStyle($style)
73 $this->options
['style'] = (int) $style;
74 $this->formatter
= null;
81 public function getStyle()
83 return $this->options
['style'];
88 * @return NumberFormat
90 public function setType($type)
92 $this->options
['type'] = (int) $type;
99 public function getType()
101 return $this->options
['type'];
105 * @param NumberFormatter $formatter
106 * @return NumberFormat
108 public function setFormatter(NumberFormatter
$formatter)
110 $this->formatter
= $formatter;
115 * @return NumberFormatter
116 * @throws Exception\RuntimeException
118 public function getFormatter()
120 if ($this->formatter
=== null) {
121 $formatter = NumberFormatter
::create($this->getLocale(), $this->getStyle());
123 throw new Exception\
RuntimeException(
124 'Can not create NumberFormatter instance; ' . intl_get_error_message()
128 $this->formatter
= $formatter;
131 return $this->formatter
;
135 * Defined by Zend\Filter\FilterInterface
137 * @see Zend\Filter\FilterInterface::filter()
138 * @param mixed $value
141 public function filter($value)
143 $formatter = $this->getFormatter();
144 $type = $this->getType();
146 if (is_int($value) ||
is_float($value)) {
147 ErrorHandler
::start();
148 $result = $formatter->format($value, $type);
149 ErrorHandler
::stop();
151 $value = str_replace(array("\xC2\xA0", ' '), '', $value);
152 ErrorHandler
::start();
153 $result = $formatter->parse($value, $type);
154 ErrorHandler
::stop();
157 if ($result === false) {
161 return str_replace("\xC2\xA0", ' ', $result);