Passed
Pull Request — master (#4267)
by Owen
16:14
created

Sample::getTemporaryFilename()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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