Passed
Push — master ( 4b8292...9204d2 )
by Mark
10:15
created

Sample::getTemporaryFilename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Helper;
4
5
use PhpOffice\PhpSpreadsheet\IOFactory;
6
use PhpOffice\PhpSpreadsheet\Spreadsheet;
7
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
8
use RecursiveDirectoryIterator;
9
use RecursiveIteratorIterator;
10
use RecursiveRegexIterator;
11
use ReflectionClass;
12
use RegexIterator;
13
use RuntimeException;
14
15
/**
16
 * Helper class to be used in sample code.
17
 */
18
class Sample
19
{
20
    /**
21
     * Returns whether we run on CLI or browser.
22
     *
23
     * @return bool
24
     */
25 161
    public function isCli()
26
    {
27 161
        return PHP_SAPI === 'cli';
28
    }
29
30
    /**
31
     * Return the filename currently being executed.
32
     *
33
     * @return string
34
     */
35 1
    public function getScriptFilename()
36
    {
37 1
        return basename($_SERVER['SCRIPT_FILENAME'], '.php');
38
    }
39
40
    /**
41
     * Whether we are executing the index page.
42
     *
43
     * @return bool
44
     */
45 1
    public function isIndex()
46
    {
47 1
        return $this->getScriptFilename() === 'index';
48
    }
49
50
    /**
51
     * Return the page title.
52
     *
53
     * @return string
54
     */
55 1
    public function getPageTitle()
56
    {
57 1
        return $this->isIndex() ? 'PHPSpreadsheet' : $this->getScriptFilename();
58
    }
59
60
    /**
61
     * Return the page heading.
62
     *
63
     * @return string
64
     */
65 1
    public function getPageHeading()
66
    {
67 1
        return $this->isIndex() ? '' : '<h1>' . str_replace('_', ' ', $this->getScriptFilename()) . '</h1>';
68
    }
69
70
    /**
71
     * Returns an array of all known samples.
72
     *
73
     * @return string[][] [$name => $path]
74
     */
75 1
    public function getSamples()
76
    {
77
        // Populate samples
78 1
        $baseDir = realpath(__DIR__ . '/../../../samples');
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 1
        foreach ($regex as $file) {
85 1
            $file = str_replace(str_replace('\\', '/', $baseDir) . '/', '', str_replace('\\', '/', $file[0]));
86 1
            $info = pathinfo($file);
87 1
            $category = str_replace('_', ' ', $info['dirname']);
88 1
            $name = str_replace('_', ' ', preg_replace('/(|\.php)/', '', $info['filename']));
89 1
            if (!in_array($category, ['.', 'boostrap', 'templates'])) {
90 1
                if (!isset($files[$category])) {
91 1
                    $files[$category] = [];
92
                }
93 1
                $files[$category][$name] = $file;
94
            }
95
        }
96
97
        // Sort everything
98 1
        ksort($files);
99 1
        foreach ($files as &$f) {
100 1
            asort($f);
101
        }
102
103 1
        return $files;
104
    }
105
106
    /**
107
     * Write documents.
108
     *
109
     * @param string $filename
110
     * @param string[] $writers
111
     */
112 53
    public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Xlsx', 'Xls']): void
113
    {
114
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
115 53
        $spreadsheet->setActiveSheetIndex(0);
116
117
        // Write documents
118 53
        foreach ($writers as $writerType) {
119 53
            $path = $this->getFilename($filename, mb_strtolower($writerType));
120 53
            $writer = IOFactory::createWriter($spreadsheet, $writerType);
121 53
            $callStartTime = microtime(true);
122 53
            $writer->save($path);
123 53
            $this->logWrite($writer, $path, $callStartTime);
1 ignored issue
show
Bug introduced by
It seems like $callStartTime can also be of type string; however, parameter $callStartTime of PhpOffice\PhpSpreadsheet\Helper\Sample::logWrite() does only seem to accept double, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

123
            $this->logWrite($writer, $path, /** @scrutinizer ignore-type */ $callStartTime);
Loading history...
124
        }
125
126 53
        $this->logEndingNotes();
127 53
    }
128
129 79
    protected function isDirOrMkdir(string $folder): bool
130
    {
131 79
        return \is_dir($folder) || \mkdir($folder);
132
    }
133
134
    /**
135
     * Returns the temporary directory and make sure it exists.
136
     *
137
     * @return string
138
     */
139 80
    private function getTemporaryFolder()
140
    {
141 80
        $tempFolder = sys_get_temp_dir() . '/phpspreadsheet';
142 80
        if (!$this->isDirOrMkdir($tempFolder)) {
143 1
            throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder));
144
        }
145
146 79
        return $tempFolder;
147
    }
148
149
    /**
150
     * Returns the filename that should be used for sample output.
151
     *
152
     * @param string $filename
153
     * @param string $extension
154
     *
155
     * @return string
156
     */
157 78
    public function getFilename($filename, $extension = 'xlsx')
158
    {
159 78
        $originalExtension = pathinfo($filename, PATHINFO_EXTENSION);
160
161 78
        return $this->getTemporaryFolder() . '/' . str_replace('.' . $originalExtension, '.' . $extension, basename($filename));
1 ignored issue
show
Bug introduced by
Are you sure $originalExtension of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

161
        return $this->getTemporaryFolder() . '/' . str_replace('.' . /** @scrutinizer ignore-type */ $originalExtension, '.' . $extension, basename($filename));
Loading history...
162
    }
163
164
    /**
165
     * Return a random temporary file name.
166
     *
167
     * @param string $extension
168
     *
169
     * @return string
170
     */
171 7
    public function getTemporaryFilename($extension = 'xlsx')
172
    {
173 7
        $temporaryFilename = tempnam($this->getTemporaryFolder(), 'phpspreadsheet-');
174 7
        unlink($temporaryFilename);
175
176 7
        return $temporaryFilename . '.' . $extension;
177
    }
178
179 160
    public function log($message): void
180
    {
181 160
        $eol = $this->isCli() ? PHP_EOL : '<br />';
182 160
        echo date('H:i:s ') . $message . $eol;
183 160
    }
184
185
    /**
186
     * Log ending notes.
187
     */
188 56
    public function logEndingNotes(): void
189
    {
190
        // Do not show execution time for index
191 56
        $this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB');
192 56
    }
193
194
    /**
195
     * Log a line about the write operation.
196
     *
197
     * @param string $path
198
     * @param float $callStartTime
199
     */
200 75
    public function logWrite(IWriter $writer, $path, $callStartTime): void
201
    {
202 75
        $callEndTime = microtime(true);
203 75
        $callTime = $callEndTime - $callStartTime;
204 75
        $reflection = new ReflectionClass($writer);
205 75
        $format = $reflection->getShortName();
206 75
        $message = "Write {$format} format to <code>{$path}</code>  in " . sprintf('%.4f', $callTime) . ' seconds';
207
208 75
        $this->log($message);
209 75
    }
210
211
    /**
212
     * Log a line about the read operation.
213
     *
214
     * @param string $format
215
     * @param string $path
216
     * @param float $callStartTime
217
     */
218 14
    public function logRead($format, $path, $callStartTime): void
219
    {
220 14
        $callEndTime = microtime(true);
221 14
        $callTime = $callEndTime - $callStartTime;
222 14
        $message = "Read {$format} format from <code>{$path}</code>  in " . sprintf('%.4f', $callTime) . ' seconds';
223
224 14
        $this->log($message);
225 14
    }
226
}
227