| 1 |
<?php |
| 2 |
|
| 3 |
namespace TablePress\PhpOffice\PhpSpreadsheet\Helper; |
| 4 |
|
| 5 |
use TablePress\PhpOffice\PhpSpreadsheet\Chart\Chart; |
| 6 |
use TablePress\PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer; |
| 7 |
use TablePress\PhpOffice\PhpSpreadsheet\IOFactory; |
| 8 |
use TablePress\PhpOffice\PhpSpreadsheet\Settings; |
| 9 |
use TablePress\PhpOffice\PhpSpreadsheet\Shared\StringHelper; |
| 10 |
use TablePress\PhpOffice\PhpSpreadsheet\Spreadsheet; |
| 11 |
use TablePress\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; |
| 12 |
use TablePress\PhpOffice\PhpSpreadsheet\Writer\IWriter; |
| 13 |
use RecursiveDirectoryIterator; |
| 14 |
use RecursiveIteratorIterator; |
| 15 |
use RecursiveRegexIterator; |
| 16 |
use ReflectionClass; |
| 17 |
use RegexIterator; |
| 18 |
use RuntimeException; |
| 19 |
use Throwable; |
| 20 |
|
| 21 |
/** |
| 22 |
* Helper class to be used in sample code. |
| 23 |
*/ |
| 24 |
class Sample |
| 25 |
{ |
| 26 |
/** |
| 27 |
* Returns whether we run on CLI or browser. |
| 28 |
*/ |
| 29 |
public function isCli(): bool |
| 30 |
{ |
| 31 |
return PHP_SAPI === 'cli'; |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Return the filename currently being executed. |
| 36 |
*/ |
| 37 |
public function getScriptFilename(): string |
| 38 |
{ |
| 39 |
return basename(StringHelper::convertToString($_SERVER['SCRIPT_FILENAME']), '.php'); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Whether we are executing the index page. |
| 44 |
*/ |
| 45 |
public function isIndex(): bool |
| 46 |
{ |
| 47 |
return $this->getScriptFilename() === 'index'; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Return the page title. |
| 52 |
*/ |
| 53 |
public function getPageTitle(): string |
| 54 |
{ |
| 55 |
return $this->isIndex() ? 'PHPSpreadsheet' : $this->getScriptFilename(); |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Return the page heading. |
| 60 |
*/ |
| 61 |
public function getPageHeading(): string |
| 62 |
{ |
| 63 |
return $this->isIndex() ? '' : '<h1>' . str_replace('_', ' ', $this->getScriptFilename()) . '</h1>'; |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* Returns an array of all known samples. |
| 68 |
* |
| 69 |
* @return string[][] [$name => $path] |
| 70 |
*/ |
| 71 |
public function getSamples(): array |
| 72 |
{ |
| 73 |
// Populate samples |
| 74 |
$baseDir = realpath(__DIR__ . '/../../../samples'); |
| 75 |
if ($baseDir === false) { |
| 76 |
// @codeCoverageIgnoreStart |
| 77 |
throw new RuntimeException('realpath returned false'); |
| 78 |
// @codeCoverageIgnoreEnd |
| 79 |
} |
| 80 |
$directory = new RecursiveDirectoryIterator($baseDir); |
| 81 |
$iterator = new RecursiveIteratorIterator($directory); |
| 82 |
$regex = new RegexIterator($iterator, '/^.+\.php$/', RecursiveRegexIterator::GET_MATCH); |
| 83 |
|
| 84 |
$files = []; |
| 85 |
/** @var string[] $file */ |
| 86 |
foreach ($regex as $file) { |
| 87 |
$file = str_replace(str_replace('\\', '/', $baseDir) . '/', '', str_replace('\\', '/', $file[0])); |
| 88 |
$info = pathinfo($file); |
| 89 |
$category = str_replace('_', ' ', $info['dirname'] ?? ''); |
| 90 |
$name = str_replace('_', ' ', (string) preg_replace('/(|\.php)/', '', $info['filename'])); |
| 91 |
if (!in_array($category, ['.', 'bootstrap', 'templates']) && $name !== 'Header') { |
| 92 |
if (!isset($files[$category])) { |
| 93 |
$files[$category] = []; |
| 94 |
} |
| 95 |
$files[$category][$name] = $file; |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
// Sort everything |
| 100 |
ksort($files); |
| 101 |
foreach ($files as &$f) { |
| 102 |
asort($f); |
| 103 |
} |
| 104 |
|
| 105 |
return $files; |
| 106 |
} |
| 107 |
|
| 108 |
/** |
| 109 |
* Write documents. |
| 110 |
* |
| 111 |
* @param string[] $writers |
| 112 |
*/ |
| 113 |
public function write(Spreadsheet $spreadsheet, string $filename, array $writers = ['Xlsx', 'Xls'], bool $withCharts = false, ?callable $writerCallback = null, bool $resetActiveSheet = true): void |
| 114 |
{ |
| 115 |
// Set active sheet index to the first sheet, so Excel opens this as the first sheet |
| 116 |
if ($resetActiveSheet) { |
| 117 |
$spreadsheet->setActiveSheetIndex(0); |
| 118 |
} |
| 119 |
|
| 120 |
// Write documents |
| 121 |
foreach ($writers as $writerType) { |
| 122 |
$path = $this->getFilename($filename, mb_strtolower($writerType)); |
| 123 |
if (preg_match('/(mpdf|tcpdf)$/', $path)) { |
| 124 |
$path .= '.pdf'; |
| 125 |
} |
| 126 |
$writer = IOFactory::createWriter($spreadsheet, $writerType); |
| 127 |
$writer->setIncludeCharts($withCharts); |
| 128 |
if ($writerCallback !== null) { |
| 129 |
$writerCallback($writer); |
| 130 |
} |
| 131 |
$callStartTime = microtime(true); |
| 132 |
$writer->save($path); |
| 133 |
$this->logWrite($writer, $path, $callStartTime); |
| 134 |
$this->addDownloadLink($path); |
| 135 |
} |
| 136 |
|
| 137 |
$this->logEndingNotes(); |
| 138 |
} |
| 139 |
|
| 140 |
public function addDownloadLink(string $path): void |
| 141 |
{ |
| 142 |
if ($this->isCli() === false) { |
| 143 |
// @codeCoverageIgnoreStart |
| 144 |
echo '<a href="/download.php?type=' . pathinfo($path, PATHINFO_EXTENSION) . '&name=' . basename($path) . '">Download ' . basename($path) . '</a><br />'; |
| 145 |
// @codeCoverageIgnoreEnd |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
protected function isDirOrMkdir(string $folder): bool |
| 150 |
{ |
| 151 |
return \is_dir($folder) || \mkdir($folder); |
| 152 |
} |
| 153 |
|
| 154 |
/** |
| 155 |
* Returns the temporary directory and make sure it exists. |
| 156 |
*/ |
| 157 |
public function getTemporaryFolder(): string |
| 158 |
{ |
| 159 |
$tempFolder = sys_get_temp_dir() . '/phpspreadsheet'; |
| 160 |
if (!$this->isDirOrMkdir($tempFolder)) { |
| 161 |
throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder)); |
| 162 |
} |
| 163 |
|
| 164 |
return $tempFolder; |
| 165 |
} |
| 166 |
|
| 167 |
/** |
| 168 |
* Returns the filename that should be used for sample output. |
| 169 |
*/ |
| 170 |
public function getFilename(string $filename, string $extension = 'xlsx'): string |
| 171 |
{ |
| 172 |
$originalExtension = pathinfo($filename, PATHINFO_EXTENSION); |
| 173 |
|
| 174 |
return $this->getTemporaryFolder() . '/' . str_replace('.' . $originalExtension, '.' . $extension, basename($filename)); |
| 175 |
} |
| 176 |
|
| 177 |
/** |
| 178 |
* Return a random temporary file name. |
| 179 |
*/ |
| 180 |
public function getTemporaryFilename(string $extension = 'xlsx'): string |
| 181 |
{ |
| 182 |
$temporaryFilename = tempnam($this->getTemporaryFolder(), 'phpspreadsheet-'); |
| 183 |
if ($temporaryFilename === false) { |
| 184 |
// @codeCoverageIgnoreStart |
| 185 |
throw new RuntimeException('tempnam returned false'); |
| 186 |
// @codeCoverageIgnoreEnd |
| 187 |
} |
| 188 |
unlink($temporaryFilename); |
| 189 |
|
| 190 |
return $temporaryFilename . '.' . $extension; |
| 191 |
} |
| 192 |
|
| 193 |
/** |
| 194 |
* @param mixed $message |
| 195 |
*/ |
| 196 |
public function log($message): void |
| 197 |
{ |
| 198 |
$eol = $this->isCli() ? PHP_EOL : '<br />'; |
| 199 |
echo ($this->isCli() ? date('H:i:s ') : '') . StringHelper::convertToString($message) . $eol; |
| 200 |
} |
| 201 |
|
| 202 |
/** |
| 203 |
* Render chart as part of running chart samples in browser. |
| 204 |
* Charts are not rendered in unit tests, which are command line. |
| 205 |
* |
| 206 |
* @codeCoverageIgnore |
| 207 |
*/ |
| 208 |
public function renderChart(Chart $chart, string $fileName, ?Spreadsheet $spreadsheet = null): void |
| 209 |
{ |
| 210 |
if ($this->isCli() === true) { |
| 211 |
return; |
| 212 |
} |
| 213 |
Settings::setChartRenderer(MtJpGraphRenderer::class); |
| 214 |
|
| 215 |
$fileName = $this->getFilename($fileName, 'png'); |
| 216 |
$title = $chart->getTitle(); |
| 217 |
$caption = null; |
| 218 |
if ($title !== null) { |
| 219 |
$calculatedTitle = $title->getCalculatedTitle($spreadsheet); |
| 220 |
if ($calculatedTitle !== null) { |
| 221 |
$caption = $title->getCaption(); |
| 222 |
$title->setCaption($calculatedTitle); |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
try { |
| 227 |
$chart->render($fileName); |
| 228 |
$this->log('Rendered image: ' . $fileName); |
| 229 |
$imageData = @file_get_contents($fileName); |
| 230 |
if ($imageData !== false) { |
| 231 |
echo '<div><img src="data:image/gif;base64,' . base64_encode($imageData) . '" /></div>'; |
| 232 |
} else { |
| 233 |
$this->log('Unable to open chart' . PHP_EOL); |
| 234 |
} |
| 235 |
} catch (Throwable $e) { |
| 236 |
$this->log('Error rendering chart: ' . $e->getMessage() . PHP_EOL); |
| 237 |
} |
| 238 |
if (isset($title, $caption)) { |
| 239 |
$title->setCaption($caption); |
| 240 |
} |
| 241 |
Settings::unsetChartRenderer(); |
| 242 |
} |
| 243 |
|
| 244 |
public function titles(string $category, string $functionName, ?string $description = null): void |
| 245 |
{ |
| 246 |
$this->log(sprintf('%s Functions:', $category)); |
| 247 |
$description === null |
| 248 |
? $this->log(sprintf('Function: %s()', rtrim($functionName, '()'))) |
| 249 |
: $this->log(sprintf('Function: %s() - %s.', rtrim($functionName, '()'), rtrim($description, '.'))); |
| 250 |
} |
| 251 |
|
| 252 |
/** @param mixed[][] $matrix |
| 253 |
* @param null|bool|\TablePress\PhpOffice\PhpSpreadsheet\Helper\TextGridRightAlign $numbersRight */ |
| 254 |
public function displayGrid(array $matrix, $numbersRight = null): void |
| 255 |
{ |
| 256 |
$renderer = new TextGrid($matrix, $this->isCli()); |
| 257 |
if (is_bool($numbersRight)) { |
| 258 |
$numbersRight = $numbersRight ? TextGridRightAlign::numeric : TextGridRightAlign::none; |
| 259 |
} |
| 260 |
if ($numbersRight !== null) { |
| 261 |
$renderer->setNumbersRight($numbersRight); |
| 262 |
} |
| 263 |
echo $renderer->render(); |
| 264 |
} |
| 265 |
|
| 266 |
public function logCalculationResult( |
| 267 |
Worksheet $worksheet, |
| 268 |
string $functionName, |
| 269 |
string $formulaCell, |
| 270 |
?string $descriptionCell = null |
| 271 |
): void { |
| 272 |
if ($descriptionCell !== null) { |
| 273 |
$this->log($worksheet->getCell($descriptionCell)->getValueString()); |
| 274 |
} |
| 275 |
$this->log($worksheet->getCell($formulaCell)->getValueString()); |
| 276 |
$this->log(sprintf('%s() Result is ', $functionName) . $worksheet->getCell($formulaCell)->getCalculatedValueString()); |
| 277 |
} |
| 278 |
|
| 279 |
/** |
| 280 |
* Log ending notes. |
| 281 |
*/ |
| 282 |
public function logEndingNotes(): void |
| 283 |
{ |
| 284 |
// Do not show execution time for index |
| 285 |
$this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB'); |
| 286 |
} |
| 287 |
|
| 288 |
/** |
| 289 |
* Log a line about the write operation. |
| 290 |
*/ |
| 291 |
public function logWrite(IWriter $writer, string $path, float $callStartTime): void |
| 292 |
{ |
| 293 |
$callEndTime = microtime(true); |
| 294 |
$callTime = $callEndTime - $callStartTime; |
| 295 |
$reflection = new ReflectionClass($writer); |
| 296 |
$format = $reflection->getShortName(); |
| 297 |
|
| 298 |
$codePath = $this->isCli() ? $path : "<code>$path</code>"; |
| 299 |
$message = "Write {$format} format to {$codePath} in " . sprintf('%.4f', $callTime) . ' seconds'; |
| 300 |
|
| 301 |
$this->log($message); |
| 302 |
} |
| 303 |
|
| 304 |
/** |
| 305 |
* Log a line about the read operation. |
| 306 |
*/ |
| 307 |
public function logRead(string $format, string $path, float $callStartTime): void |
| 308 |
{ |
| 309 |
$callEndTime = microtime(true); |
| 310 |
$callTime = $callEndTime - $callStartTime; |
| 311 |
$message = "Read {$format} format from <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds'; |
| 312 |
|
| 313 |
$this->log($message); |
| 314 |
} |
| 315 |
} |
| 316 |
|