123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218 |
- <?php
- namespace Cube\Locale;
- class Format
- {
-
- const US = 1;
-
- const EU = 2;
-
- protected $_formats = array(
- self::US,
- self::EU,
- );
-
- protected $_format;
-
- protected $_decimals = 0;
-
- private static $_instance;
-
- public static function getInstance()
- {
- if (!self::$_instance instanceof self) {
- self::$_instance = new self();
- }
- return self::$_instance;
- }
-
- public function getFormat()
- {
- return $this->_format;
- }
-
- public function setFormat($format)
- {
- $this->_format = $format;
- return $this;
- }
-
- public function getDecimals()
- {
- return $this->_decimals;
- }
-
- public function setDecimals($decimals)
- {
- $this->_decimals = $decimals;
- return $this;
- }
-
- public function localizedToNumeric($value, $valueOnFalse = false)
- {
- if ($this->_isNumeric($value) && $this->getDecimals() > 0) {
- return $value;
- }
- $format = $this->getFormat();
- switch ($format) {
- case self::US:
- if (!preg_match('#^(-+)?\d{1,3}(?:,?\d{3})*(?:\.\d+)?$#', $value)) {
- return ($valueOnFalse) ? $value : false;
- }
- $value = str_replace(',', '', $value);
- break;
- case self::EU:
- if (!preg_match('#^(-+)?\d{1,3}(?:\.?\d{3})*(?:\,\d+)?$#', $value)) {
- return ($valueOnFalse) ? $value : false;
- }
- $value = str_replace(array('.', ','), array('', '.'), $value);
- break;
- }
- return ($this->_isNumeric($value) || $valueOnFalse) ? $value : false;
- }
-
- public function numericToLocalized($value, $valueOnFalse = false)
- {
- if (!$this->_isNumeric($value)) {
- return ($valueOnFalse) ? $value : false;
- }
- $format = $this->getFormat();
- $decimals = $this->getDecimals();
- switch ($format) {
- case self::US:
- $value = number_format($value, $decimals, '.', ',');
- break;
- case self::EU:
- $value = number_format($value, $decimals, ',', '.');
- break;
- }
- return $value;
- }
-
- protected function _isNumeric($value)
- {
- return (bool)preg_match('#^-?\d*\.?\d+$#', $value);
- }
- }
|