Completed
Pull Request — master (#717)
by
unknown
03:27
created

WriterAbstract::getContentDispositionHeader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Box\Spout\Writer;
4
5
use Box\Spout\Common\Creator\HelperFactory;
6
use Box\Spout\Common\Entity\Row;
7
use Box\Spout\Common\Entity\Style\Style;
8
use Box\Spout\Common\Exception\InvalidArgumentException;
9
use Box\Spout\Common\Exception\IOException;
10
use Box\Spout\Common\Exception\SpoutException;
11
use Box\Spout\Common\Helper\GlobalFunctionsHelper;
12
use Box\Spout\Common\Manager\OptionsManagerInterface;
13
use Box\Spout\Writer\Common\Entity\Options;
14
use Box\Spout\Writer\Exception\WriterAlreadyOpenedException;
15
use Box\Spout\Writer\Exception\WriterNotOpenedException;
16
17
/**
18
 * Class WriterAbstract
19
 *
20
 * @abstract
21
 */
22
abstract class WriterAbstract implements WriterInterface
23
{
24
    /** @var string Path to the output file */
25
    protected $outputFilePath;
26
27
    /** @var resource Pointer to the file/stream we will write to */
28
    protected $filePointer;
29
30
    /** @var bool Indicates whether the writer has been opened or not */
31
    protected $isWriterOpened = false;
32
33
    /** @var GlobalFunctionsHelper Helper to work with global functions */
34
    protected $globalFunctionsHelper;
35
36
    /** @var HelperFactory $helperFactory */
37
    protected $helperFactory;
38
39
    /** @var OptionsManagerInterface Writer options manager */
40
    protected $optionsManager;
41
42
    /** @var string Content-Type value for the header - to be defined by child class */
43
    protected static $headerContentType;
44
45
    /**
46
     * @param OptionsManagerInterface $optionsManager
47
     * @param GlobalFunctionsHelper $globalFunctionsHelper
48
     * @param HelperFactory $helperFactory
49
     */
50 105
    public function __construct(
51
        OptionsManagerInterface $optionsManager,
52
        GlobalFunctionsHelper $globalFunctionsHelper,
53
        HelperFactory $helperFactory
54
    ) {
55 105
        $this->optionsManager = $optionsManager;
56 105
        $this->globalFunctionsHelper = $globalFunctionsHelper;
57 105
        $this->helperFactory = $helperFactory;
58 105
    }
59
60
    /**
61
     * Opens the streamer and makes it ready to accept data.
62
     *
63
     * @throws IOException If the writer cannot be opened
64
     * @return void
65
     */
66
    abstract protected function openWriter();
67
68
    /**
69
     * Adds a row to the currently opened writer.
70
     *
71
     * @param Row $row The row containing cells and styles
72
     * @throws WriterNotOpenedException If the workbook is not created yet
73
     * @throws IOException If unable to write data
74
     * @return void
75
     */
76
    abstract protected function addRowToWriter(Row $row);
77
78
    /**
79
     * Closes the streamer, preventing any additional writing.
80
     *
81
     * @return void
82
     */
83
    abstract protected function closeWriter();
84
85
    /**
86
     * {@inheritdoc}
87
     */
88 2
    public function setDefaultRowStyle(Style $defaultStyle)
89
    {
90 2
        $this->optionsManager->setOption(Options::DEFAULT_ROW_STYLE, $defaultStyle);
91
92 2
        return $this;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98 90
    public function openToFile($outputFilePath)
99
    {
100 90
        $this->outputFilePath = $outputFilePath;
101
102 90
        $this->filePointer = $this->globalFunctionsHelper->fopen($this->outputFilePath, 'wb+');
103 90
        $this->throwIfFilePointerIsNotAvailable();
104
105 87
        $this->openWriter();
106 87
        $this->isWriterOpened = true;
107
108 87
        return $this;
109
    }
110
111
    /**
112
     * @codeCoverageIgnore
113
     * {@inheritdoc}
114
     */
115
    public function openToBrowser($outputFileName)
116
    {
117
        $this->outputFilePath = $this->globalFunctionsHelper->basename($outputFileName);
118
119
        $this->filePointer = $this->globalFunctionsHelper->fopen('php://output', 'w');
120
        $this->throwIfFilePointerIsNotAvailable();
121
122
        // Clear any previous output (otherwise the generated file will be corrupted)
123
        // @see https://github.com/box/spout/issues/241
124
        $this->globalFunctionsHelper->ob_end_clean();
125
126
        // Set headers
127
        $this->globalFunctionsHelper->header('Content-Type: ' . static::$headerContentType);
128
        $this->globalFunctionsHelper->header($this->getContentDispositionHeader());
129
130
        /*
131
         * When forcing the download of a file over SSL,IE8 and lower browsers fail
132
         * if the Cache-Control and Pragma headers are not set.
133
         *
134
         * @see http://support.microsoft.com/KB/323308
135
         * @see https://github.com/liuggio/ExcelBundle/issues/45
136
         */
137
        $this->globalFunctionsHelper->header('Cache-Control: max-age=0');
138
        $this->globalFunctionsHelper->header('Pragma: public');
139
140
        $this->openWriter();
141
        $this->isWriterOpened = true;
142
143
        return $this;
144
    }
145
146
    /**
147
     * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
148
     * @see https://tools.ietf.org/html/rfc5987
149
     * @see https://tools.ietf.org/html/rfc2231#section-4
150
     */
151
    protected function getContentDispositionHeader() : string
152
    {
153
        return 'Content-Disposition: attachment; filename="' . iconv('UTF-8', 'ASCII//IGNORE', $this->outputFilePath) . '"; filename*=utf-8\'\'' . rawurlencode($this->outputFilePath);
154
    }
155
156
    /**
157
     * Checks if the pointer to the file/stream to write to is available.
158
     * Will throw an exception if not available.
159
     *
160
     * @throws IOException If the pointer is not available
161
     * @return void
162
     */
163 90
    protected function throwIfFilePointerIsNotAvailable()
164
    {
165 90
        if (!$this->filePointer) {
166 3
            throw new IOException('File pointer has not be opened');
167
        }
168 87
    }
169
170
    /**
171
     * Checks if the writer has already been opened, since some actions must be done before it gets opened.
172
     * Throws an exception if already opened.
173
     *
174
     * @param string $message Error message
175
     * @throws WriterAlreadyOpenedException If the writer was already opened and must not be.
176
     * @return void
177
     */
178 54
    protected function throwIfWriterAlreadyOpened($message)
179
    {
180 54
        if ($this->isWriterOpened) {
181 5
            throw new WriterAlreadyOpenedException($message);
182
        }
183 49
    }
184
185
    /**
186
     * {@inheritdoc}
187
     */
188 85
    public function addRow(Row $row)
189
    {
190 85
        if ($this->isWriterOpened) {
191
            try {
192 75
                $this->addRowToWriter($row);
193 4
            } catch (SpoutException $e) {
194
                // if an exception occurs while writing data,
195
                // close the writer and remove all files created so far.
196 4
                $this->closeAndAttemptToCleanupAllFiles();
197
198
                // re-throw the exception to alert developers of the error
199 75
                throw $e;
200
            }
201
        } else {
202 10
            throw new WriterNotOpenedException('The writer needs to be opened before adding row.');
203
        }
204
205 73
        return $this;
206
    }
207
208
    /**
209
     * {@inheritdoc}
210
     */
211 71
    public function addRows(array $rows)
212
    {
213 71
        foreach ($rows as $row) {
214 71
            if (!$row instanceof Row) {
215 2
                $this->closeAndAttemptToCleanupAllFiles();
216 2
                throw new InvalidArgumentException('The input should be an array of Row');
217
            }
218
219 69
            $this->addRow($row);
220
        }
221
222 63
        return $this;
223
    }
224
225
    /**
226
     * {@inheritdoc}
227
     */
228 81
    public function close()
229
    {
230 81
        if (!$this->isWriterOpened) {
231 1
            return;
232
        }
233
234 80
        $this->closeWriter();
235
236 80
        if (\is_resource($this->filePointer)) {
237 80
            $this->globalFunctionsHelper->fclose($this->filePointer);
238
        }
239
240 80
        $this->isWriterOpened = false;
241 80
    }
242
243
    /**
244
     * Closes the writer and attempts to cleanup all files that were
245
     * created during the writing process (temp files & final file).
246
     *
247
     * @return void
248
     */
249 6
    private function closeAndAttemptToCleanupAllFiles()
250
    {
251
        // close the writer, which should remove all temp files
252 6
        $this->close();
253
254
        // remove output file if it was created
255 6
        if ($this->globalFunctionsHelper->file_exists($this->outputFilePath)) {
256 5
            $outputFolderPath = \dirname($this->outputFilePath);
257 5
            $fileSystemHelper = $this->helperFactory->createFileSystemHelper($outputFolderPath);
258 5
            $fileSystemHelper->deleteFile($this->outputFilePath);
259
        }
260 6
    }
261
}
262