PageRenderTime 50ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/backend/modules/mbase2/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php

https://gitlab.com/mbase2/source-code
PHP | 230 lines | 121 code | 26 blank | 83 comment | 6 complexity | 3256a3172594edc019e79130039fdc85 MD5 | raw file
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Helper;
  3. use PhpOffice\PhpSpreadsheet\IOFactory;
  4. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  5. use PhpOffice\PhpSpreadsheet\Writer\IWriter;
  6. use PhpOffice\PhpSpreadsheet\Writer\Pdf;
  7. use RecursiveDirectoryIterator;
  8. use RecursiveIteratorIterator;
  9. use RecursiveRegexIterator;
  10. use ReflectionClass;
  11. use RegexIterator;
  12. /**
  13. * Helper class to be used in sample code.
  14. */
  15. class Sample
  16. {
  17. /**
  18. * Returns whether we run on CLI or browser.
  19. *
  20. * @return bool
  21. */
  22. public function isCli()
  23. {
  24. return PHP_SAPI === 'cli';
  25. }
  26. /**
  27. * Return the filename currently being executed.
  28. *
  29. * @return string
  30. */
  31. public function getScriptFilename()
  32. {
  33. return basename($_SERVER['SCRIPT_FILENAME'], '.php');
  34. }
  35. /**
  36. * Whether we are executing the index page.
  37. *
  38. * @return bool
  39. */
  40. public function isIndex()
  41. {
  42. return $this->getScriptFilename() === 'index';
  43. }
  44. /**
  45. * Return the page title.
  46. *
  47. * @return string
  48. */
  49. public function getPageTitle()
  50. {
  51. return $this->isIndex() ? 'PHPSpreadsheet' : $this->getScriptFilename();
  52. }
  53. /**
  54. * Return the page heading.
  55. *
  56. * @return string
  57. */
  58. public function getPageHeading()
  59. {
  60. return $this->isIndex() ? '' : '<h1>' . str_replace('_', ' ', $this->getScriptFilename()) . '</h1>';
  61. }
  62. /**
  63. * Returns an array of all known samples.
  64. *
  65. * @return string[] [$name => $path]
  66. */
  67. public function getSamples()
  68. {
  69. // Populate samples
  70. $baseDir = realpath(__DIR__ . '/../../../samples');
  71. $directory = new RecursiveDirectoryIterator($baseDir);
  72. $iterator = new RecursiveIteratorIterator($directory);
  73. $regex = new RegexIterator($iterator, '/^.+\.php$/', RecursiveRegexIterator::GET_MATCH);
  74. $files = [];
  75. foreach ($regex as $file) {
  76. $file = str_replace(str_replace('\\', '/', $baseDir) . '/', '', str_replace('\\', '/', $file[0]));
  77. $info = pathinfo($file);
  78. $category = str_replace('_', ' ', $info['dirname']);
  79. $name = str_replace('_', ' ', preg_replace('/(|\.php)/', '', $info['filename']));
  80. if (!in_array($category, ['.', 'boostrap', 'templates'])) {
  81. if (!isset($files[$category])) {
  82. $files[$category] = [];
  83. }
  84. $files[$category][$name] = $file;
  85. }
  86. }
  87. // Sort everything
  88. ksort($files);
  89. foreach ($files as &$f) {
  90. asort($f);
  91. }
  92. return $files;
  93. }
  94. /**
  95. * Write documents.
  96. *
  97. * @param Spreadsheet $spreadsheet
  98. * @param string $filename
  99. * @param string[] $writers
  100. */
  101. public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Xlsx', 'Xls'])
  102. {
  103. // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  104. $spreadsheet->setActiveSheetIndex(0);
  105. // Write documents
  106. foreach ($writers as $writerType) {
  107. $path = $this->getFilename($filename, mb_strtolower($writerType));
  108. $writer = IOFactory::createWriter($spreadsheet, $writerType);
  109. if ($writer instanceof Pdf) {
  110. // PDF writer needs temporary directory
  111. $tempDir = $this->getTemporaryFolder();
  112. $writer->setTempDir($tempDir);
  113. }
  114. $callStartTime = microtime(true);
  115. $writer->save($path);
  116. $this->logWrite($writer, $path, $callStartTime);
  117. }
  118. $this->logEndingNotes();
  119. }
  120. /**
  121. * Returns the temporary directory and make sure it exists.
  122. *
  123. * @return string
  124. */
  125. private function getTemporaryFolder()
  126. {
  127. $tempFolder = sys_get_temp_dir() . '/phpspreadsheet';
  128. if (!is_dir($tempFolder)) {
  129. if (!mkdir($tempFolder) && !is_dir($tempFolder)) {
  130. throw new \RuntimeException(sprintf('Directory "%s" was not created', $tempFolder));
  131. }
  132. }
  133. return $tempFolder;
  134. }
  135. /**
  136. * Returns the filename that should be used for sample output.
  137. *
  138. * @param string $filename
  139. * @param string $extension
  140. *
  141. * @return string
  142. */
  143. public function getFilename($filename, $extension = 'xlsx')
  144. {
  145. $originalExtension = pathinfo($filename, PATHINFO_EXTENSION);
  146. return $this->getTemporaryFolder() . '/' . str_replace('.' . $originalExtension, '.' . $extension, basename($filename));
  147. }
  148. /**
  149. * Return a random temporary file name.
  150. *
  151. * @param string $extension
  152. *
  153. * @return string
  154. */
  155. public function getTemporaryFilename($extension = 'xlsx')
  156. {
  157. $temporaryFilename = tempnam($this->getTemporaryFolder(), 'phpspreadsheet-');
  158. unlink($temporaryFilename);
  159. return $temporaryFilename . '.' . $extension;
  160. }
  161. public function log($message)
  162. {
  163. $eol = $this->isCli() ? PHP_EOL : '<br />';
  164. echo date('H:i:s ') . $message . $eol;
  165. }
  166. /**
  167. * Log ending notes.
  168. */
  169. public function logEndingNotes()
  170. {
  171. // Do not show execution time for index
  172. $this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB');
  173. }
  174. /**
  175. * Log a line about the write operation.
  176. *
  177. * @param IWriter $writer
  178. * @param string $path
  179. * @param float $callStartTime
  180. */
  181. public function logWrite(IWriter $writer, $path, $callStartTime)
  182. {
  183. $callEndTime = microtime(true);
  184. $callTime = $callEndTime - $callStartTime;
  185. $reflection = new ReflectionClass($writer);
  186. $format = $reflection->getShortName();
  187. $message = "Write {$format} format to <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds';
  188. $this->log($message);
  189. }
  190. /**
  191. * Log a line about the read operation.
  192. *
  193. * @param string $format
  194. * @param string $path
  195. * @param float $callStartTime
  196. */
  197. public function logRead($format, $path, $callStartTime)
  198. {
  199. $callEndTime = microtime(true);
  200. $callTime = $callEndTime - $callStartTime;
  201. $message = "Read {$format} format from <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds';
  202. $this->log($message);
  203. }
  204. }