3 namespace PhpOffice\PhpSpreadsheet\Helper
;
5 use PhpOffice\PhpSpreadsheet\IOFactory
;
6 use PhpOffice\PhpSpreadsheet\Spreadsheet
;
7 use PhpOffice\PhpSpreadsheet\Writer\IWriter
;
8 use PhpOffice\PhpSpreadsheet\Writer\Pdf
;
9 use RecursiveDirectoryIterator
;
10 use RecursiveIteratorIterator
;
11 use RecursiveRegexIterator
;
16 * Helper class to be used in sample code.
21 * Returns whether we run on CLI or browser.
25 public function isCli()
27 return PHP_SAPI
=== 'cli';
31 * Return the filename currently being executed.
35 public function getScriptFilename()
37 return basename($_SERVER['SCRIPT_FILENAME'], '.php');
41 * Whether we are executing the index page.
45 public function isIndex()
47 return $this->getScriptFilename() === 'index';
51 * Return the page title.
55 public function getPageTitle()
57 return $this->isIndex() ?
'PHPSpreadsheet' : $this->getScriptFilename();
61 * Return the page heading.
65 public function getPageHeading()
67 return $this->isIndex() ?
'' : '<h1>' . str_replace('_', ' ', $this->getScriptFilename()) . '</h1>';
71 * Returns an array of all known samples.
73 * @return string[] [$name => $path]
75 public function getSamples()
78 $baseDir = realpath(__DIR__
. '/../../../samples');
79 $directory = new RecursiveDirectoryIterator($baseDir);
80 $iterator = new RecursiveIteratorIterator($directory);
81 $regex = new RegexIterator($iterator, '/^.+\.php$/', RecursiveRegexIterator
::GET_MATCH
);
84 foreach ($regex as $file) {
85 $file = str_replace($baseDir . '/', '', $file[0]);
86 $info = pathinfo($file);
87 $category = str_replace('_', ' ', $info['dirname']);
88 $name = str_replace('_', ' ', preg_replace('/(|\.php)/', '', $info['filename']));
89 if (!in_array($category, ['.', 'boostrap', 'templates'])) {
90 if (!isset($files[$category])) {
91 $files[$category] = [];
93 $files[$category][$name] = $file;
99 foreach ($files as &$f) {
109 * @param Spreadsheet $spreadsheet
110 * @param string $filename
111 * @param string[] $writers
113 public function write(Spreadsheet
$spreadsheet, $filename, array $writers = ['Xlsx', 'Xls'])
115 // Set active sheet index to the first sheet, so Excel opens this as the first sheet
116 $spreadsheet->setActiveSheetIndex(0);
119 foreach ($writers as $writerType) {
120 $path = $this->getFilename($filename, mb_strtolower($writerType));
121 $writer = IOFactory
::createWriter($spreadsheet, $writerType);
122 if ($writer instanceof Pdf
) {
123 // PDF writer needs temporary directory
124 $tempDir = $this->getTemporaryFolder();
125 $writer->setTempDir($tempDir);
127 $callStartTime = microtime(true);
128 $writer->save($path);
129 $this->logWrite($writer, $path, $callStartTime);
132 $this->logEndingNotes();
136 * Returns the temporary directory and make sure it exists.
140 private function getTemporaryFolder()
142 $tempFolder = sys_get_temp_dir() . '/phpspreadsheet';
143 if (!is_dir($tempFolder)) {
144 if (!mkdir($tempFolder) && !is_dir($tempFolder)) {
145 throw new \
RuntimeException(sprintf('Directory "%s" was not created', $tempFolder));
153 * Returns the filename that should be used for sample output.
155 * @param string $filename
156 * @param string $extension
160 public function getFilename($filename, $extension = 'xlsx')
162 $originalExtension = pathinfo($filename, PATHINFO_EXTENSION
);
164 return $this->getTemporaryFolder() . '/' . str_replace('.' . $originalExtension, '.' . $extension, basename($filename));
168 * Return a random temporary file name.
170 * @param string $extension
174 public function getTemporaryFilename($extension = 'xlsx')
176 $temporaryFilename = tempnam($this->getTemporaryFolder(), 'phpspreadsheet-');
177 unlink($temporaryFilename);
179 return $temporaryFilename . '.' . $extension;
182 public function log($message)
184 $eol = $this->isCli() ? PHP_EOL
: '<br />';
185 echo date('H:i:s ') . $message . $eol;
191 public function logEndingNotes()
193 // Do not show execution time for index
194 $this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB');
198 * Log a line about the write operation.
200 * @param IWriter $writer
201 * @param string $path
202 * @param float $callStartTime
204 public function logWrite(IWriter
$writer, $path, $callStartTime)
206 $callEndTime = microtime(true);
207 $callTime = $callEndTime - $callStartTime;
208 $reflection = new ReflectionClass($writer);
209 $format = $reflection->getShortName();
210 $message = "Write {$format} format to <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds';
212 $this->log($message);
216 * Log a line about the read operation.
218 * @param string $format
219 * @param string $path
220 * @param float $callStartTime
222 public function logRead($format, $path, $callStartTime)
224 $callEndTime = microtime(true);
225 $callTime = $callEndTime - $callStartTime;
226 $message = "Read {$format} format from <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds';
228 $this->log($message);