Format.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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$
  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 = 'auto';
  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. 'disableCache' => false,
  43. 'precision' => null);
  44. /**
  45. * Sets class wide options, if no option was given, the actual set options will be returned
  46. * The 'precision' option of a value is used to truncate or stretch extra digits. -1 means not to touch the extra digits.
  47. * The 'locale' option helps when parsing numbers and dates using separators and month names.
  48. * The date format 'format_type' option selects between CLDR/ISO date format specifier tokens and PHP's date() tokens.
  49. * The 'fix_date' option enables or disables heuristics that attempt to correct invalid dates.
  50. * The 'number_format' option can be used to specify a default number format string
  51. * The 'date_format' option can be used to specify a default date format string, but beware of using getDate(),
  52. * checkDateFormat() and getTime() after using setOptions() with a 'format'. To use these four methods
  53. * with the default date format for a locale, use array('date_format' => null, 'locale' => $locale) for their options.
  54. *
  55. * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,
  56. * locale = Zend_Locale | locale string, precision = whole number between -1 and 30
  57. * @throws Zend_Locale_Exception
  58. * @return Options array if no option was given
  59. */
  60. public static function setOptions(array $options = array())
  61. {
  62. self::$_options = self::_checkOptions($options) + self::$_options;
  63. return self::$_options;
  64. }
  65. /**
  66. * Internal function for checking the options array of proper input values
  67. * See {@link setOptions()} for details.
  68. *
  69. * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,
  70. * locale = Zend_Locale | locale string, precision = whole number between -1 and 30
  71. * @throws Zend_Locale_Exception
  72. * @return Options array if no option was given
  73. */
  74. private static function _checkOptions(array $options = array())
  75. {
  76. if (count($options) == 0) {
  77. return self::$_options;
  78. }
  79. foreach ($options as $name => $value) {
  80. $name = strtolower($name);
  81. if ($name !== 'locale') {
  82. if (gettype($value) === 'string') {
  83. $value = strtolower($value);
  84. }
  85. }
  86. switch($name) {
  87. case 'number_format' :
  88. if ($value == Zend_Locale_Format::STANDARD) {
  89. $locale = self::$_options['locale'];
  90. if (isset($options['locale'])) {
  91. $locale = $options['locale'];
  92. }
  93. $options['number_format'] = Zend_Locale_Data::getContent($locale, 'decimalnumber');
  94. } else if ((gettype($value) !== 'string') and ($value !== NULL)) {
  95. require_once 'Zend/Locale/Exception.php';
  96. throw new Zend_Locale_Exception("Unknown number format type '" . gettype($value) . "'. "
  97. . "Format '$value' must be a valid number format string.");
  98. }
  99. break;
  100. case 'date_format' :
  101. if ($value == Zend_Locale_Format::STANDARD) {
  102. $locale = self::$_options['locale'];
  103. if (isset($options['locale'])) {
  104. $locale = $options['locale'];
  105. }
  106. $options['date_format'] = Zend_Locale_Format::getDateFormat($locale);
  107. } else if ((gettype($value) !== 'string') and ($value !== NULL)) {
  108. require_once 'Zend/Locale/Exception.php';
  109. throw new Zend_Locale_Exception("Unknown dateformat type '" . gettype($value) . "'. "
  110. . "Format '$value' must be a valid ISO or PHP date format string.");
  111. } else {
  112. if (((isset($options['format_type']) === true) and ($options['format_type'] == 'php')) or
  113. ((isset($options['format_type']) === false) and (self::$_options['format_type'] == 'php'))) {
  114. $options['date_format'] = Zend_Locale_Format::convertPhpToIsoFormat($value);
  115. }
  116. }
  117. break;
  118. case 'format_type' :
  119. if (($value != 'php') && ($value != 'iso')) {
  120. require_once 'Zend/Locale/Exception.php';
  121. throw new Zend_Locale_Exception("Unknown date format type '$value'. Only 'iso' and 'php'"
  122. . " are supported.");
  123. }
  124. break;
  125. case 'fix_date' :
  126. if (($value !== true) && ($value !== false)) {
  127. require_once 'Zend/Locale/Exception.php';
  128. throw new Zend_Locale_Exception("Enabling correction of dates must be either true or false"
  129. . "(fix_date='$value').");
  130. }
  131. break;
  132. case 'locale' :
  133. $options['locale'] = Zend_Locale::findLocale($value);
  134. break;
  135. case 'cache' :
  136. if ($value instanceof Zend_Cache_Core) {
  137. Zend_Locale_Data::setCache($value);
  138. }
  139. break;
  140. case 'disablecache' :
  141. Zend_Locale_Data::disableCache($value);
  142. break;
  143. case 'precision' :
  144. if ($value === NULL) {
  145. $value = -1;
  146. }
  147. if (($value < -1) || ($value > 30)) {
  148. require_once 'Zend/Locale/Exception.php';
  149. throw new Zend_Locale_Exception("'$value' precision is not a whole number less than 30.");
  150. }
  151. break;
  152. default:
  153. require_once 'Zend/Locale/Exception.php';
  154. throw new Zend_Locale_Exception("Unknown option: '$name' = '$value'");
  155. break;
  156. }
  157. }
  158. return $options;
  159. }
  160. /**
  161. * Changes the numbers/digits within a given string from one script to another
  162. * 'Decimal' representated the stardard numbers 0-9, if a script does not exist
  163. * an exception will be thrown.
  164. *
  165. * Examples for conversion from Arabic to Latin numerals:
  166. * convertNumerals('١١٠ Tests', 'Arab'); -> returns '100 Tests'
  167. * Example for conversion from Latin to Arabic numerals:
  168. * convertNumerals('100 Tests', 'Latn', 'Arab'); -> returns '١١٠ Tests'
  169. *
  170. * @param string $input String to convert
  171. * @param string $from Script to parse, see {@link Zend_Locale::getScriptList()} for details.
  172. * @param string $to OPTIONAL Script to convert to
  173. * @return string Returns the converted input
  174. * @throws Zend_Locale_Exception
  175. */
  176. public static function convertNumerals($input, $from, $to = null)
  177. {
  178. $from = strtolower($from);
  179. $source = Zend_Locale_Data::getContent('en', 'numberingsystem', $from);
  180. if (empty($source)) {
  181. require_once 'Zend/Locale/Exception.php';
  182. throw new Zend_Locale_Exception("Unknown script '$from'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");
  183. }
  184. if ($to !== null) {
  185. $to = strtolower($to);
  186. $target = Zend_Locale_Data::getContent('en', 'numberingsystem', $to);
  187. if (empty($target)) {
  188. require_once 'Zend/Locale/Exception.php';
  189. throw new Zend_Locale_Exception("Unknown script '$to'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");
  190. }
  191. } else {
  192. $target = '0123456789';
  193. }
  194. for ($x = 0; $x < 10; ++$x) {
  195. $asource[$x] = "/" . iconv_substr($source, $x, 1) . "/u";
  196. $atarget[$x] = iconv_substr($target, $x, 1);
  197. }
  198. return preg_replace($asource, $atarget, $input);
  199. }
  200. /**
  201. * Returns the first found number from an string
  202. * Parsing depends on given locale (grouping and decimal)
  203. *
  204. * Examples for input:
  205. * ' 2345.4356,1234' = 23455456.1234
  206. * '+23,3452.123' = 233452.123
  207. * ' 12343 ' = 12343
  208. * '-9456km' = -9456
  209. * '0' = 0
  210. * '(-){0,1}(\d+(\.){0,1})*(\,){0,1})\d+'
  211. * '١١٠ Tests' = 110 call: getNumber($string, 'Arab');
  212. *
  213. * @param string $input Input string to parse for numbers
  214. * @param array $options Options: locale, precision. See {@link setOptions()} for details.
  215. * @return string Returns the extracted number
  216. * @throws Zend_Locale_Exception
  217. */
  218. public static function getNumber($input, array $options = array())
  219. {
  220. $options = self::_checkOptions($options) + self::$_options;
  221. if (!is_string($input)) {
  222. return $input;
  223. }
  224. // Get correct signs for this locale
  225. $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');
  226. // Parse input locale aware
  227. $regex = '/([' . $symbols['minus'] . '-]){0,1}(\d+(\\' . $symbols['group'] . '){0,1})*(\\' .
  228. $symbols['decimal'] . '){0,1}\d+/';
  229. preg_match($regex, $input, $found);
  230. if (!isset($found[0])) {
  231. require_once 'Zend/Locale/Exception.php';
  232. throw new Zend_Locale_Exception('No value in ' . $input . ' found');
  233. }
  234. $found = $found[0];
  235. // Change locale input to be default number
  236. if ($symbols['minus'] != "-")
  237. $found = strtr($found,$symbols['minus'],'-');
  238. $found = str_replace($symbols['group'],'', $found);
  239. // Do precision
  240. if (strpos($found, $symbols['decimal']) !== false) {
  241. if ($symbols['decimal'] != '.') {
  242. $found = str_replace($symbols['decimal'], ".", $found);
  243. }
  244. $pre = substr($found, strpos($found, '.') + 1);
  245. if ($options['precision'] === null) {
  246. $options['precision'] = strlen($pre);
  247. }
  248. if (strlen($pre) >= $options['precision']) {
  249. $found = substr($found, 0, strlen($found) - strlen($pre) + $options['precision']);
  250. }
  251. }
  252. return $found;
  253. }
  254. /**
  255. * Returns a locale formatted number depending on the given options.
  256. * The seperation and fraction sign is used from the set locale.
  257. * ##0.# -> 12345.12345 -> 12345.12345
  258. * ##0.00 -> 12345.12345 -> 12345.12
  259. * ##,##0.00 -> 12345.12345 -> 12,345.12
  260. *
  261. * @param string $input Localized number string
  262. * @param array $options Options: number_format, locale, precision. See {@link setOptions()} for details.
  263. * @return string locale formatted number
  264. * @throws Zend_Locale_Exception
  265. */
  266. public static function toNumber($value, array $options = array())
  267. {
  268. // load class within method for speed
  269. require_once 'Zend/Locale/Math.php';
  270. $value = Zend_Locale_Math::normalize($value);
  271. $options = self::_checkOptions($options) + self::$_options;
  272. $options['locale'] = (string) $options['locale'];
  273. // Get correct signs for this locale
  274. $symbols = Zend_Locale_Data::getList($options['locale'], 'symbols');
  275. iconv_set_encoding('internal_encoding', 'UTF-8');
  276. // Get format
  277. $format = $options['number_format'];
  278. if ($format === null) {
  279. $format = Zend_Locale_Data::getContent($options['locale'], 'decimalnumber');
  280. if (iconv_strpos($format, ';') !== false) {
  281. if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $options['precision']) < 0) {
  282. $tmpformat = iconv_substr($format, iconv_strpos($format, ';') + 1);
  283. if ($tmpformat[0] == '(') {
  284. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  285. } else {
  286. $format = $tmpformat;
  287. }
  288. } else {
  289. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  290. }
  291. }
  292. } else {
  293. // seperate negative format pattern when available
  294. if (iconv_strpos($format, ';') !== false) {
  295. if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $options['precision']) < 0) {
  296. $tmpformat = iconv_substr($format, iconv_strpos($format, ';') + 1);
  297. if ($tmpformat[0] == '(') {
  298. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  299. } else {
  300. $format = $tmpformat;
  301. }
  302. } else {
  303. $format = iconv_substr($format, 0, iconv_strpos($format, ';'));
  304. }
  305. }
  306. if (strpos($format, '.')) {
  307. if (is_numeric($options['precision'])) {
  308. $value = Zend_Locale_Math::round($value, $options['precision']);
  309. } else {
  310. if (substr($format, iconv_strpos($format, '.') + 1, 3) == '###') {
  311. $options['precision'] = null;
  312. } else {
  313. $options['precision'] = iconv_strlen(iconv_substr($format, iconv_strpos($format, '.') + 1,
  314. iconv_strrpos($format, '0') - iconv_strpos($format, '.')));
  315. $format = iconv_substr($format, 0, iconv_strpos($format, '.') + 1) . '###'
  316. . iconv_substr($format, iconv_strrpos($format, '0') + 1);
  317. }
  318. }
  319. } else {
  320. $value = Zend_Locale_Math::round($value, 0);
  321. $options['precision'] = 0;
  322. }
  323. $value = Zend_Locale_Math::normalize($value);
  324. }
  325. if (iconv_strpos($format, '0') === false) {
  326. require_once 'Zend/Locale/Exception.php';
  327. throw new Zend_Locale_Exception('Wrong format... missing 0');
  328. }
  329. // get number parts
  330. $pos = iconv_strpos($value, '.');
  331. if ($pos !== false) {
  332. if ($options['precision'] === null) {
  333. $precstr = iconv_substr($value, $pos + 1);
  334. } else {
  335. $precstr = iconv_substr($value, $pos + 1, $options['precision']);
  336. if (iconv_strlen($precstr) < $options['precision']) {
  337. $precstr = $precstr . str_pad("0", ($options['precision'] - iconv_strlen($precstr)), "0");
  338. }
  339. }
  340. } else {
  341. if ($options['precision'] > 0) {
  342. $precstr = str_pad("0", ($options['precision']), "0");
  343. }
  344. }
  345. if ($options['precision'] === null) {
  346. if (isset($precstr)) {
  347. $options['precision'] = iconv_strlen($precstr);
  348. } else {
  349. $options['precision'] = 0;
  350. }
  351. }
  352. // get fraction and format lengths
  353. if (strpos($value, '.') !== false) {
  354. $number = substr((string) $value, 0, strpos($value, '.'));
  355. } else {
  356. $number = $value;
  357. }
  358. $prec = call_user_func(Zend_Locale_Math::$sub, $value, $number, $options['precision']);
  359. $prec = Zend_Locale_Math::normalize($prec);
  360. if (iconv_strpos($prec, '-') !== false) {
  361. $prec = iconv_substr($prec, 1);
  362. }
  363. if (($prec == 0) and ($options['precision'] > 0)) {
  364. $prec = "0.0";
  365. }
  366. if (($options['precision'] + 2) > iconv_strlen($prec)) {
  367. $prec = str_pad((string) $prec, $options['precision'] + 2, "0", STR_PAD_RIGHT);
  368. }
  369. if (iconv_strpos($number, '-') !== false) {
  370. $number = iconv_substr($number, 1);
  371. }
  372. $group = iconv_strrpos($format, ',');
  373. $group2 = iconv_strpos ($format, ',');
  374. $point = iconv_strpos ($format, '0');
  375. // Add fraction
  376. $rest = "";
  377. if (iconv_strpos($format, '.')) {
  378. $rest = iconv_substr($format, iconv_strpos($format, '.') + 1);
  379. $length = iconv_strlen($rest);
  380. for($x = 0; $x < $length; ++$x) {
  381. if (($rest[0] == '0') || ($rest[0] == '#')) {
  382. $rest = iconv_substr($rest, 1);
  383. }
  384. }
  385. $format = iconv_substr($format, 0, iconv_strlen($format) - iconv_strlen($rest));
  386. }
  387. if ($options['precision'] == '0') {
  388. if (iconv_strrpos($format, '-') != 0) {
  389. $format = iconv_substr($format, 0, $point)
  390. . iconv_substr($format, iconv_strrpos($format, '#') + 2);
  391. } else {
  392. $format = iconv_substr($format, 0, $point);
  393. }
  394. } else {
  395. $format = iconv_substr($format, 0, $point) . $symbols['decimal']
  396. . iconv_substr($prec, 2);
  397. }
  398. $format .= $rest;
  399. // Add seperation
  400. if ($group == 0) {
  401. // no seperation
  402. $format = $number . iconv_substr($format, $point);
  403. } else if ($group == $group2) {
  404. // only 1 seperation
  405. $seperation = ($point - $group);
  406. for ($x = iconv_strlen($number); $x > $seperation; $x -= $seperation) {
  407. if (iconv_substr($number, 0, $x - $seperation) !== "") {
  408. $number = iconv_substr($number, 0, $x - $seperation) . $symbols['group']
  409. . iconv_substr($number, $x - $seperation);
  410. }
  411. }
  412. $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);
  413. } else {
  414. // 2 seperations
  415. if (iconv_strlen($number) > ($point - $group)) {
  416. $seperation = ($point - $group);
  417. $number = iconv_substr($number, 0, iconv_strlen($number) - $seperation) . $symbols['group']
  418. . iconv_substr($number, iconv_strlen($number) - $seperation);
  419. if ((iconv_strlen($number) - 1) > ($point - $group + 1)) {
  420. $seperation2 = ($group - $group2 - 1);
  421. for ($x = iconv_strlen($number) - $seperation2 - 2; $x > $seperation2; $x -= $seperation2) {
  422. $number = iconv_substr($number, 0, $x - $seperation2) . $symbols['group']
  423. . iconv_substr($number, $x - $seperation2);
  424. }
  425. }
  426. }
  427. $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);
  428. }
  429. // set negative sign
  430. if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $options['precision']) < 0) {
  431. if (iconv_strpos($format, '-') === false) {
  432. $format = $symbols['minus'] . $format;
  433. } else {
  434. $format = str_replace('-', $symbols['minus'], $format);
  435. }
  436. }
  437. return (string) $format;
  438. }
  439. /**
  440. * Checks if the input contains a normalized or localized number
  441. *
  442. * @param string $input Localized number string
  443. * @param array $options Options: locale. See {@link setOptions()} for details.
  444. * @return boolean Returns true if a number was found
  445. */
  446. public static function isNumber($input, array $options = array())
  447. {
  448. $options = self::_checkOptions($options) + self::$_options;
  449. // Get correct signs for this locale
  450. $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');
  451. // Parse input locale aware
  452. $regex = '/^[' . $symbols['minus'] . $symbols['plus'] . '-+]?'
  453. . '\d(\d*(\\' . $symbols['group'] . ')?\d+)*'
  454. . '((\\' . $symbols['decimal'] . ')\d*)?([' . $symbols['exponent'] . 'eE]'
  455. . '([' . $symbols['minus'] . $symbols['plus'] . '+-])?\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'] = Zend_Locale_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'] = Zend_Locale_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. if (!self::isNumber($value, $options)) {
  541. return false;
  542. }
  543. if (self::getInteger($value, $options) == self::getFloat($value, $options)) {
  544. return true;
  545. }
  546. return false;
  547. }
  548. /**
  549. * Converts a format string from PHP's date format to ISO format
  550. * Remember that Zend Date always returns localized string, so a month name which returns the english
  551. * month in php's date() will return the translated month name with this function... use 'en' as locale
  552. * if you are in need of the original english names
  553. *
  554. * The conversion has the following restrictions:
  555. * 'a', 'A' - Meridiem is not explicit upper/lowercase, you have to upper/lowercase the translated value yourself
  556. *
  557. * @param string $format Format string in PHP's date format
  558. * @return string Format string in ISO format
  559. */
  560. public static function convertPhpToIsoFormat($format)
  561. {
  562. $convert = array('d' => 'dd' , 'D' => 'EE' , 'j' => 'd' , 'l' => 'EEEE', 'N' => 'e' , 'S' => 'SS' ,
  563. 'w' => 'eee' , 'z' => 'D' , 'W' => 'ww' , 'F' => 'MMMM', 'm' => 'MM' , 'M' => 'MMM' ,
  564. 'n' => 'M' , 't' => 'ddd' , 'L' => 'l' , 'o' => 'YYYY', 'Y' => 'yyyy', 'y' => 'yy' ,
  565. 'a' => 'a' , 'A' => 'a' , 'B' => 'B' , 'g' => 'h' , 'G' => 'H' , 'h' => 'hh' ,
  566. 'H' => 'HH' , 'i' => 'mm' , 's' => 'ss' , 'e' => 'zzzz', 'I' => 'I' , 'O' => 'Z' ,
  567. 'P' => 'ZZZZ', 'T' => 'z' , 'Z' => 'X' , 'c' => 'yyyy-MM-ddTHH:mm:ssZZZZ',
  568. 'r' => 'r' , 'U' => 'U');
  569. $values = str_split($format);
  570. foreach ($values as $key => $value) {
  571. if (isset($convert[$value]) === true) {
  572. $values[$key] = $convert[$value];
  573. }
  574. }
  575. return join($values);
  576. }
  577. /**
  578. * Parse date and split in named array fields
  579. *
  580. * @param string $date Date string to parse
  581. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  582. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  583. */
  584. private static function _parseDate($date, $options)
  585. {
  586. $options = self::_checkOptions($options) + self::$_options;
  587. $test = array('h', 'H', 'm', 's', 'y', 'Y', 'M', 'd', 'D', 'E', 'S', 'l', 'B', 'I',
  588. 'X', 'r', 'U', 'G', 'w', 'e', 'a', 'A', 'Z', 'z', 'v');
  589. $format = $options['date_format'];
  590. $number = $date; // working copy
  591. $result['date_format'] = $format; // save the format used to normalize $number (convenience)
  592. $result['locale'] = $options['locale']; // save the locale used to normalize $number (convenience)
  593. $day = iconv_strpos($format, 'd');
  594. $month = iconv_strpos($format, 'M');
  595. $year = iconv_strpos($format, 'y');
  596. $hour = iconv_strpos($format, 'H');
  597. $min = iconv_strpos($format, 'm');
  598. $sec = iconv_strpos($format, 's');
  599. $am = null;
  600. if ($hour === false) {
  601. $hour = iconv_strpos($format, 'h');
  602. }
  603. if ($year === false) {
  604. $year = iconv_strpos($format, 'Y');
  605. }
  606. if ($day === false) {
  607. $day = iconv_strpos($format, 'E');
  608. if ($day === false) {
  609. $day = iconv_strpos($format, 'D');
  610. }
  611. }
  612. if ($day !== false) {
  613. $parse[$day] = 'd';
  614. if (!empty($options['locale']) && ($options['locale'] !== 'root') &&
  615. (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {
  616. // erase day string
  617. $daylist = Zend_Locale_Data::getList($options['locale'], 'day');
  618. foreach($daylist as $key => $name) {
  619. if (iconv_strpos($number, $name) !== false) {
  620. $number = str_replace($name, "EEEE", $number);
  621. break;
  622. }
  623. }
  624. }
  625. }
  626. $position = false;
  627. if ($month !== false) {
  628. $parse[$month] = 'M';
  629. if (!empty($options['locale']) && ($options['locale'] !== 'root') &&
  630. (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {
  631. // prepare to convert month name to their numeric equivalents, if requested,
  632. // and we have a $options['locale']
  633. $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],
  634. 'month'));
  635. if ($position === false) {
  636. $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],
  637. 'month', array('gregorian', 'format', 'abbreviated')));
  638. }
  639. }
  640. }
  641. if ($year !== false) {
  642. $parse[$year] = 'y';
  643. }
  644. if ($hour !== false) {
  645. $parse[$hour] = 'H';
  646. }
  647. if ($min !== false) {
  648. $parse[$min] = 'm';
  649. }
  650. if ($sec !== false) {
  651. $parse[$sec] = 's';
  652. }
  653. if (empty($parse)) {
  654. require_once 'Zend/Locale/Exception.php';
  655. throw new Zend_Locale_Exception("Unknown date format, neither date nor time in '" . $format . "' found");
  656. }
  657. ksort($parse);
  658. // get daytime
  659. if (iconv_strpos($format, 'a') !== false) {
  660. if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'am'))) !== false) {
  661. $am = true;
  662. } else if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'pm'))) !== false) {
  663. $am = false;
  664. }
  665. }
  666. // split number parts
  667. $split = false;
  668. preg_match_all('/\d+/u', $number, $splitted);
  669. if (count($splitted[0]) == 0) {
  670. require_once 'Zend/Locale/Exception.php';
  671. throw new Zend_Locale_Exception("No date part in '$date' found.");
  672. }
  673. if (count($splitted[0]) == 1) {
  674. $split = 0;
  675. }
  676. $cnt = 0;
  677. foreach($parse as $key => $value) {
  678. switch($value) {
  679. case 'd':
  680. if ($split === false) {
  681. if (count($splitted[0]) > $cnt) {
  682. $result['day'] = $splitted[0][$cnt];
  683. }
  684. } else {
  685. $result['day'] = iconv_substr($splitted[0][0], $split, 2);
  686. $split += 2;
  687. }
  688. ++$cnt;
  689. break;
  690. case 'M':
  691. if ($split === false) {
  692. if (count($splitted[0]) > $cnt) {
  693. $result['month'] = $splitted[0][$cnt];
  694. }
  695. } else {
  696. $result['month'] = iconv_substr($splitted[0][0], $split, 2);
  697. $split += 2;
  698. }
  699. ++$cnt;
  700. break;
  701. case 'y':
  702. $length = 2;
  703. if ((iconv_substr($format, $year, 4) == 'yyyy')
  704. || (iconv_substr($format, $year, 4) == 'YYYY')) {
  705. $length = 4;
  706. }
  707. if ($split === false) {
  708. if (count($splitted[0]) > $cnt) {
  709. $result['year'] = $splitted[0][$cnt];
  710. }
  711. } else {
  712. $result['year'] = iconv_substr($splitted[0][0], $split, $length);
  713. $split += $length;
  714. }
  715. ++$cnt;
  716. break;
  717. case 'H':
  718. if ($split === false) {
  719. if (count($splitted[0]) > $cnt) {
  720. $result['hour'] = $splitted[0][$cnt];
  721. }
  722. } else {
  723. $result['hour'] = iconv_substr($splitted[0][0], $split, 2);
  724. $split += 2;
  725. }
  726. ++$cnt;
  727. break;
  728. case 'm':
  729. if ($split === false) {
  730. if (count($splitted[0]) > $cnt) {
  731. $result['minute'] = $splitted[0][$cnt];
  732. }
  733. } else {
  734. $result['minute'] = iconv_substr($splitted[0][0], $split, 2);
  735. $split += 2;
  736. }
  737. ++$cnt;
  738. break;
  739. case 's':
  740. if ($split === false) {
  741. if (count($splitted[0]) > $cnt) {
  742. $result['second'] = $splitted[0][$cnt];
  743. }
  744. } else {
  745. $result['second'] = iconv_substr($splitted[0][0], $split, 2);
  746. $split += 2;
  747. }
  748. ++$cnt;
  749. break;
  750. }
  751. }
  752. // AM/PM correction
  753. if ($hour !== false) {
  754. if (($am === true) and ($result['hour'] == 12)){
  755. $result['hour'] = 0;
  756. } else if (($am === false) and ($result['hour'] != 12)) {
  757. $result['hour'] += 12;
  758. }
  759. }
  760. if ($options['fix_date'] === true) {
  761. $result['fixed'] = 0; // nothing has been "fixed" by swapping date parts around (yet)
  762. }
  763. if ($day !== false) {
  764. // fix false month
  765. if (isset($result['day']) and isset($result['month'])) {
  766. if (($position !== false) and ((iconv_strpos($date, $result['day']) === false) or
  767. (isset($result['year']) and (iconv_strpos($date, $result['year']) === false)))) {
  768. if ($options['fix_date'] !== true) {
  769. require_once 'Zend/Locale/Exception.php';
  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. require_once 'Zend/Locale/Exception.php';
  784. throw new Zend_Locale_Exception("Unable to parse date '$date' using '"
  785. . $format . "' (d <> y)");
  786. }
  787. $temp = $result['year'];
  788. $result['year'] = $result['day'];
  789. $result['day'] = $temp;
  790. $result['fixed'] = 2;
  791. }
  792. }
  793. // fix switched values M <> y
  794. if (isset($result['month']) and isset($result['year'])) {
  795. if ($result['month'] > 31) {
  796. if ($options['fix_date'] !== true) {
  797. require_once 'Zend/Locale/Exception.php';
  798. throw new Zend_Locale_Exception("Unable to parse date '$date' using '"
  799. . $format . "' (M <> y)");
  800. }
  801. $temp = $result['year'];
  802. $result['year'] = $result['month'];
  803. $result['month'] = $temp;
  804. $result['fixed'] = 3;
  805. }
  806. }
  807. // fix switched values M <> d
  808. if (isset($result['month']) and isset($result['day'])) {
  809. if ($result['month'] > 12) {
  810. if ($options['fix_date'] !== true || $result['month'] > 31) {
  811. require_once 'Zend/Locale/Exception.php';
  812. throw new Zend_Locale_Exception("Unable to parse date '$date' using '"
  813. . $format . "' (M <> d)");
  814. }
  815. $temp = $result['day'];
  816. $result['day'] = $result['month'];
  817. $result['month'] = $temp;
  818. $result['fixed'] = 4;
  819. }
  820. }
  821. }
  822. if (isset($result['year'])) {
  823. if (((iconv_strlen($result['year']) == 2) && ($result['year'] < 10)) ||
  824. (((iconv_strpos($format, 'yy') !== false) && (iconv_strpos($format, 'yyyy') === false)) ||
  825. ((iconv_strpos($format, 'YY') !== false) && (iconv_strpos($format, 'YYYY') === false)))) {
  826. if (($result['year'] >= 0) && ($result['year'] < 100)) {
  827. if ($result['year'] < 70) {
  828. $result['year'] = (int) $result['year'] + 100;
  829. }
  830. $result['year'] = (int) $result['year'] + 1900;
  831. }
  832. }
  833. }
  834. return $result;
  835. }
  836. /**
  837. * Search $number for a month name found in $monthlist, and replace if found.
  838. *
  839. * @param string $number Date string (modified)
  840. * @param array $monthlist List of month names
  841. *
  842. * @return int|false Position of replaced string (false if nothing replaced)
  843. */
  844. protected static function _replaceMonth(&$number, $monthlist)
  845. {
  846. // If $locale was invalid, $monthlist will default to a "root" identity
  847. // mapping for each month number from 1 to 12.
  848. // If no $locale was given, or $locale was invalid, do not use this identity mapping to normalize.
  849. // Otherwise, translate locale aware month names in $number to their numeric equivalents.
  850. $position = false;
  851. if ($monthlist && $monthlist[1] != 1) {
  852. foreach($monthlist as $key => $name) {
  853. if (($position = iconv_strpos($number, $name)) !== false) {
  854. $number = str_ireplace($name, $key, $number);
  855. return $position;
  856. }
  857. }
  858. }
  859. return false;
  860. }
  861. /**
  862. * Returns the default date format for $locale.
  863. *
  864. * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')
  865. * @return string format
  866. * @throws Zend_Locale_Exception throws an exception when locale data is broken
  867. */
  868. public static function getDateFormat($locale = null)
  869. {
  870. $format = Zend_Locale_Data::getContent($locale, 'date');
  871. if (empty($format)) {
  872. require_once 'Zend/Locale/Exception.php';
  873. throw new Zend_Locale_Exception("failed to receive data from locale $locale");
  874. }
  875. return $format;
  876. }
  877. /**
  878. * Returns an array with the normalized date from an locale date
  879. * a input of 10.01.2006 without a $locale would return:
  880. * array ('day' => 10, 'month' => 1, 'year' => 2006)
  881. * The 'locale' option is only used to convert human readable day
  882. * and month names to their numeric equivalents.
  883. * The 'format' option allows specification of self-defined date formats,
  884. * when not using the default format for the 'locale'.
  885. *
  886. * @param string $date Date string
  887. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  888. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  889. */
  890. public static function getDate($date, array $options = array())
  891. {
  892. $options = self::_checkOptions($options) + self::$_options;
  893. if (empty($options['date_format'])) {
  894. $options['format_type'] = 'iso';
  895. $options['date_format'] = self::getDateFormat($options['locale']);
  896. }
  897. return self::_parseDate($date, $options);
  898. }
  899. /**
  900. * Returns if the given datestring contains all date parts from the given format.
  901. * If no format is given, the default date format from the locale is used
  902. * If you want to check if the date is a proper date you should use Zend_Date::isDate()
  903. *
  904. * @param string $date Date string
  905. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  906. * @return boolean
  907. */
  908. public static function checkDateFormat($date, array $options = array())
  909. {
  910. try {
  911. $date = self::getDate($date, $options);
  912. } catch (Exception $e) {
  913. return false;
  914. }
  915. if (empty($options['date_format'])) {
  916. $options['format_type'] = 'iso';
  917. $options['date_format'] = self::getDateFormat($options['locale']);
  918. }
  919. $options = self::_checkOptions($options) + self::$_options;
  920. // day expected but not parsed
  921. if ((iconv_strpos($options['date_format'], 'd') !== false) and (!isset($date['day']) or ($date['day'] == ""))) {
  922. return false;
  923. }
  924. // month expected but not parsed
  925. if ((iconv_strpos($options['date_format'], 'M') !== false) and (!isset($date['month']) or ($date['month'] == ""))) {
  926. return false;
  927. }
  928. // year expected but not parsed
  929. if (((iconv_strpos($options['date_format'], 'Y') !== false) or
  930. (iconv_strpos($options['date_format'], 'y') !== false)) and (!isset($date['year']) or ($date['year'] == ""))) {
  931. return false;
  932. }
  933. // second expected but not parsed
  934. if ((iconv_strpos($options['date_format'], 's') !== false) and (!isset($date['second']) or ($date['second'] == ""))) {
  935. return false;
  936. }
  937. // minute expected but not parsed
  938. if ((iconv_strpos($options['date_format'], 'm') !== false) and (!isset($date['minute']) or ($date['minute'] == ""))) {
  939. return false;
  940. }
  941. // hour expected but not parsed
  942. if (((iconv_strpos($options['date_format'], 'H') !== false) or
  943. (iconv_strpos($options['date_format'], 'h') !== false)) and (!isset($date['hour']) or ($date['hour'] == ""))) {
  944. return false;
  945. }
  946. return true;
  947. }
  948. /**
  949. * Returns the default time format for $locale.
  950. *
  951. * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')
  952. * @return string format
  953. */
  954. public static function getTimeFormat($locale = null)
  955. {
  956. $format = Zend_Locale_Data::getContent($locale, 'time');
  957. if (empty($format)) {
  958. require_once 'Zend/Locale/Exception.php';
  959. throw new Zend_Locale_Exception("failed to receive data from locale $locale");
  960. }
  961. return $format;
  962. }
  963. /**
  964. * Returns an array with 'hour', 'minute', and 'second' elements extracted from $time
  965. * according to the order described in $format. For a format of 'H:m:s', and
  966. * an input of 11:20:55, getTime() would return:
  967. * array ('hour' => 11, 'minute' => 20, 'second' => 55)
  968. * The optional $locale parameter may be used to help extract times from strings
  969. * containing both a time and a day or month name.
  970. *
  971. * @param string $time Time string
  972. * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.
  973. * @return array Possible array members: day, month, year, hour, minute, second, fixed, format
  974. */
  975. public static function getTime($time, array $options = array())
  976. {
  977. $options = self::_checkOptions($options) + self::$_options;
  978. if (empty($options['date_format'])) {
  979. $options['format_type'] = 'iso';
  980. $options['date_format'] = self::getTimeFormat($options['locale']);
  981. }
  982. return self::_parseDate($time, $options);
  983. }
  984. }