PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/devblocks/libs/ZendFramework/Zend/Locale/Format.php

https://github.com/sluther/portsensor
PHP | 1065 lines | 702 code | 91 blank | 272 comment | 207 complexity | 5a4846141e7db08eacda709211e9fc8f MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Locale
  17. * @subpackage Format
  18. * @copyright Copyright (c) 2005-2007 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @version $Id: Format.php 6727 2007-11-03 19:29:21Z thomas $
  20. * @license http://framework.zend.com/license/new-bsd New BSD License
  21. */
  22. /**
  23. * include needed classes
  24. */
  25. require_once 'Zend/Locale/Data.php';
  26. require_once 'Zend/Locale/Exception.php';
  27. /**
  28. * @category Zend
  29. * @package Zend_Locale
  30. * @subpackage Format
  31. * @copyright Copyright (c) 2005-2007 Zend Technologies USA Inc. (http://www.zend.com)
  32. * @license http://framework.zend.com/license/new-bsd New BSD License
  33. */
  34. class Zend_Locale_Format
  35. {
  36. const STANDARD = 'STANDARD';
  37. private static $_Options = array('date_format' => null,
  38. 'number_format' => null,
  39. 'format_type' => 'iso',
  40. 'fix_date' => false,
  41. 'locale' => null,
  42. 'cache' => null,
  43. 'precision' => null);
  44. private static $_signs = array(
  45. 'Latn' => array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), // Latn - default latin
  46. 'Arab' => array( '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'), // 0660 - 0669 arabic
  47. 'Deva' => array( '०', '१', '२', '३', '४', '५', '६', '७', '८', '९'), // 0966 - 096F devanagari
  48. 'Beng' => array( '০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯'), // 09E6 - 09EF bengali
  49. 'Guru' => array( '੦', '੧', '੨', '੩', '੪', '੫', '੬', '੭', '੮', '੯'), // 0A66 - 0A6F gurmukhi
  50. 'Gujr' => array( '૦', '૧', '૨', '૩', '૪', '૫', '૬', '૭', '૮', '૯'), // 0AE6 - 0AEF gujarati
  51. 'Orya' => array( '୦', '୧', '୨', '୩', '୪', '୫', '୬', '୭', '୮', '୯'), // 0B66 - 0B6F orija
  52. 'Taml' => array( '௦', '௧', '௨', '௩', '௪', '௫', '௬', '௭', '௮', '௯'), // 0BE6 - 0BEF tamil
  53. 'Telu' => array( '౦', '౧', '౨', '౩', '౪', '౫', '౬', '౭', '౮', '౯'), // 0C66 - 0C6F telugu
  54. 'Knda' => array( '೦', '೧', '೨', '೩', '೪', '೫', '೬', '೭', '೮', '೯'), // 0CE6 - 0CEF kannada
  55. 'Mlym' => array( '൦', '൧', '൨', '൩', '൪', '൫', '൬', '൭', '൮', '൯ '), // 0D66 - 0D6F malayalam
  56. 'Tale' => array( '๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙ '), // 0E50 - 0E59 thai
  57. 'Laoo' => array( '໐', '໑', '໒', '໓', '໔', '໕', '໖', '໗', '໘', '໙'), // 0ED0 - 0ED9 lao
  58. 'Tibt' => array( '༠', '༡', '༢', '༣', '༤', '༥', '༦', '༧', '༨', '༩ '), // 0F20 - 0F29 tibetan
  59. 'Mymr' => array( '၀', '၁', '၂', '၃', '၄', '၅', '၆', '၇', '၈', '၉'), // 1040 - 1049 myanmar
  60. 'Khmr' => array( '០', '១', '២', '៣', '៤', '៥', '៦', '៧', '៨', '៩'), // 17E0 - 17E9 khmer
  61. 'Mong' => array( '᠐', '᠑', '᠒', '᠓', '᠔', '᠕', '᠖', '᠗', '᠘', '᠙'), // 1810 - 1819 mongolian
  62. 'Limb' => array( '᥆', '᥇', '᥈', '᥉', '᥊', '᥋', '᥌', '᥍', '᥎', '᥏'), // 1946 - 194F limbu
  63. 'Talu' => array( '᧐', '᧑', '᧒', '᧓', '᧔', '᧕', '᧖', '᧗', '᧘', '᧙'), // 19D0 - 19D9 tailue
  64. 'Bali' => array( '᭐', '᭑', '᭒', '᭓', '᭔', '᭕', '᭖', '᭗', '᭘', '᭙'), // 1B50 - 1B59 balinese
  65. 'Nkoo' => array( '߀', '߁', '߂', '߃', '߄', '߅', '߆', '߇', '߈', '߉') // 07C0 - 07C9 nko
  66. );
  67. /**
  68. * Sets class wide options, if no option was given, the actual set options will be returned
  69. * The 'precision' option of a value is used to truncate or stretch extra digits. -1 means not to touch the extra digits.
  70. * The 'locale' option helps when parsing numbers and dates using separators and month names.
  71. * The date format 'format_type' option selects between CLDR/ISO date format specifier tokens and PHP's date() tokens.
  72. * The 'fix_date' option enables or disables heuristics that attempt to correct invalid dates.
  73. * The 'number_format' option can be used to specify a default number format string
  74. * The 'date_format' option can be used to specify a default date format string, but beware of using getDate(),
  75. * checkDateFormat() and getTime() after using setOptions() with a 'format'. To use these four methods
  76. * with the default date format for a locale, use array('date_format' => null, 'locale' => $locale) for their options.
  77. *
  78. * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,
  79. * locale = Zend_Locale | locale string, precision = whole number between -1 and 30
  80. * @throws Zend_Locale_Exception
  81. * @return Options array if no option was given
  82. */
  83. public static function setOptions(array $options = array())
  84. {
  85. self::$_Options = array_merge(self::$_Options, self::checkOptions($options));
  86. return self::$_Options;
  87. }
  88. /**
  89. * Internal function for checking the options array of proper input values
  90. * See {@link setOptions()} for details.
  91. *
  92. * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,
  93. * locale = Zend_Locale | locale string, precision = whole number between -1 and 30
  94. * @throws Zend_Locale_Exception
  95. * @return Options array if no option was given
  96. */
  97. private static function checkOptions(array $options = array())
  98. {
  99. if (count($options) == 0) {
  100. return self::$_Options;
  101. }
  102. foreach ($options as $name => $value) {
  103. $name = strtolower($name);
  104. if ($name !== 'locale') {
  105. if (gettype($value) === 'string') {
  106. $value = strtolower($value);
  107. }
  108. }
  109. if (array_key_exists($name, self::$_Options)) {
  110. switch($name) {
  111. case 'number_format' :
  112. if ($value == 'standard') {
  113. $locale = self::$_Options['locale'];
  114. if (isset($options['locale'])) {
  115. $locale = $options['locale'];
  116. }
  117. $format = Zend_Locale_Data::getContent($locale, 'decimalnumberformat');
  118. $options['number_format'] = $format['default'];
  119. } else if ((gettype($value) !== 'string') and ($value !== NULL)) {
  120. throw new Zend_Locale_Exception("Unknown number format type '" . gettype($value) . "'. "
  121. . "Format '$value' must be a valid number format string.");
  122. }
  123. break;
  124. case 'date_format' :
  125. if ($value == 'standard') {
  126. $locale = self::$_Options['locale'];
  127. if (isset($options['locale'])) {
  128. $locale = $options['locale'];
  129. }
  130. $options['date_format'] = Zend_Locale_Format::getDateFormat($locale);
  131. } else if ((gettype($value) !== 'string') and ($value !== NULL)) {
  132. throw new Zend_Locale_Exception("Unknown dateformat type '" . gettype($value) . "'. "
  133. . "Format '$value' must be a valid ISO or PHP date format string.");
  134. } else {
  135. if (((array_key_exists('format_type', $options)) and ($options['format_type'] == 'php')) or
  136. ((!array_key_exists('format_type', $options)) and (self::$_Options['format_type'] == 'php'))) {
  137. $options['date_format'] = Zend_Locale_Format::convertPhpToIsoFormat($value);
  138. }
  139. }
  140. break;
  141. case 'format_type' :
  142. if (($value != 'php') && ($value != 'iso')) {
  143. throw new Zend_Locale_Exception("Unknown date format type '$value'. Only 'iso' and 'php'"
  144. . " are supported.");
  145. }
  146. break;
  147. case 'fix_date' :
  148. if (($value !== true) && ($value !== false)) {
  149. throw new Zend_Locale_Exception("Enabling correction of dates must be either true or false"
  150. . "(fix_date='$value').");
  151. }
  152. break;
  153. case 'locale' :
  154. if (gettype($value) === 'string' && strtolower($value) == 'standard') {
  155. $options['locale'] = new Zend_Locale();
  156. } else if (!empty($value) && (!Zend_Locale::isLocale($value))) {
  157. throw new Zend_Locale_Exception("'" .
  158. (gettype($value) === 'object' ? get_class($value) : $value)
  159. . "' is not a known locale.");
  160. }
  161. break;
  162. case 'cache' :
  163. if ($value instanceof Zend_Cache_Core) {
  164. Zend_Locale_Data::setCache($value);
  165. }
  166. break;
  167. case 'precision' :
  168. if ($value === NULL) {
  169. $value = -1;
  170. }
  171. if (($value < -1) || ($value > 30)) {
  172. throw new Zend_Locale_Exception("'$value' precision is not a whole number less than 30.");
  173. }
  174. break;
  175. }
  176. }
  177. else {
  178. throw new Zend_Locale_Exception("Unknown option: '$name' = '$value'");
  179. }
  180. }
  181. return $options;
  182. }
  183. /**
  184. * Changes the numbers/digits within a given string from one script to another
  185. * 'Decimal' representated the stardard numbers 0-9, if a script does not exist
  186. * an exception will be thrown.
  187. *
  188. * Examples for conversion from Arabic to Latin numerals:
  189. * convertNumerals('١١٠ Tests', 'Arab'); -> returns '100 Tests'
  190. * Example for conversion from Latin to Arabic numerals:
  191. * convertNumerals('100 Tests', 'Latn', 'Arab'); -> returns '١١٠ Tests'
  192. *
  193. * @param string $input String to convert
  194. * @param string $from Script to parse, see {@link Zend_Locale::getScriptList()} for details.
  195. * @param string $to OPTIONAL Script to convert to
  196. * @return string Returns the converted input
  197. * @throws Zend_Locale_Exception
  198. */
  199. public static function convertNumerals($input, $from, $to = null)
  200. {
  201. if (is_string($from)) {
  202. $from = ucfirst(strtolower($from));
  203. }
  204. if (!array_key_exists($from, self::$_signs)) {
  205. throw new Zend_Locale_Exception("Unknown script '$from'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");
  206. }
  207. if (is_string($to)) {
  208. $to = ucfirst(strtolower($to));
  209. }
  210. if (($to !== null) and (!array_key_exists($to, self::$_signs))) {
  211. throw new Zend_Locale_Exception("Unknown script '$to'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");
  212. }
  213. if (isset(self::$_signs[$from])) {
  214. for ($X = 0; $X < 10; ++$X) {
  215. $source[$X + 10] = "/" . self::$_signs[$from][$X] . "/u";
  216. }
  217. }
  218. if (isset(self::$_signs[$to])) {
  219. for ($X = 0; $X < 10; ++$X) {
  220. $dest[$X + 10] = self::$_signs[$to][$X];
  221. }
  222. } else {
  223. for ($X = 0; $X < 10; ++$X) {
  224. $dest[$X + 10] = $X;
  225. }
  226. }
  227. return preg_replace($source, $dest, $input);
  228. }
  229. /**
  230. * Returns the first found number from an string
  231. * Parsing depends on given locale (grouping and decimal)
  232. *
  233. * Examples for input:
  234. * ' 2345.4356,1234' = 23455456.1234
  235. * '+23,3452.123' = 233452.123
  236. * ' 12343 ' = 12343
  237. * '-9456km' = -9456
  238. * '0' = 0
  239. * '(-){0,1}(\d+(\.){0,1})*(\,){0,1})\d+'
  240. * '١١٠ Tests' = 110 call: getNumber($string, 'Arab');
  241. *
  242. * @param string $input Input string to parse for numbers
  243. * @param array $options Options: locale, precision. See {@link setOptions()} for details.
  244. * @return integer|string Returns the extracted number
  245. * @throws Zend_Locale_Exception
  246. */
  247. public static function getNumber($input, array $options = array())
  248. {
  249. $options = array_merge(self::$_Options, self::checkOptions($options));
  250. if (!is_string($input)) {
  251. return $input;
  252. }
  253. // Get correct signs for this locale
  254. $symbols = Zend_Locale_Data::getContent($options['locale'],'numbersymbols');
  255. // Parse input locale aware
  256. $regex = '/([' . $symbols['minus'] . '-]){0,1}(\d+(\\' . $symbols['group'] . '){0,1})*(\\' .
  257. $symbols['decimal'] . '){0,1}\d+/';
  258. preg_match($regex, $input, $found);
  259. if (!isset($found[0]))
  260. throw new Zend_Locale_Exception('No value in ' . $input . ' found');
  261. $found = $found[0];
  262. // Change locale input to be standard number
  263. if ($symbols['minus'] != "-")
  264. $found = strtr($found,$symbols['minus'],'-');
  265. $found = str_replace($symbols['group'],'', $found);
  266. // Do precision
  267. if (strpos($found, $symbols['decimal']) !== false) {
  268. if ($symbols['decimal'] != '.') {
  269. $found = str_replace($symbols['decimal'], ".", $found);
  270. }
  271. $pre = substr($found, strpos($found, '.') + 1);
  272. if ($options['precision'] === null) {
  273. $options['precision'] = strlen($pre);
  274. }
  275. if (strlen($pre) >= $options['precision']) {
  276. $found = substr($found, 0, strlen($found) - strlen($pre) + $options['precision']);
  277. }
  278. }
  279. return $found;
  280. }
  281. /**
  282. * Returns a locale formatted number depending on the given options.
  283. * The seperation and fraction sign is used from the set locale.
  284. * ##0.# -> 12345.12345 -> 12345.12345
  285. * ##0.00 -> 12345.12345 -> 12345.12
  286. * ##,##0.00 -> 12345.12345 -> 12,345.12
  287. *
  288. * @param string $input Localized number string
  289. * @param array $options Options: number_format, locale, precision. See {@link setOptions()} for details.
  290. * @return string locale formatted number
  291. */
  292. public static function toNumber($value, array $options = array())
  293. {
  294. // load class within method for speed
  295. require_once 'Zend/Locale/Math.php';
  296. $value = Zend_Locale_Math::normalize($value);
  297. $options = array_merge(self::$_Options, self::checkOptions($options));
  298. if ($options['locale'] instanceof Zend_Locale) {
  299. $options['locale'] = $options['locale']->toString();
  300. }
  301. // Get correct signs for this locale
  302. $symbols = Zend_Locale_Data::getContent($options['locale'], 'numbersymbols');
  303. iconv_set_encoding('internal_encoding', 'UTF-8');
  304. // Get format
  305. $format = $options['number_format'];
  306. if ($format === null) {
  307. $format = Zend_Locale_Data::getContent($options['locale'], 'decimalnumberformat');
  308. $format = $format['default'];
  309. if (iconv_strpos($format, ';') !== false) {
  310. if (call_user_func(Zend_Locale_Math::$comp, $value, 0) < 0) {
  311. $format = iconv_substr($format, iconv_strpos($format, ';') + 1);
  312. } else {
  313. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  314. }
  315. }
  316. } else {
  317. // seperate negative format pattern when avaiable
  318. if (iconv_strpos($format, ';') !== false) {
  319. if (call_user_func(Zend_Locale_Math::$comp, $value, 0) < 0) {
  320. $format = iconv_substr($format, iconv_strpos($format, ';') + 1);
  321. } else {
  322. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  323. }
  324. }
  325. if (strpos($format, '.')) {
  326. if (is_numeric($options['precision'])) {
  327. $value = Zend_Locale_Math::round($value, $options['precision']);
  328. } else {
  329. if (substr($format, strpos($format, '.') + 1, 3) == '###') {
  330. $options['precision'] = null;
  331. } else {
  332. $options['precision'] = strlen(substr($format, strpos($format, '.') + 1,
  333. strrpos($format, '0') - strpos($format, '.')));
  334. $format = substr($format, 0, strpos($format, '.') + 1) . '###'
  335. . substr($format, strrpos($format, '0') + 1);
  336. }
  337. }
  338. } else {
  339. $value = Zend_Locale_Math::round($value, 0);
  340. $options['precision'] = 0;
  341. }
  342. $value = Zend_Locale_Math::normalize($value);
  343. }
  344. // get number parts
  345. if (strlen($value) != strlen(Zend_Locale_Math::round($value, 0))) {
  346. if ($options['precision'] === null) {
  347. $precstr = iconv_substr($value, strlen(Zend_Locale_Math::round($value, 0)) + 1);
  348. } else {
  349. $precstr = iconv_substr($value, strlen(Zend_Locale_Math::round($value, 0)) + 1, $options['precision']);
  350. if (iconv_strlen($precstr) < $options['precision']) {
  351. $precstr = $precstr . str_pad("0", ($options['precision'] - iconv_strlen($precstr)), "0");
  352. }
  353. }
  354. } else {
  355. if ($options['precision'] > 0) {
  356. $precstr = str_pad("0", ($options['precision']), "0");
  357. }
  358. }
  359. if ($options['precision'] === null) {
  360. if (isset($precstr)) {
  361. $options['precision'] = iconv_strlen($precstr);
  362. } else {
  363. $options['precision'] = 0;
  364. }
  365. }
  366. // get fraction and format lengths
  367. if (strpos($value, '.') !== false) {
  368. $number = substr((string) $value, 0, strpos($value, '.'));
  369. } else {
  370. $number = $value;
  371. }
  372. $prec = call_user_func(Zend_Locale_Math::$sub, $value, $number, $options['precision']);
  373. if (iconv_strpos($prec, '-') !== false) {
  374. $prec = iconv_substr($prec, 1);
  375. }
  376. if (($prec == 0) and ($options['precision'] > 0)) {
  377. $prec = "0.0";
  378. }
  379. if (($options['precision'] + 2) > iconv_strlen($prec)) {
  380. $prec = str_pad((string) $prec, $options['precision'] + 2, "0", STR_PAD_RIGHT);
  381. }
  382. if (iconv_strpos($number, '-') !== false) {
  383. $number = iconv_substr($number, 1);
  384. }
  385. $group = iconv_strrpos($format, ',');
  386. $group2 = iconv_strpos ($format, ',');
  387. $point = iconv_strpos ($format, '0');
  388. // Add fraction
  389. $rest = "";
  390. if (($value < 0) && (strpos($format, '.'))) {
  391. $rest = substr(substr($format, strpos($format, '.') + 1), -1, 1);
  392. }
  393. if ($options['precision'] == '0') {
  394. $format = iconv_substr($format, 0, $point) . iconv_substr($format, iconv_strrpos($format, '#') + 2);
  395. } else {
  396. $format = iconv_substr($format, 0, $point) . $symbols['decimal']
  397. . iconv_substr($prec, 2) . iconv_substr($format, iconv_strrpos($format, '#') + 2 + strlen($prec) - 2);
  398. }
  399. if (($value < 0) and ($rest != '0') and ($rest != '#')) {
  400. $format .= $rest;
  401. }
  402. // Add seperation
  403. if ($group == 0) {
  404. // no seperation
  405. $format = $number . iconv_substr($format, $point);
  406. } else if ($group == $group2) {
  407. // only 1 seperation
  408. $seperation = ($point - $group);
  409. for ($x = iconv_strlen($number); $x > $seperation; $x -= $seperation) {
  410. if (iconv_substr($number, 0, $x - $seperation) !== "") {
  411. $number = iconv_substr($number, 0, $x - $seperation) . $symbols['group']
  412. . iconv_substr($number, $x - $seperation);
  413. }
  414. }
  415. $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);
  416. } else {
  417. // 2 seperations
  418. if (iconv_strlen($number) > ($point - $group)) {
  419. $seperation = ($point - $group);
  420. $number = iconv_substr($number, 0, iconv_strlen($number) - $seperation) . $symbols['group']
  421. . iconv_substr($number, iconv_strlen($number) - $seperation);
  422. if ((iconv_strlen($number) - 1) > ($point - $group + 1)) {
  423. $seperation2 = ($group - $group2 - 1);
  424. for ($x = iconv_strlen($number) - $seperation2 - 2; $x > $seperation2; $x -= $seperation2) {
  425. $number = iconv_substr($number, 0, $x - $seperation2) . $symbols['group']
  426. . iconv_substr($number, $x - $seperation2);
  427. }
  428. }
  429. }
  430. $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);
  431. }
  432. // set negative sign
  433. if (call_user_func(Zend_Locale_Math::$comp, $value, 0) < 0) {
  434. if (iconv_strpos($format, '-') === false) {
  435. $format = $symbols['minus'] . $format;
  436. } else {
  437. $format = str_replace('-', $symbols['minus'], $format);
  438. }
  439. }
  440. return (string) $format;
  441. }
  442. /**
  443. * Checks if the input contains a normalized or localized number
  444. *
  445. * @param string $input Localized number string
  446. * @param array $options Options: locale. See {@link setOptions()} for details.
  447. * @return boolean Returns true if a number was found
  448. */
  449. public static function isNumber($input, array $options = array())
  450. {
  451. // Get correct signs for this locale
  452. $symbols = Zend_Locale_Data::getContent($options['locale'],'numbersymbols');
  453. // Parse input locale aware
  454. $regex = '/^([' . $symbols['minus'] . '-]){0,1}(\d+(\\' . $symbols['group']
  455. . '){0,1})*(\\' . $symbols['decimal'] . '){0,1}\d+$/';
  456. preg_match($regex, $input, $found);
  457. if (!isset($found[0]))
  458. return false;
  459. return true;
  460. }
  461. /**
  462. * Alias for getNumber
  463. *
  464. * @param string $value Number to localize
  465. * @param array $options Options: locale, precision. See {@link setOptions()} for details.
  466. * @return float
  467. */
  468. public static function getFloat($input, array $options = array())
  469. {
  470. return floatval(self::getNumber($input, $options));
  471. }
  472. /**
  473. * Returns a locale formatted integer number
  474. * Alias for toNumber()
  475. *
  476. * @param string $value Number to normalize
  477. * @param array $options Options: locale, precision. See {@link setOptions()} for details.
  478. * @return string Locale formatted number
  479. */
  480. public static function toFloat($value, array $options = array())
  481. {
  482. $options['number_format'] = 'standard';
  483. return self::toNumber($value, $options);
  484. }
  485. /**
  486. * Returns if a float was found
  487. * Alias for isNumber()
  488. *
  489. * @param string $input Localized number string
  490. * @param array $options Options: locale. See {@link setOptions()} for details.
  491. * @return boolean Returns true if a number was found
  492. */
  493. public static function isFloat($value, array $options = array())
  494. {
  495. return self::isNumber($value, $options);
  496. }
  497. /**
  498. * Returns the first found integer from an string
  499. * Parsing depends on given locale (grouping and decimal)
  500. *
  501. * Examples for input:
  502. * ' 2345.4356,1234' = 23455456
  503. * '+23,3452.123' = 233452
  504. * ' 12343 ' = 12343
  505. * '-9456km' = -9456
  506. * '0' = 0
  507. * '(-){0,1}(\d+(\.){0,1})*(\,){0,1})\d+'
  508. *
  509. * @param string $input Input string to parse for numbers
  510. * @param array $options Options: locale. See {@link setOptions()} for details.
  511. * @return integer Returns the extracted number
  512. */
  513. public static function getInteger($input, array $options = array())
  514. {
  515. $options['precision'] = 0;
  516. return intval(self::getFloat($input, $options));
  517. }
  518. /**
  519. * Returns a localized number
  520. *
  521. * @param string $value Number to normalize
  522. * @param array $options Options: locale. See {@link setOptions()} for details.
  523. * @return string Locale formatted number
  524. */
  525. public static function toInteger($value, array $options = array())
  526. {
  527. $options['precision'] = 0;
  528. $options['number_format'] = 'standard';
  529. return self::toNumber($value, $options);
  530. }
  531. /**
  532. * Returns if a integer was found
  533. *
  534. * @param string $input Localized number string
  535. * @param array $options Options: locale. See {@link setOptions()} for details.
  536. * @return boolean Returns true if a integer was found
  537. */
  538. public static function isInteger($value, array $options = array())
  539. {
  540. $options['precision'] = 0;
  541. return self::isNumber($value, $options);
  542. }
  543. /**
  544. * Converts a format string from PHP's date format to ISO format
  545. * Remember that Zend Date always returns localized string, so a month name which returns the english
  546. * month in php's date() will return the translated month name with this function... use 'en' as locale
  547. * if you are in need of the original english names
  548. *
  549. * The conversion has the following restrictions:
  550. * 'a', 'A' - Meridiem is not explicit upper/lowercase, you have to upper/lowercase the translated value yourself
  551. *
  552. * @param string $format Format string in PHP's date format
  553. * @return string Format string in ISO format
  554. */
  555. public static function convertPhpToIsoFormat($format)
  556. {
  557. $convert = array('d' => 'dd' , 'D' => 'EE' , 'j' => 'd' , 'l' => 'EEEE', 'N' => 'e' , 'S' => 'SS' ,
  558. 'w' => 'eee' , 'z' => 'D' , 'W' => 'w' , 'F' => 'MMMM', 'm' => 'MM' , 'M' => 'MMM' ,
  559. 'n' => 'M' , 't' => 'ddd' , 'L' => 'l' , 'o' => 'YYYY', 'Y' => 'yyyy', 'y' => 'yy' ,
  560. 'a' => 'a' , 'A' => 'a' , 'B' => 'B' , 'g' => 'h' , 'G' => 'H' , 'h' => 'hh' ,
  561. 'H' => 'HH' , 'i' => 'mm' , 's' => 'ss' , 'e' => 'zzzz', 'I' => 'I' , 'O' => 'Z' ,
  562. 'P' => 'ZZZZ', 'T' => 'z' , 'Z' => 'X' , 'c' => 'yyyy-MM-ddTHH:mm:ssZZZZ',
  563. 'r' => 'r' , 'U' => 'U');
  564. $values = str_split($format);
  565. foreach ($values as $key => $value) {
  566. if (array_key_exists($value, $convert)) {
  567. $values[$key] = $convert[$value];
  568. }
  569. }
  570. return join($values);
  571. }
  572. /**
  573. * Parse date and split in named array fields
  574. *
  575. * @param string $date Date string to parse
  576. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  577. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  578. */
  579. private static function _parseDate($date, $options)
  580. {
  581. $options = array_merge(self::$_Options, self::checkOptions($options));
  582. $test = array('h', 'H', 'm', 's', 'y', 'Y', 'M', 'd', 'D', 'E', 'S', 'l', 'B', 'I',
  583. 'X', 'r', 'U', 'G', 'w', 'e', 'a', 'A', 'Z', 'z', 'v');
  584. $format = $options['date_format'];
  585. foreach (str_split($format) as $splitted) {
  586. if ((!in_array($splitted, $test)) and (ctype_alpha($splitted))) {
  587. throw new Zend_Locale_Exception("Unable to parse the date format string '" . $format
  588. . "' at letter '$splitted'");
  589. }
  590. }
  591. $number = $date; // working copy
  592. $result['date_format'] = $format; // save the format used to normalize $number (convenience)
  593. $result['locale'] = $options['locale']; // save the locale used to normalize $number (convenience)
  594. $day = iconv_strpos($format, 'd');
  595. $month = iconv_strpos($format, 'M');
  596. $year = iconv_strpos($format, 'y');
  597. $hour = iconv_strpos($format, 'H');
  598. $min = iconv_strpos($format, 'm');
  599. $sec = iconv_strpos($format, 's');
  600. $am = null;
  601. if ($hour === false) {
  602. $hour = iconv_strpos($format, 'h');
  603. }
  604. if ($year === false) {
  605. $year = iconv_strpos($format, 'Y');
  606. }
  607. if ($day === false) {
  608. $day = iconv_strpos($format, 'E');
  609. if ($day === false) {
  610. $day = iconv_strpos($format, 'D');
  611. }
  612. }
  613. if ($day !== false) {
  614. $parse[$day] = 'd';
  615. if (!empty($options['locale']) && ($options['locale'] !== 'root') &&
  616. (!is_object($options['locale']) || ($options['locale']->toString() !== 'root'))) {
  617. // erase day string
  618. $daylist = Zend_Locale_Data::getContent($options['locale'], 'daylist',
  619. array('gregorian', 'format', 'wide'));
  620. foreach($daylist as $key => $name) {
  621. if (iconv_strpos($number, $name) !== false) {
  622. $number = str_replace($name, "EEEE", $number);
  623. break;
  624. }
  625. }
  626. }
  627. }
  628. $position = false;
  629. if ($month !== false) {
  630. $parse[$month] = 'M';
  631. if (!empty($options['locale']) && ($options['locale'] !== 'root') &&
  632. (!is_object($options['locale']) || ($options['locale']->toString() !== 'root'))) {
  633. // prepare to convert month name to their numeric equivalents, if requested,
  634. // and we have a $options['locale']
  635. $position = self::_replaceMonth($number, Zend_Locale_Data::getContent($options['locale'],
  636. 'monthlist', array('gregorian', 'format', 'wide')));
  637. if ($position === false) {
  638. $position = self::_replaceMonth($number, Zend_Locale_Data::getContent($options['locale'],
  639. 'monthlist', array('gregorian', 'format', 'abbreviated')));
  640. }
  641. }
  642. }
  643. if ($year !== false) {
  644. $parse[$year] = 'y';
  645. }
  646. if ($hour !== false) {
  647. $parse[$hour] = 'H';
  648. }
  649. if ($min !== false) {
  650. $parse[$min] = 'm';
  651. }
  652. if ($sec !== false) {
  653. $parse[$sec] = 's';
  654. }
  655. if (empty($parse)) {
  656. throw new Zend_Locale_Exception("unknown date format, neither date nor time in '" . $format . "' found");
  657. }
  658. ksort($parse);
  659. // get daytime
  660. if (iconv_strpos($format, 'a') !== false) {
  661. $daytime = Zend_Locale_Data::getContent($options['locale'], 'daytime', 'gregorian');
  662. if (iconv_strpos(strtoupper($number), strtoupper($daytime['am'])) !== false) {
  663. $am = true;
  664. } else if (iconv_strpos(strtoupper($number), strtoupper($daytime['pm'])) !== false) {
  665. $am = false;
  666. }
  667. }
  668. // split number parts
  669. $split = false;
  670. preg_match_all('/\d+/u', $number, $splitted);
  671. if (count($splitted[0]) == 0) {
  672. throw new Zend_Locale_Exception("No date part in '$date' found.");
  673. }
  674. if (count($splitted[0]) == 1) {
  675. $split = 0;
  676. }
  677. $cnt = 0;
  678. foreach($parse as $key => $value) {
  679. switch($value) {
  680. case 'd':
  681. if ($split === false) {
  682. if (count($splitted[0]) > $cnt) {
  683. $result['day'] = $splitted[0][$cnt];
  684. }
  685. } else {
  686. $result['day'] = iconv_substr($splitted[0][0], $split, 2);
  687. $split += 2;
  688. }
  689. ++$cnt;
  690. break;
  691. case 'M':
  692. if ($split === false) {
  693. if (count($splitted[0]) > $cnt) {
  694. $result['month'] = $splitted[0][$cnt];
  695. }
  696. } else {
  697. $result['month'] = iconv_substr($splitted[0][0], $split, 2);
  698. $split += 2;
  699. }
  700. ++$cnt;
  701. break;
  702. case 'y':
  703. $length = 2;
  704. if ((iconv_substr($format, $year, 4) == 'yyyy')
  705. || (iconv_substr($format, $year, 4) == 'YYYY')) {
  706. $length = 4;
  707. }
  708. if ($split === false) {
  709. if (count($splitted[0]) > $cnt) {
  710. $result['year'] = $splitted[0][$cnt];
  711. }
  712. } else {
  713. $result['year'] = iconv_substr($splitted[0][0], $split, $length);
  714. $split += $length;
  715. }
  716. ++$cnt;
  717. break;
  718. case 'H':
  719. if ($split === false) {
  720. if (count($splitted[0]) > $cnt) {
  721. $result['hour'] = $splitted[0][$cnt];
  722. }
  723. } else {
  724. $result['hour'] = iconv_substr($splitted[0][0], $split, 2);
  725. $split += 2;
  726. }
  727. ++$cnt;
  728. break;
  729. case 'm':
  730. if ($split === false) {
  731. if (count($splitted[0]) > $cnt) {
  732. $result['minute'] = $splitted[0][$cnt];
  733. }
  734. } else {
  735. $result['minute'] = iconv_substr($splitted[0][0], $split, 2);
  736. $split += 2;
  737. }
  738. ++$cnt;
  739. break;
  740. case 's':
  741. if ($split === false) {
  742. if (count($splitted[0]) > $cnt) {
  743. $result['second'] = $splitted[0][$cnt];
  744. }
  745. } else {
  746. $result['second'] = iconv_substr($splitted[0][0], $split, 2);
  747. $split += 2;
  748. }
  749. ++$cnt;
  750. break;
  751. }
  752. }
  753. // AM/PM correction
  754. if ($hour !== false) {
  755. if (($am === true) and ($result['hour'] == 12)){
  756. $result['hour'] = 0;
  757. } else if (($am === false) and ($result['hour'] != 12)) {
  758. $result['hour'] += 12;
  759. }
  760. }
  761. if ($options['fix_date'] === true) {
  762. $result['fixed'] = 0; // nothing has been "fixed" by swapping date parts around (yet)
  763. }
  764. if ($day !== false) {
  765. // fix false month
  766. if (isset($result['day']) and isset($result['month'])) {
  767. if (($position !== false) and ((iconv_strpos($date, $result['day']) === false) or
  768. (isset($result['year']) and (iconv_strpos($date, $result['year']) === false)))) {
  769. if ($options['fix_date'] !== true) {
  770. throw new Zend_Locale_Exception("unable to parse date '$date' using '" . $format
  771. . "' (false month, $position, $month)");
  772. }
  773. $temp = $result['day'];
  774. $result['day'] = $result['month'];
  775. $result['month'] = $temp;
  776. $result['fixed'] = 1;
  777. }
  778. }
  779. // fix switched values d <> y
  780. if (isset($result['day']) and isset($result['year'])) {
  781. if ($result['day'] > 31) {
  782. if ($options['fix_date'] !== true) {
  783. throw new Zend_Locale_Exception("unable to parse date '$date' using '"
  784. . $format . "' (d <> y)");
  785. }
  786. $temp = $result['year'];
  787. $result['year'] = $result['day'];
  788. $result['day'] = $temp;
  789. $result['fixed'] = 2;
  790. }
  791. }
  792. // fix switched values M <> y
  793. if (isset($result['month']) and isset($result['year'])) {
  794. if ($result['month'] > 31) {
  795. if ($options['fix_date'] !== true) {
  796. throw new Zend_Locale_Exception("unable to parse date '$date' using '"
  797. . $format . "' (M <> y)");
  798. }
  799. $temp = $result['year'];
  800. $result['year'] = $result['month'];
  801. $result['month'] = $temp;
  802. $result['fixed'] = 3;
  803. }
  804. }
  805. // fix switched values M <> d
  806. if (isset($result['month']) and isset($result['day'])) {
  807. if ($result['month'] > 12) {
  808. if ($options['fix_date'] !== true || $result['month'] > 31) {
  809. throw new Zend_Locale_Exception("unable to parse date '$date' using '"
  810. . $format . "' (M <> d)");
  811. }
  812. $temp = $result['day'];
  813. $result['day'] = $result['month'];
  814. $result['month'] = $temp;
  815. $result['fixed'] = 4;
  816. }
  817. }
  818. }
  819. return $result;
  820. }
  821. /**
  822. * Search $number for a month name found in $monthlist, and replace if found.
  823. *
  824. * @param string $number Date string (modified)
  825. * @param array $monthlist List of month names
  826. *
  827. * @return int|false Position of replaced string (false if nothing replaced)
  828. */
  829. protected static function _replaceMonth(&$number, $monthlist)
  830. {
  831. // If $locale was invalid, $monthlist will default to a "root" identity
  832. // mapping for each month number from 1 to 12.
  833. // If no $locale was given, or $locale was invalid, do not use this identity mapping to normalize.
  834. // Otherwise, translate locale aware month names in $number to their numeric equivalents.
  835. $position = false;
  836. if ($monthlist && $monthlist[1] != 1) {
  837. foreach($monthlist as $key => $name) {
  838. if (($position = iconv_strpos($number, $name)) !== false) {
  839. if ($key < 10) {
  840. $key = "0" . $key;
  841. }
  842. $number = str_replace($name, $key, $number);
  843. return $position;
  844. }
  845. }
  846. }
  847. return false;
  848. }
  849. /**
  850. * Returns the default date format for $locale.
  851. *
  852. * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')
  853. * @return string format
  854. * @throws Zend_Locale_Exception throws an exception when locale data is broken
  855. */
  856. public static function getDateFormat($locale = null)
  857. {
  858. $format = Zend_Locale_Data::getContent($locale, 'defdateformat', 'gregorian');
  859. if (!array_key_exists('default', $format)) {
  860. throw new Zend_Locale_Exception("failed to receive data from locale $locale");
  861. }
  862. $format = $format['default'];
  863. $format = Zend_Locale_Data::getContent($locale, 'dateformat', array('gregorian', $format));
  864. if (!array_key_exists('pattern', $format)) {
  865. throw new Zend_Locale_Exception("failed to receive data from locale $locale");
  866. }
  867. return $format['pattern'];
  868. }
  869. /**
  870. * Returns an array with the normalized date from an locale date
  871. * a input of 10.01.2006 without a $locale would return:
  872. * array ('day' => 10, 'month' => 1, 'year' => 2006)
  873. * The 'locale' option is only used to convert human readable day
  874. * and month names to their numeric equivalents.
  875. * The 'format' option allows specification of self-defined date formats,
  876. * when not using the default format for the 'locale'.
  877. *
  878. * @param string $date Date string
  879. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  880. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  881. */
  882. public static function getDate($date, array $options = array())
  883. {
  884. $options = array_merge(self::$_Options, self::checkOptions($options));
  885. if (empty($options['date_format'])) {
  886. $options['format_type'] = 'iso';
  887. $options['date_format'] = self::getDateFormat($options['locale']);
  888. }
  889. return self::_parseDate($date, $options);
  890. }
  891. /**
  892. * Returns if the given datestring contains all date parts from the given format.
  893. * If no format is given, the standard date format from the locale is used
  894. * If you want to check if the date is a proper date you should use Zend_Date::isDate()
  895. *
  896. * @param string $date Date string
  897. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  898. * @return boolean
  899. */
  900. public static function checkDateFormat($date, array $options = array())
  901. {
  902. try {
  903. $date = self::getDate($date, $options);
  904. } catch (Exception $e) {
  905. return false;
  906. }
  907. if (empty($options['date_format'])) {
  908. $options['format_type'] = 'iso';
  909. $options['date_format'] = self::getDateFormat($options['locale']);
  910. }
  911. $options = array_merge(self::$_Options, self::checkOptions($options));
  912. // day expected but not parsed
  913. if ((iconv_strpos($options['date_format'], 'd') !== false) and (!isset($date['day']) or ($date['day'] == ""))) {
  914. return false;
  915. }
  916. // month expected but not parsed
  917. if ((iconv_strpos($options['date_format'], 'M') !== false) and (!isset($date['month']) or ($date['month'] == ""))) {
  918. return false;
  919. }
  920. // year expected but not parsed
  921. if (((iconv_strpos($options['date_format'], 'Y') !== false) or
  922. (iconv_strpos($options['date_format'], 'y') !== false)) and (!isset($date['year']) or ($date['year'] == ""))) {
  923. return false;
  924. }
  925. // second expected but not parsed
  926. if ((iconv_strpos($options['date_format'], 's') !== false) and (!isset($date['second']) or ($date['second'] == ""))) {
  927. return false;
  928. }
  929. // minute expected but not parsed
  930. if ((iconv_strpos($options['date_format'], 'm') !== false) and (!isset($date['minute']) or ($date['minute'] == ""))) {
  931. return false;
  932. }
  933. // hour expected but not parsed
  934. if (((iconv_strpos($options['date_format'], 'H') !== false) or
  935. (iconv_strpos($options['date_format'], 'h') !== false)) and (!isset($date['hour']) or ($date['hour'] == ""))) {
  936. return false;
  937. }
  938. return true;
  939. }
  940. /**
  941. * Returns the default time format for $locale.
  942. *
  943. * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')
  944. * @return string format
  945. */
  946. public static function getTimeFormat($locale = null)
  947. {
  948. $format = Zend_Locale_Data::getContent($locale, 'deftimeformat', 'gregorian');
  949. $format = $format['default'];
  950. $format = Zend_Locale_Data::getContent($locale, 'timeformat', array('gregorian', $format));
  951. return $format['pattern'];
  952. }
  953. /**
  954. * Returns an array with 'hour', 'minute', and 'second' elements extracted from $time
  955. * according to the order described in $format. For a format of 'H:m:s', and
  956. * an input of 11:20:55, getTime() would return:
  957. * array ('hour' => 11, 'minute' => 20, 'second' => 55)
  958. * The optional $locale parameter may be used to help extract times from strings
  959. * containing both a time and a day or month name.
  960. *
  961. * @param string $time Time string
  962. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  963. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  964. */
  965. public static function getTime($time, array $options = array())
  966. {
  967. $options = array_merge(self::$_Options, self::checkOptions($options));
  968. if (empty($options['date_format'])) {
  969. $options['format_type'] = 'iso';
  970. $options['date_format'] = self::getTimeFormat($options['locale']);
  971. }
  972. return self::_parseDate($time, $options);
  973. }
  974. }