NumberFormat.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Style;
  3. use PhpOffice\PhpSpreadsheet\Calculation\MathTrig;
  4. use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
  5. use PhpOffice\PhpSpreadsheet\Shared\Date;
  6. use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
  7. class NumberFormat extends Supervisor
  8. {
  9. // Pre-defined formats
  10. const FORMAT_GENERAL = 'General';
  11. const FORMAT_TEXT = '@';
  12. const FORMAT_NUMBER = '0';
  13. const FORMAT_NUMBER_00 = '0.00';
  14. const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
  15. const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
  16. const FORMAT_PERCENTAGE = '0%';
  17. const FORMAT_PERCENTAGE_00 = '0.00%';
  18. const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';
  19. const FORMAT_DATE_YYYYMMDD = 'yyyy-mm-dd';
  20. const FORMAT_DATE_DDMMYYYY = 'dd/mm/yyyy';
  21. const FORMAT_DATE_DMYSLASH = 'd/m/yy';
  22. const FORMAT_DATE_DMYMINUS = 'd-m-yy';
  23. const FORMAT_DATE_DMMINUS = 'd-m';
  24. const FORMAT_DATE_MYMINUS = 'm-yy';
  25. const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
  26. const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
  27. const FORMAT_DATE_XLSX16 = 'd-mmm';
  28. const FORMAT_DATE_XLSX17 = 'mmm-yy';
  29. const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
  30. const FORMAT_DATE_DATETIME = 'd/m/yy h:mm';
  31. const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
  32. const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
  33. const FORMAT_DATE_TIME3 = 'h:mm';
  34. const FORMAT_DATE_TIME4 = 'h:mm:ss';
  35. const FORMAT_DATE_TIME5 = 'mm:ss';
  36. const FORMAT_DATE_TIME6 = 'h:mm:ss';
  37. const FORMAT_DATE_TIME7 = 'i:s.S';
  38. const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
  39. const FORMAT_DATE_YYYYMMDDSLASH = 'yyyy/mm/dd;@';
  40. const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-';
  41. const FORMAT_CURRENCY_USD = '$#,##0_-';
  42. const FORMAT_CURRENCY_EUR_SIMPLE = '#,##0.00_-"€"';
  43. const FORMAT_CURRENCY_EUR = '#,##0_-"€"';
  44. const FORMAT_ACCOUNTING_USD = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
  45. const FORMAT_ACCOUNTING_EUR = '_("€"* #,##0.00_);_("€"* \(#,##0.00\);_("€"* "-"??_);_(@_)';
  46. /**
  47. * Excel built-in number formats.
  48. *
  49. * @var array
  50. */
  51. protected static $builtInFormats;
  52. /**
  53. * Excel built-in number formats (flipped, for faster lookups).
  54. *
  55. * @var array
  56. */
  57. protected static $flippedBuiltInFormats;
  58. /**
  59. * Format Code.
  60. *
  61. * @var string
  62. */
  63. protected $formatCode = self::FORMAT_GENERAL;
  64. /**
  65. * Built-in format Code.
  66. *
  67. * @var string
  68. */
  69. protected $builtInFormatCode = 0;
  70. /**
  71. * Create a new NumberFormat.
  72. *
  73. * @param bool $isSupervisor Flag indicating if this is a supervisor or not
  74. * Leave this value at default unless you understand exactly what
  75. * its ramifications are
  76. * @param bool $isConditional Flag indicating if this is a conditional style or not
  77. * Leave this value at default unless you understand exactly what
  78. * its ramifications are
  79. */
  80. public function __construct($isSupervisor = false, $isConditional = false)
  81. {
  82. // Supervisor?
  83. parent::__construct($isSupervisor);
  84. if ($isConditional) {
  85. $this->formatCode = null;
  86. $this->builtInFormatCode = false;
  87. }
  88. }
  89. /**
  90. * Get the shared style component for the currently active cell in currently active sheet.
  91. * Only used for style supervisor.
  92. *
  93. * @return NumberFormat
  94. */
  95. public function getSharedComponent()
  96. {
  97. return $this->parent->getSharedComponent()->getNumberFormat();
  98. }
  99. /**
  100. * Build style array from subcomponents.
  101. *
  102. * @param array $array
  103. *
  104. * @return array
  105. */
  106. public function getStyleArray($array)
  107. {
  108. return ['numberFormat' => $array];
  109. }
  110. /**
  111. * Apply styles from array.
  112. *
  113. * <code>
  114. * $spreadsheet->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
  115. * [
  116. * 'formatCode' => NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
  117. * ]
  118. * );
  119. * </code>
  120. *
  121. * @param array $pStyles Array containing style information
  122. *
  123. * @throws PhpSpreadsheetException
  124. *
  125. * @return $this
  126. */
  127. public function applyFromArray(array $pStyles)
  128. {
  129. if ($this->isSupervisor) {
  130. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
  131. } else {
  132. if (isset($pStyles['formatCode'])) {
  133. $this->setFormatCode($pStyles['formatCode']);
  134. }
  135. }
  136. return $this;
  137. }
  138. /**
  139. * Get Format Code.
  140. *
  141. * @return string
  142. */
  143. public function getFormatCode()
  144. {
  145. if ($this->isSupervisor) {
  146. return $this->getSharedComponent()->getFormatCode();
  147. }
  148. if ($this->builtInFormatCode !== false) {
  149. return self::builtInFormatCode($this->builtInFormatCode);
  150. }
  151. return $this->formatCode;
  152. }
  153. /**
  154. * Set Format Code.
  155. *
  156. * @param string $pValue see self::FORMAT_*
  157. *
  158. * @return $this
  159. */
  160. public function setFormatCode($pValue)
  161. {
  162. if ($pValue == '') {
  163. $pValue = self::FORMAT_GENERAL;
  164. }
  165. if ($this->isSupervisor) {
  166. $styleArray = $this->getStyleArray(['formatCode' => $pValue]);
  167. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
  168. } else {
  169. $this->formatCode = $pValue;
  170. $this->builtInFormatCode = self::builtInFormatCodeIndex($pValue);
  171. }
  172. return $this;
  173. }
  174. /**
  175. * Get Built-In Format Code.
  176. *
  177. * @return int
  178. */
  179. public function getBuiltInFormatCode()
  180. {
  181. if ($this->isSupervisor) {
  182. return $this->getSharedComponent()->getBuiltInFormatCode();
  183. }
  184. return $this->builtInFormatCode;
  185. }
  186. /**
  187. * Set Built-In Format Code.
  188. *
  189. * @param int $pValue
  190. *
  191. * @return $this
  192. */
  193. public function setBuiltInFormatCode($pValue)
  194. {
  195. if ($this->isSupervisor) {
  196. $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($pValue)]);
  197. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
  198. } else {
  199. $this->builtInFormatCode = $pValue;
  200. $this->formatCode = self::builtInFormatCode($pValue);
  201. }
  202. return $this;
  203. }
  204. /**
  205. * Fill built-in format codes.
  206. */
  207. private static function fillBuiltInFormatCodes()
  208. {
  209. // [MS-OI29500: Microsoft Office Implementation Information for ISO/IEC-29500 Standard Compliance]
  210. // 18.8.30. numFmt (Number Format)
  211. //
  212. // The ECMA standard defines built-in format IDs
  213. // 14: "mm-dd-yy"
  214. // 22: "m/d/yy h:mm"
  215. // 37: "#,##0 ;(#,##0)"
  216. // 38: "#,##0 ;[Red](#,##0)"
  217. // 39: "#,##0.00;(#,##0.00)"
  218. // 40: "#,##0.00;[Red](#,##0.00)"
  219. // 47: "mmss.0"
  220. // KOR fmt 55: "yyyy-mm-dd"
  221. // Excel defines built-in format IDs
  222. // 14: "m/d/yyyy"
  223. // 22: "m/d/yyyy h:mm"
  224. // 37: "#,##0_);(#,##0)"
  225. // 38: "#,##0_);[Red](#,##0)"
  226. // 39: "#,##0.00_);(#,##0.00)"
  227. // 40: "#,##0.00_);[Red](#,##0.00)"
  228. // 47: "mm:ss.0"
  229. // KOR fmt 55: "yyyy/mm/dd"
  230. // Built-in format codes
  231. if (self::$builtInFormats === null) {
  232. self::$builtInFormats = [];
  233. // General
  234. self::$builtInFormats[0] = self::FORMAT_GENERAL;
  235. self::$builtInFormats[1] = '0';
  236. self::$builtInFormats[2] = '0.00';
  237. self::$builtInFormats[3] = '#,##0';
  238. self::$builtInFormats[4] = '#,##0.00';
  239. self::$builtInFormats[9] = '0%';
  240. self::$builtInFormats[10] = '0.00%';
  241. self::$builtInFormats[11] = '0.00E+00';
  242. self::$builtInFormats[12] = '# ?/?';
  243. self::$builtInFormats[13] = '# ??/??';
  244. self::$builtInFormats[14] = 'm/d/yyyy'; // Despite ECMA 'mm-dd-yy';
  245. self::$builtInFormats[15] = 'd-mmm-yy';
  246. self::$builtInFormats[16] = 'd-mmm';
  247. self::$builtInFormats[17] = 'mmm-yy';
  248. self::$builtInFormats[18] = 'h:mm AM/PM';
  249. self::$builtInFormats[19] = 'h:mm:ss AM/PM';
  250. self::$builtInFormats[20] = 'h:mm';
  251. self::$builtInFormats[21] = 'h:mm:ss';
  252. self::$builtInFormats[22] = 'm/d/yyyy h:mm'; // Despite ECMA 'm/d/yy h:mm';
  253. self::$builtInFormats[37] = '#,##0_);(#,##0)'; // Despite ECMA '#,##0 ;(#,##0)';
  254. self::$builtInFormats[38] = '#,##0_);[Red](#,##0)'; // Despite ECMA '#,##0 ;[Red](#,##0)';
  255. self::$builtInFormats[39] = '#,##0.00_);(#,##0.00)'; // Despite ECMA '#,##0.00;(#,##0.00)';
  256. self::$builtInFormats[40] = '#,##0.00_);[Red](#,##0.00)'; // Despite ECMA '#,##0.00;[Red](#,##0.00)';
  257. self::$builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
  258. self::$builtInFormats[45] = 'mm:ss';
  259. self::$builtInFormats[46] = '[h]:mm:ss';
  260. self::$builtInFormats[47] = 'mm:ss.0'; // Despite ECMA 'mmss.0';
  261. self::$builtInFormats[48] = '##0.0E+0';
  262. self::$builtInFormats[49] = '@';
  263. // CHT
  264. self::$builtInFormats[27] = '[$-404]e/m/d';
  265. self::$builtInFormats[30] = 'm/d/yy';
  266. self::$builtInFormats[36] = '[$-404]e/m/d';
  267. self::$builtInFormats[50] = '[$-404]e/m/d';
  268. self::$builtInFormats[57] = '[$-404]e/m/d';
  269. // THA
  270. self::$builtInFormats[59] = 't0';
  271. self::$builtInFormats[60] = 't0.00';
  272. self::$builtInFormats[61] = 't#,##0';
  273. self::$builtInFormats[62] = 't#,##0.00';
  274. self::$builtInFormats[67] = 't0%';
  275. self::$builtInFormats[68] = 't0.00%';
  276. self::$builtInFormats[69] = 't# ?/?';
  277. self::$builtInFormats[70] = 't# ??/??';
  278. // JPN
  279. self::$builtInFormats[28] = '[$-411]ggge"年"m"月"d"日"';
  280. self::$builtInFormats[29] = '[$-411]ggge"年"m"月"d"日"';
  281. self::$builtInFormats[31] = 'yyyy"年"m"月"d"日"';
  282. self::$builtInFormats[32] = 'h"時"mm"分"';
  283. self::$builtInFormats[33] = 'h"時"mm"分"ss"秒"';
  284. self::$builtInFormats[34] = 'yyyy"年"m"月"';
  285. self::$builtInFormats[35] = 'm"月"d"日"';
  286. self::$builtInFormats[51] = '[$-411]ggge"年"m"月"d"日"';
  287. self::$builtInFormats[52] = 'yyyy"年"m"月"';
  288. self::$builtInFormats[53] = 'm"月"d"日"';
  289. self::$builtInFormats[54] = '[$-411]ggge"年"m"月"d"日"';
  290. self::$builtInFormats[55] = 'yyyy"年"m"月"';
  291. self::$builtInFormats[56] = 'm"月"d"日"';
  292. self::$builtInFormats[58] = '[$-411]ggge"年"m"月"d"日"';
  293. // Flip array (for faster lookups)
  294. self::$flippedBuiltInFormats = array_flip(self::$builtInFormats);
  295. }
  296. }
  297. /**
  298. * Get built-in format code.
  299. *
  300. * @param int $pIndex
  301. *
  302. * @return string
  303. */
  304. public static function builtInFormatCode($pIndex)
  305. {
  306. // Clean parameter
  307. $pIndex = (int) $pIndex;
  308. // Ensure built-in format codes are available
  309. self::fillBuiltInFormatCodes();
  310. // Lookup format code
  311. if (isset(self::$builtInFormats[$pIndex])) {
  312. return self::$builtInFormats[$pIndex];
  313. }
  314. return '';
  315. }
  316. /**
  317. * Get built-in format code index.
  318. *
  319. * @param string $formatCode
  320. *
  321. * @return bool|int
  322. */
  323. public static function builtInFormatCodeIndex($formatCode)
  324. {
  325. // Ensure built-in format codes are available
  326. self::fillBuiltInFormatCodes();
  327. // Lookup format code
  328. if (array_key_exists($formatCode, self::$flippedBuiltInFormats)) {
  329. return self::$flippedBuiltInFormats[$formatCode];
  330. }
  331. return false;
  332. }
  333. /**
  334. * Get hash code.
  335. *
  336. * @return string Hash code
  337. */
  338. public function getHashCode()
  339. {
  340. if ($this->isSupervisor) {
  341. return $this->getSharedComponent()->getHashCode();
  342. }
  343. return md5(
  344. $this->formatCode .
  345. $this->builtInFormatCode .
  346. __CLASS__
  347. );
  348. }
  349. /**
  350. * Search/replace values to convert Excel date/time format masks to PHP format masks.
  351. *
  352. * @var array
  353. */
  354. private static $dateFormatReplacements = [
  355. // first remove escapes related to non-format characters
  356. '\\' => '',
  357. // 12-hour suffix
  358. 'am/pm' => 'A',
  359. // 4-digit year
  360. 'e' => 'Y',
  361. 'yyyy' => 'Y',
  362. // 2-digit year
  363. 'yy' => 'y',
  364. // first letter of month - no php equivalent
  365. 'mmmmm' => 'M',
  366. // full month name
  367. 'mmmm' => 'F',
  368. // short month name
  369. 'mmm' => 'M',
  370. // mm is minutes if time, but can also be month w/leading zero
  371. // so we try to identify times be the inclusion of a : separator in the mask
  372. // It isn't perfect, but the best way I know how
  373. ':mm' => ':i',
  374. 'mm:' => 'i:',
  375. // month leading zero
  376. 'mm' => 'm',
  377. // month no leading zero
  378. 'm' => 'n',
  379. // full day of week name
  380. 'dddd' => 'l',
  381. // short day of week name
  382. 'ddd' => 'D',
  383. // days leading zero
  384. 'dd' => 'd',
  385. // days no leading zero
  386. 'd' => 'j',
  387. // seconds
  388. 'ss' => 's',
  389. // fractional seconds - no php equivalent
  390. '.s' => '',
  391. ];
  392. /**
  393. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock).
  394. *
  395. * @var array
  396. */
  397. private static $dateFormatReplacements24 = [
  398. 'hh' => 'H',
  399. 'h' => 'G',
  400. ];
  401. /**
  402. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock).
  403. *
  404. * @var array
  405. */
  406. private static $dateFormatReplacements12 = [
  407. 'hh' => 'h',
  408. 'h' => 'g',
  409. ];
  410. private static function setLowercaseCallback($matches)
  411. {
  412. return mb_strtolower($matches[0]);
  413. }
  414. private static function escapeQuotesCallback($matches)
  415. {
  416. return '\\' . implode('\\', str_split($matches[1]));
  417. }
  418. private static function formatAsDate(&$value, &$format)
  419. {
  420. // strip off first part containing e.g. [$-F800] or [$USD-409]
  421. // general syntax: [$<Currency string>-<language info>]
  422. // language info is in hexadecimal
  423. // strip off chinese part like [DBNum1][$-804]
  424. $format = preg_replace('/^(\[[0-9A-Za-z]*\])*(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format);
  425. // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case;
  426. // but we don't want to change any quoted strings
  427. $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', ['self', 'setLowercaseCallback'], $format);
  428. // Only process the non-quoted blocks for date format characters
  429. $blocks = explode('"', $format);
  430. foreach ($blocks as $key => &$block) {
  431. if ($key % 2 == 0) {
  432. $block = strtr($block, self::$dateFormatReplacements);
  433. if (!strpos($block, 'A')) {
  434. // 24-hour time format
  435. // when [h]:mm format, the [h] should replace to the hours of the value * 24
  436. if (false !== strpos($block, '[h]')) {
  437. $hours = (int) ($value * 24);
  438. $block = str_replace('[h]', $hours, $block);
  439. continue;
  440. }
  441. $block = strtr($block, self::$dateFormatReplacements24);
  442. } else {
  443. // 12-hour time format
  444. $block = strtr($block, self::$dateFormatReplacements12);
  445. }
  446. }
  447. }
  448. $format = implode('"', $blocks);
  449. // escape any quoted characters so that DateTime format() will render them correctly
  450. $format = preg_replace_callback('/"(.*)"/U', ['self', 'escapeQuotesCallback'], $format);
  451. $dateObj = Date::excelToDateTimeObject($value);
  452. $value = $dateObj->format($format);
  453. }
  454. private static function formatAsPercentage(&$value, &$format)
  455. {
  456. if ($format === self::FORMAT_PERCENTAGE) {
  457. $value = round((100 * $value), 0) . '%';
  458. } else {
  459. if (preg_match('/\.[#0]+/', $format, $m)) {
  460. $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1);
  461. $format = str_replace($m[0], $s, $format);
  462. }
  463. if (preg_match('/^[#0]+/', $format, $m)) {
  464. $format = str_replace($m[0], strlen($m[0]), $format);
  465. }
  466. $format = '%' . str_replace('%', 'f%%', $format);
  467. $value = sprintf($format, 100 * $value);
  468. }
  469. }
  470. private static function formatAsFraction(&$value, &$format)
  471. {
  472. $sign = ($value < 0) ? '-' : '';
  473. $integerPart = floor(abs($value));
  474. $decimalPart = trim(fmod(abs($value), 1), '0.');
  475. $decimalLength = strlen($decimalPart);
  476. $decimalDivisor = pow(10, $decimalLength);
  477. $GCD = MathTrig::GCD($decimalPart, $decimalDivisor);
  478. $adjustedDecimalPart = $decimalPart / $GCD;
  479. $adjustedDecimalDivisor = $decimalDivisor / $GCD;
  480. if ((strpos($format, '0') !== false) || (strpos($format, '#') !== false) || (substr($format, 0, 3) == '? ?')) {
  481. if ($integerPart == 0) {
  482. $integerPart = '';
  483. }
  484. $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
  485. } else {
  486. $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor;
  487. $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor";
  488. }
  489. }
  490. private static function mergeComplexNumberFormatMasks($numbers, $masks)
  491. {
  492. $decimalCount = strlen($numbers[1]);
  493. $postDecimalMasks = [];
  494. do {
  495. $tempMask = array_pop($masks);
  496. $postDecimalMasks[] = $tempMask;
  497. $decimalCount -= strlen($tempMask);
  498. } while ($decimalCount > 0);
  499. return [
  500. implode('.', $masks),
  501. implode('.', array_reverse($postDecimalMasks)),
  502. ];
  503. }
  504. private static function processComplexNumberFormatMask($number, $mask)
  505. {
  506. $result = $number;
  507. $maskingBlockCount = preg_match_all('/0+/', $mask, $maskingBlocks, PREG_OFFSET_CAPTURE);
  508. if ($maskingBlockCount > 1) {
  509. $maskingBlocks = array_reverse($maskingBlocks[0]);
  510. foreach ($maskingBlocks as $block) {
  511. $divisor = 1 . $block[0];
  512. $size = strlen($block[0]);
  513. $offset = $block[1];
  514. $blockValue = sprintf(
  515. '%0' . $size . 'd',
  516. fmod($number, $divisor)
  517. );
  518. $number = floor($number / $divisor);
  519. $mask = substr_replace($mask, $blockValue, $offset, $size);
  520. }
  521. if ($number > 0) {
  522. $mask = substr_replace($mask, $number, $offset, 0);
  523. }
  524. $result = $mask;
  525. }
  526. return $result;
  527. }
  528. private static function complexNumberFormatMask($number, $mask, $splitOnPoint = true)
  529. {
  530. $sign = ($number < 0.0);
  531. $number = abs($number);
  532. if ($splitOnPoint && strpos($mask, '.') !== false && strpos($number, '.') !== false) {
  533. $numbers = explode('.', $number);
  534. $masks = explode('.', $mask);
  535. if (count($masks) > 2) {
  536. $masks = self::mergeComplexNumberFormatMasks($numbers, $masks);
  537. }
  538. $result1 = self::complexNumberFormatMask($numbers[0], $masks[0], false);
  539. $result2 = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false));
  540. return (($sign) ? '-' : '') . $result1 . '.' . $result2;
  541. }
  542. $result = self::processComplexNumberFormatMask($number, $mask);
  543. return (($sign) ? '-' : '') . $result;
  544. }
  545. private static function formatStraightNumericValue($value, $format, array $matches, $useThousands, $number_regex)
  546. {
  547. $left = $matches[1];
  548. $dec = $matches[2];
  549. $right = $matches[3];
  550. // minimun width of formatted number (including dot)
  551. $minWidth = strlen($left) + strlen($dec) + strlen($right);
  552. if ($useThousands) {
  553. $value = number_format(
  554. $value,
  555. strlen($right),
  556. StringHelper::getDecimalSeparator(),
  557. StringHelper::getThousandsSeparator()
  558. );
  559. $value = preg_replace($number_regex, $value, $format);
  560. } else {
  561. if (preg_match('/[0#]E[+-]0/i', $format)) {
  562. // Scientific format
  563. $value = sprintf('%5.2E', $value);
  564. } elseif (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) {
  565. if ($value == (int) $value && substr_count($format, '.') === 1) {
  566. $value *= 10 ** strlen(explode('.', $format)[1]);
  567. }
  568. $value = self::complexNumberFormatMask($value, $format);
  569. } else {
  570. $sprintf_pattern = "%0$minWidth." . strlen($right) . 'f';
  571. $value = sprintf($sprintf_pattern, $value);
  572. $value = preg_replace($number_regex, $value, $format);
  573. }
  574. }
  575. return $value;
  576. }
  577. private static function formatAsNumber($value, $format)
  578. {
  579. if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) {
  580. return 'EUR ' . sprintf('%1.2f', $value);
  581. }
  582. // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
  583. $format = str_replace(['"', '*'], '', $format);
  584. // Find out if we need thousands separator
  585. // This is indicated by a comma enclosed by a digit placeholder:
  586. // #,# or 0,0
  587. $useThousands = preg_match('/(#,#|0,0)/', $format);
  588. if ($useThousands) {
  589. $format = preg_replace('/0,0/', '00', $format);
  590. $format = preg_replace('/#,#/', '##', $format);
  591. }
  592. // Scale thousands, millions,...
  593. // This is indicated by a number of commas after a digit placeholder:
  594. // #, or 0.0,,
  595. $scale = 1; // same as no scale
  596. $matches = [];
  597. if (preg_match('/(#|0)(,+)/', $format, $matches)) {
  598. $scale = pow(1000, strlen($matches[2]));
  599. // strip the commas
  600. $format = preg_replace('/0,+/', '0', $format);
  601. $format = preg_replace('/#,+/', '#', $format);
  602. }
  603. if (preg_match('/#?.*\?\/\?/', $format, $m)) {
  604. if ($value != (int) $value) {
  605. self::formatAsFraction($value, $format);
  606. }
  607. } else {
  608. // Handle the number itself
  609. // scale number
  610. $value = $value / $scale;
  611. // Strip #
  612. $format = preg_replace('/\\#/', '0', $format);
  613. // Remove locale code [$-###]
  614. $format = preg_replace('/\[\$\-.*\]/', '', $format);
  615. $n = '/\\[[^\\]]+\\]/';
  616. $m = preg_replace($n, '', $format);
  617. $number_regex = '/(0+)(\\.?)(0*)/';
  618. if (preg_match($number_regex, $m, $matches)) {
  619. $value = self::formatStraightNumericValue($value, $format, $matches, $useThousands, $number_regex);
  620. }
  621. }
  622. if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
  623. // Currency or Accounting
  624. $currencyCode = $m[1];
  625. [$currencyCode] = explode('-', $currencyCode);
  626. if ($currencyCode == '') {
  627. $currencyCode = StringHelper::getCurrencyCode();
  628. }
  629. $value = preg_replace('/\[\$([^\]]*)\]/u', $currencyCode, $value);
  630. }
  631. return $value;
  632. }
  633. /**
  634. * Convert a value in a pre-defined format to a PHP string.
  635. *
  636. * @param mixed $value Value to format
  637. * @param string $format Format code, see = self::FORMAT_*
  638. * @param array $callBack Callback function for additional formatting of string
  639. *
  640. * @return string Formatted string
  641. */
  642. public static function toFormattedString($value, $format, $callBack = null)
  643. {
  644. // For now we do not treat strings although section 4 of a format code affects strings
  645. if (!is_numeric($value)) {
  646. return $value;
  647. }
  648. // For 'General' format code, we just pass the value although this is not entirely the way Excel does it,
  649. // it seems to round numbers to a total of 10 digits.
  650. if (($format === self::FORMAT_GENERAL) || ($format === self::FORMAT_TEXT)) {
  651. return $value;
  652. }
  653. // Convert any other escaped characters to quoted strings, e.g. (\T to "T")
  654. $format = preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/u', '"${2}"', $format);
  655. // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal)
  656. $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format);
  657. // Extract the relevant section depending on whether number is positive, negative, or zero?
  658. // Text not supported yet.
  659. // Here is how the sections apply to various values in Excel:
  660. // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT]
  661. // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE]
  662. // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO]
  663. // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT]
  664. switch (count($sections)) {
  665. case 1:
  666. $format = $sections[0];
  667. break;
  668. case 2:
  669. $format = ($value >= 0) ? $sections[0] : $sections[1];
  670. $value = abs($value); // Use the absolute value
  671. break;
  672. case 3:
  673. $format = ($value > 0) ?
  674. $sections[0] : (($value < 0) ?
  675. $sections[1] : $sections[2]);
  676. $value = abs($value); // Use the absolute value
  677. break;
  678. case 4:
  679. $format = ($value > 0) ?
  680. $sections[0] : (($value < 0) ?
  681. $sections[1] : $sections[2]);
  682. $value = abs($value); // Use the absolute value
  683. break;
  684. default:
  685. // something is wrong, just use first section
  686. $format = $sections[0];
  687. break;
  688. }
  689. // In Excel formats, "_" is used to add spacing,
  690. // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space
  691. $format = preg_replace('/_./', ' ', $format);
  692. // Save format with color information for later use below
  693. $formatColor = $format;
  694. // Strip colour information
  695. $color_regex = '/\[(' . implode('|', Color::NAMED_COLORS) . ')\]/';
  696. $format = preg_replace($color_regex, '', $format);
  697. // Let's begin inspecting the format and converting the value to a formatted string
  698. // Check for date/time characters (not inside quotes)
  699. if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) {
  700. // datetime format
  701. self::formatAsDate($value, $format);
  702. } else {
  703. if (substr($format, 0, 1) === '"' && substr($format, -1, 1) === '"') {
  704. $value = substr($format, 1, -1);
  705. } elseif (preg_match('/%$/', $format)) {
  706. // % number format
  707. self::formatAsPercentage($value, $format);
  708. } else {
  709. $value = self::formatAsNumber($value, $format);
  710. }
  711. }
  712. // Additional formatting provided by callback function
  713. if ($callBack !== null) {
  714. [$writerInstance, $function] = $callBack;
  715. $value = $writerInstance->$function($value, $formatColor);
  716. }
  717. return $value;
  718. }
  719. }