Completed
Push — develop ( 08525a...2922a1 )
by Adrien
22:42
created

Sample::isIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace PhpSpreadsheet\Helper;
4
5
use PhpSpreadsheet\IOFactory;
6
use PhpSpreadsheet\Spreadsheet;
7
8
class Sample
9
{
10
    /**
11
     * Returns wether we run on CLI or browser
12
     * @return bool
13
     */
14
    public function isCli()
15
    {
16
        return PHP_SAPI === 'cli';
17
    }
18
19
    /**
20
     * Return the filename currently being executed
21
     * @return string
22
     */
23
    public function getScriptFilename()
0 ignored issues
show
Coding Style introduced by
getScriptFilename uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
24
    {
25
        return basename($_SERVER['SCRIPT_FILENAME'], '.php');
26
    }
27
28
    /**
29
     * Wether we are executing the index page
30
     * @return bool
31
     */
32
    public function isIndex()
33
    {
34
        return $this->getScriptFilename() === 'index';
35
    }
36
37
    /**
38
     * Return the page title
39
     * @return string
40
     */
41
    public function getPageTitle()
42
    {
43
        return $this->isIndex() ? 'PHPSpreadsheet' : $this->getScriptFilename();
44
    }
45
46
    /**
47
     * Return the page heading
48
     * @return string
49
     */
50
    public function getPageHeading()
51
    {
52
        return $this->isIndex() ? '' : '<h1>' . str_replace('_', ' ', $this->getScriptFilename()) . '</h1>';
53
    }
54
55
    /**
56
     * Returns an array of all known samples
57
     * @return string[] [$name => $path]
58
     */
59
    public function getSamples()
60
    {
61
        // Populate samples
62
        $files = [];
63
        foreach (glob(realpath(__DIR__ . '/../../../samples') . '/*.php') as $file) {
64
            $info = pathinfo($file);
65
            $name = str_replace('_', ' ', preg_replace('/(|\.php)/', '', $info['filename']));
66
            if (preg_match('/^\d+/', $name)) {
67
                $files[$name] = $file;
68
            }
69
        }
70
71
        return $files;
72
    }
73
74
    /**
75
     * Write documents
76
     *
77
     * @param Spreadsheet $spreadsheet
78
     * @param string $filename
79
     * @param array $writers
80
     */
81
    public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Excel2007' => 'xlsx', 'Excel5' => 'xls'])
82
    {
83
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
84
        $spreadsheet->setActiveSheetIndex(0);
85
86
        // Write documents
87
        foreach ($writers as $format => $extension) {
88
            $path = $this->getFilename($filename, $extension);
89
            if (!is_null($extension)) {
90
                $writer = IOFactory::createWriter($spreadsheet, $format);
91
                $callStartTime = microtime(true);
92
                $writer->save($path);
93
                $this->logWrite($writer, $path, $callStartTime);
94
            } else {
95
                throw new \Exception('Missing extension');
96
            }
97
        }
98
99
        $this->logEndingNotes();
100
    }
101
102
    /**
103
     * Returns the temporary directory and make sure it exists
104
     * @return string
105
     */
106
    private function getTemporaryFolder()
107
    {
108
        $tempFolder = sys_get_temp_dir() . '/phpspreadsheet';
109
        if (!is_dir($tempFolder)) {
110
            mkdir($tempFolder);
111
        }
112
113
        return $tempFolder;
114
    }
115
116
    /**
117
     * Returns the filename that should be used for sample output
118
     * @param string $filename
119
     * @param string $extension
120
     * @return string
121
     */
122
    public function getFilename($filename, $extension = 'xlsx')
123
    {
124
        return $this->getTemporaryFolder() . '/' . str_replace('.php', '.' . $extension, basename($filename));
125
    }
126
127
    /**
128
     * Return a random temporary file name
129
     * @param string $extension
130
     * @return string
131
     */
132
    public function getTemporaryFilename($extension = 'xlsx')
133
    {
134
        $temporaryFilename = tempnam($this->getTemporaryFolder(), 'phpspreadsheet-');
135
        unlink($temporaryFilename);
136
137
        return $temporaryFilename . '.' . $extension;
138
    }
139
140
    public function log($message)
141
    {
142
        echo date('H:i:s '), $message, EOL;
143
    }
144
145
    /**
146
     * Log ending notes
147
     */
148
    public function logEndingNotes()
149
    {
150
        // Do not show execution time for index
151
        $this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB');
152
    }
153
154
    /**
155
     * Log a line about the write operation
156
     * @param \PhpSpreadsheet\Writer\IWriter $writer
157
     * @param string $path
158
     * @param float $callStartTime
159
     */
160
    public function logWrite(\PhpSpreadsheet\Writer\IWriter $writer, $path, $callStartTime)
161
    {
162
        $callEndTime = microtime(true);
163
        $callTime = $callEndTime - $callStartTime;
164
        $reflection = new \ReflectionClass($writer);
165
        $format = $reflection->getShortName();
166
        $message = "Write {$format} format to <code>{$path}</code>  in " . sprintf('%.4f', $callTime) . ' seconds';
167
168
        $this->log($message);
169
    }
170
171
    /**
172
     * Log a line about the read operation
173
     * @param string $format
174
     * @param string $path
175
     * @param float $callStartTime
176
     */
177
    public function logRead($format, $path, $callStartTime)
178
    {
179
        $callEndTime = microtime(true);
180
        $callTime = $callEndTime - $callStartTime;
181
        $message = "Read {$format} format from <code>{$path}</code>  in " . sprintf('%.4f', $callTime) . ' seconds';
182
183
        $this->log($message);
184
    }
185
}
186