ILIAS  eassessment Revision 61809
 All Data Structures Namespaces Files Functions Variables Groups Pages
NumberFormat.php
Go to the documentation of this file.
1 <?php
37 {
38  /* Pre-defined formats */
39  const FORMAT_GENERAL = 'General';
40 
41  const FORMAT_TEXT = '@';
42 
43  const FORMAT_NUMBER = '0';
44  const FORMAT_NUMBER_00 = '0.00';
45  const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
46  const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
47 
48  const FORMAT_PERCENTAGE = '0%';
49  const FORMAT_PERCENTAGE_00 = '0.00%';
50 
51  const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';
52  const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd';
53  const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy';
54  const FORMAT_DATE_DMYSLASH = 'd/m/y';
55  const FORMAT_DATE_DMYMINUS = 'd-m-y';
56  const FORMAT_DATE_DMMINUS = 'd-m';
57  const FORMAT_DATE_MYMINUS = 'm-y';
58  const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
59  const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
60  const FORMAT_DATE_XLSX16 = 'd-mmm';
61  const FORMAT_DATE_XLSX17 = 'mmm-yy';
62  const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
63  const FORMAT_DATE_DATETIME = 'd/m/y h:mm';
64  const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
65  const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
66  const FORMAT_DATE_TIME3 = 'h:mm';
67  const FORMAT_DATE_TIME4 = 'h:mm:ss';
68  const FORMAT_DATE_TIME5 = 'mm:ss';
69  const FORMAT_DATE_TIME6 = 'h:mm:ss';
70  const FORMAT_DATE_TIME7 = 'i:s.S';
71  const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
72  const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@';
73 
74  const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-';
75  const FORMAT_CURRENCY_USD = '$#,##0_-';
76  const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-';
77 
83  private static $_builtInFormats;
84 
90  private static $_flippedBuiltInFormats;
91 
98 
104  private $_builtInFormatCode = 0;
105 
112 
118  private $_isSupervisor;
119 
125  private $_parent;
126 
130  public function __construct($isSupervisor = false)
131  {
132  // Supervisor?
133  $this->_isSupervisor = $isSupervisor;
134  }
135 
142  public function bindParent($parent)
143  {
144  $this->_parent = $parent;
145  }
146 
152  public function getIsSupervisor()
153  {
154  return $this->_isSupervisor;
155  }
156 
163  public function getSharedComponent()
164  {
165  return $this->_parent->getSharedComponent()->getNumberFormat();
166  }
167 
173  public function getActiveSheet()
174  {
175  return $this->_parent->getActiveSheet();
176  }
177 
184  public function getSelectedCells()
185  {
186  return $this->getActiveSheet()->getSelectedCells();
187  }
188 
195  public function getActiveCell()
196  {
197  return $this->getActiveSheet()->getActiveCell();
198  }
199 
206  public function getStyleArray($array)
207  {
208  return array('numberformat' => $array);
209  }
210 
226  public function applyFromArray($pStyles = null)
227  {
228  if (is_array($pStyles)) {
229  if ($this->_isSupervisor) {
230  $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
231  } else {
232  if (array_key_exists('code', $pStyles)) {
233  $this->setFormatCode($pStyles['code']);
234  }
235  }
236  } else {
237  throw new Exception("Invalid style array passed.");
238  }
239  return $this;
240  }
241 
247  public function getFormatCode()
248  {
249  if ($this->_isSupervisor) {
250  return $this->getSharedComponent()->getFormatCode();
251  }
252  if ($this->_builtInFormatCode !== false)
253  {
254  return self::builtInFormatCode($this->_builtInFormatCode);
255  }
256  return $this->_formatCode;
257  }
258 
266  {
267  if ($pValue == '') {
269  }
270  if ($this->_isSupervisor) {
271  $styleArray = $this->getStyleArray(array('code' => $pValue));
272  $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
273  } else {
274  $this->_formatCode = $pValue;
275  $this->_builtInFormatCode = self::builtInFormatCodeIndex($pValue);
276  }
277  return $this;
278  }
279 
285  public function getBuiltInFormatCode()
286  {
287  if ($this->_isSupervisor) {
288  return $this->getSharedComponent()->getBuiltInFormatCode();
289  }
291  }
292 
299  public function setBuiltInFormatCode($pValue = 0)
300  {
301 
302  if ($this->_isSupervisor) {
303  $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue)));
304  $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
305  } else {
306  $this->_builtInFormatCode = $pValue;
307  $this->_formatCode = self::builtInFormatCode($pValue);
308  }
309  return $this;
310  }
311 
315  private static function fillBuiltInFormatCodes()
316  {
317  // Built-in format codes
318  if (is_null(self::$_builtInFormats)) {
319  self::$_builtInFormats = array();
320 
321  // General
322  self::$_builtInFormats[0] = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
323  self::$_builtInFormats[1] = '0';
324  self::$_builtInFormats[2] = '0.00';
325  self::$_builtInFormats[3] = '#,##0';
326  self::$_builtInFormats[4] = '#,##0.00';
327 
328  self::$_builtInFormats[9] = '0%';
329  self::$_builtInFormats[10] = '0.00%';
330  self::$_builtInFormats[11] = '0.00E+00';
331  self::$_builtInFormats[12] = '# ?/?';
332  self::$_builtInFormats[13] = '# ??/??';
333  self::$_builtInFormats[14] = 'mm-dd-yy';
334  self::$_builtInFormats[15] = 'd-mmm-yy';
335  self::$_builtInFormats[16] = 'd-mmm';
336  self::$_builtInFormats[17] = 'mmm-yy';
337  self::$_builtInFormats[18] = 'h:mm AM/PM';
338  self::$_builtInFormats[19] = 'h:mm:ss AM/PM';
339  self::$_builtInFormats[20] = 'h:mm';
340  self::$_builtInFormats[21] = 'h:mm:ss';
341  self::$_builtInFormats[22] = 'm/d/yy h:mm';
342 
343  self::$_builtInFormats[37] = '#,##0 ;(#,##0)';
344  self::$_builtInFormats[38] = '#,##0 ;[Red](#,##0)';
345  self::$_builtInFormats[39] = '#,##0.00;(#,##0.00)';
346  self::$_builtInFormats[40] = '#,##0.00;[Red](#,##0.00)';
347 
348  self::$_builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
349  self::$_builtInFormats[45] = 'mm:ss';
350  self::$_builtInFormats[46] = '[h]:mm:ss';
351  self::$_builtInFormats[47] = 'mmss.0';
352  self::$_builtInFormats[48] = '##0.0E+0';
353  self::$_builtInFormats[49] = '@';
354 
355  // CHT
356  self::$_builtInFormats[27] = '[$-404]e/m/d';
357  self::$_builtInFormats[30] = 'm/d/yy';
358  self::$_builtInFormats[36] = '[$-404]e/m/d';
359  self::$_builtInFormats[50] = '[$-404]e/m/d';
360  self::$_builtInFormats[57] = '[$-404]e/m/d';
361 
362  // THA
363  self::$_builtInFormats[59] = 't0';
364  self::$_builtInFormats[60] = 't0.00';
365  self::$_builtInFormats[61] = 't#,##0';
366  self::$_builtInFormats[62] = 't#,##0.00';
367  self::$_builtInFormats[67] = 't0%';
368  self::$_builtInFormats[68] = 't0.00%';
369  self::$_builtInFormats[69] = 't# ?/?';
370  self::$_builtInFormats[70] = 't# ??/??';
371 
372  // Flip array (for faster lookups)
373  self::$_flippedBuiltInFormats = array_flip(self::$_builtInFormats);
374  }
375  }
376 
383  public static function builtInFormatCode($pIndex)
384  {
385  // Clean parameter
386  $pIndex = intval($pIndex);
387 
388  // Ensure built-in format codes are available
390 
391  // Lookup format code
392  if (isset(self::$_builtInFormats[$pIndex])) {
393  return self::$_builtInFormats[$pIndex];
394  }
395 
396  return '';
397  }
398 
405  public static function builtInFormatCodeIndex($formatCode)
406  {
407  // Ensure built-in format codes are available
409 
410  // Lookup format code
411  if (isset(self::$_flippedBuiltInFormats[$formatCode])) {
412  return self::$_flippedBuiltInFormats[$formatCode];
413  }
414 
415  return false;
416  }
417 
423  public function getHashCode()
424  {
425  if ($this->_isSupervisor) {
426  return $this->getSharedComponent()->getHashCode();
427  }
428  return md5(
429  $this->_formatCode
430  . $this->_builtInFormatCode
431  . __CLASS__
432  );
433  }
434 
438  public function __clone()
439  {
440  $vars = get_object_vars($this);
441  foreach ($vars as $key => $value) {
442  if ((is_object($value)) && ($key != '_parent')) {
443  $this->$key = clone $value;
444  } else {
445  $this->$key = $value;
446  }
447  }
448  }
449 
450  private static $_dateFormatReplacements = array(
451  // first remove escapes related to non-format characters
452  '\\' => '',
453  // 12-hour suffix
454  'am/pm' => 'A',
455  // 4-digit year
456  'yyyy' => 'Y',
457  // 2-digit year
458  'yy' => 'y',
459  // first letter of month - no php equivalent
460  'mmmmm' => 'M',
461  // full month name
462  'mmmm' => 'F',
463  // short month name
464  'mmm' => 'M',
465  // mm is minutes if time or month w/leading zero
466  ':mm' => ':i',
467  // month leading zero
468  'mm' => 'm',
469  // month no leading zero
470  'm' => 'n',
471  // full day of week name
472  'dddd' => 'l',
473  // short day of week name
474  'ddd' => 'D',
475  // days leading zero
476  'dd' => 'd',
477  // days no leading zero
478  'd' => 'j',
479  // seconds
480  'ss' => 's',
481  // fractional seconds - no php equivalent
482  '.s' => ''
483  );
484  private static $_dateFormatReplacements24 = array(
485  'hh' => 'H',
486  'h' => 'G'
487  );
488  private static $_dateFormatReplacements12 = array(
489  'hh' => 'h',
490  'h' => 'g'
491  );
492 
501  public static function toFormattedString($value = '', $format = '', $callBack = null)
502  {
503  // For now we do not treat strings although section 4 of a format code affects strings
504  if (!is_numeric($value)) return $value;
505 
506  // For 'General' format code, we just pass the value although this is not entirely the way Excel does it,
507  // it seems to round numbers to a total of 10 digits.
509  return $value;
510  }
511 
512  // Get the sections, there can be up to four sections
513  $sections = explode(';', $format);
514 
515  // Fetch the relevant section depending on whether number is positive, negative, or zero?
516  // Text not supported yet.
517  // Here is how the sections apply to various values in Excel:
518  // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT]
519  // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE]
520  // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO]
521  // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT]
522  switch (count($sections)) {
523  case 1:
524  $format = $sections[0];
525  break;
526 
527  case 2:
528  $format = ($value >= 0) ? $sections[0] : $sections[1];
529  $value = abs($value); // Use the absolute value
530  break;
531 
532  case 3:
533  $format = ($value > 0) ?
534  $sections[0] : ( ($value < 0) ?
535  $sections[1] : $sections[2]);
536  $value = abs($value); // Use the absolute value
537  break;
538 
539  case 4:
540  $format = ($value > 0) ?
541  $sections[0] : ( ($value < 0) ?
542  $sections[1] : $sections[2]);
543  $value = abs($value); // Use the absolute value
544  break;
545 
546  default:
547  // something is wrong, just use first section
548  $format = $sections[0];
549  break;
550  }
551 
552  // Save format with color information for later use below
553  $formatColor = $format;
554 
555  // Strip color information
556  $color_regex = '/^\\[[a-zA-Z]+\\]/';
557  $format = preg_replace($color_regex, '', $format);
558 
559  // Let's begin inspecting the format and converting the value to a formatted string
560  if (preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i', $format)) { // datetime format
561  // dvc: convert Excel formats to PHP date formats
562 
563  // strip off first part containing e.g. [$-F800] or [$USD-409]
564  // general syntax: [$<Currency string>-<language info>]
565  // language info is in hexadecimal
566  $format = preg_replace('/^(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format);
567 
568  // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case
569  $format = strtolower($format);
570 
571  $format = strtr($format,self::$_dateFormatReplacements);
572  if (!strpos($format,'A')) { // 24-hour time format
573  $format = strtr($format,self::$_dateFormatReplacements24);
574  } else { // 12-hour time format
575  $format = strtr($format,self::$_dateFormatReplacements12);
576  }
577 
578  $dateObj = PHPExcel_Shared_Date::ExcelToPHPObject($value);
579  $value = $dateObj->format($format);
580 
581  } else if (preg_match('/%$/', $format)) { // % number format
582  if ($format === self::FORMAT_PERCENTAGE) {
583  $value = round( (100 * $value), 0) . '%';
584  } else {
585  if (preg_match('/\.[#0]+/i', $format, $m)) {
586  $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1);
587  $format = str_replace($m[0], $s, $format);
588  }
589  if (preg_match('/^[#0]+/', $format, $m)) {
590  $format = str_replace($m[0], strlen($m[0]), $format);
591  }
592  $format = '%' . str_replace('%', 'f%%', $format);
593 
594  $value = sprintf($format, 100 * $value);
595  }
596 
597  } else {
598  if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) {
599  $value = 'EUR ' . sprintf('%1.2f', $value);
600 
601  } else {
602  // In Excel formats, "_" is used to add spacing, which we can't do in HTML
603  $format = preg_replace('/_./', '', $format);
604 
605  // Some non-number characters are escaped with \, which we don't need
606  $format = preg_replace("/\\\\/", '', $format);
607 
608  // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
609  $format = str_replace(array('"','*'), '', $format);
610 
611  // Find out if we need thousands separator
612  // This is indicated by a comma enclosed by a digit placeholder:
613  // #,# or 0,0
614  $useThousands = preg_match('/(#,#|0,0)/', $format);
615  if ($useThousands) {
616  $format = preg_replace('/0,0/', '00', $format);
617  $format = preg_replace('/#,#/', '##', $format);
618  }
619 
620  // Scale thousands, millions,...
621  // This is indicated by a number of commas after a digit placeholder:
622  // #, or 0.0,,
623  $scale = 1; // same as no scale
624  $matches = array();
625  if (preg_match('/(#|0)(,+)/', $format, $matches)) {
626  $scale = pow(1000, strlen($matches[2]));
627 
628  // strip the commas
629  $format = preg_replace('/0,+/', '0', $format);
630  $format = preg_replace('/#,+/', '#', $format);
631  }
632 
633  if (preg_match('/#?.*\?\/\?/', $format, $m)) {
634  //echo 'Format mask is fractional '.$format.' <br />';
635  if ($value != (int)$value) {
636  $sign = ($value < 0) ? '-' : '';
637 
638  $integerPart = floor(abs($value));
639  $decimalPart = trim(fmod(abs($value),1),'0.');
640  $decimalLength = strlen($decimalPart);
641  $decimalDivisor = pow(10,$decimalLength);
642 
643  $GCD = PHPExcel_Calculation_MathTrig::GCD($decimalPart,$decimalDivisor);
644 
645  $adjustedDecimalPart = $decimalPart/$GCD;
646  $adjustedDecimalDivisor = $decimalDivisor/$GCD;
647 
648  if ((strpos($format,'0') !== false) || (strpos($format,'#') !== false) || (substr($format,0,3) == '? ?')) {
649  if ($integerPart == 0) { $integerPart = ''; }
650  $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
651  } else {
652  $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor;
653  $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor";
654  }
655  }
656 
657  } else {
658  // Handle the number itself
659 
660  // scale number
661  $value = $value / $scale;
662 
663  // Strip #
664  $format = preg_replace('/\\#/', '', $format);
665 
666  $n = "/\[[^\]]+\]/";
667  $m = preg_replace($n, '', $format);
668  $number_regex = "/(0+)(\.?)(0*)/";
669  if (preg_match($number_regex, $m, $matches)) {
670  $left = $matches[1];
671  $dec = $matches[2];
672  $right = $matches[3];
673 
674  // minimun width of formatted number (including dot)
675  $minWidth = strlen($left) + strlen($dec) + strlen($right);
676 
677  if ($useThousands) {
678  $value = number_format(
679  $value
680  , strlen($right)
683  );
684  } else {
685  $sprintf_pattern = "%0$minWidth." . strlen($right) . "f";
686  $value = sprintf($sprintf_pattern, $value);
687  }
688 
689  $value = preg_replace($number_regex, $value, $format);
690  }
691  }
692  if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
693  // Currency or Accounting
694  $currencyFormat = $m[0];
695  $currencyCode = $m[1];
696  list($currencyCode) = explode('-',$currencyCode);
697  if ($currencyCode == '') {
698  $currencyCode = PHPExcel_Shared_String::getCurrencyCode();
699  }
700  $value = preg_replace('/\[\$([^\]]*)\]/u',$currencyCode,$value);
701  }
702  }
703  }
704 
705  // Additional formatting provided by callback function
706  if ($callBack !== null) {
707  list($writerInstance, $function) = $callBack;
708  $value = $writerInstance->$function($value, $formatColor);
709  }
710 
711  return $value;
712  }
713 
714 }