PageRenderTime 63ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Zend/Locale/Format.php

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