Completed
Pull Request — master (#235)
by
unknown
03:06
created

AbstractReader::doesSupportStreamWrapper()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 1
ccs 0
cts 0
cp 0
nc 1
1
<?php
2
3
namespace Box\Spout\Reader;
4
5
use Box\Spout\Common\Exception\IOException;
6
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
7
8
/**
9
 * Class AbstractReader
10
 *
11
 * @package Box\Spout\Reader
12
 * @abstract
13
 */
14
abstract class AbstractReader implements ReaderInterface
15
{
16
    /** @var bool Indicates whether the stream is currently open */
17
    protected $isStreamOpened = false;
18
19
    /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper Helper to work with global functions */
20
    protected $globalFunctionsHelper;
21
22
    /** @var \Box\Spout\Reader\ReaderOptions */
23
    protected $readerOptions;
24
25
    /**
26
     * The constructor.
27
     */
28 312
    public function __construct()
29
    {
30 312
        $this->readerOptions = new ReaderOptions();
31 312
    }
32
33
    /**
34
     * Returns whether stream wrappers are supported
35
     *
36
     * @return bool
37
     */
38
    abstract protected function doesSupportStreamWrapper();
39
40
    /**
41
     * Opens the file at the given file path to make it ready to be read
42
     *
43
     * @param  string $filePath Path of the file to be read
44
     * @return void
45
     */
46
    abstract protected function openReader($filePath);
47
48
    /**
49
     * Returns an iterator to iterate over sheets.
50
     *
51
     * @return \Iterator To iterate over sheets
52
     */
53
    abstract public function getConcreteSheetIterator();
54
55
    /**
56
     * Closes the reader. To be used after reading the file.
57
     *
58
     * @return AbstractReader
59
     */
60
    abstract protected function closeReader();
61
62
    /**
63
     * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper
64
     * @return AbstractReader
65
     */
66 312
    public function setGlobalFunctionsHelper($globalFunctionsHelper)
67
    {
68 312
        $this->globalFunctionsHelper = $globalFunctionsHelper;
69 312
        return $this;
70
    }
71
72
    /**
73
     * Sets whether date/time values should be returned as PHP objects or be formatted as strings.
74
     *
75
     * @param bool $shouldFormatDates
76
     * @return AbstractReader
77
     */
78 6
    public function setShouldFormatDates($shouldFormatDates)
79
    {
80 6
        $this->readerOptions->setShouldFormatDates($shouldFormatDates);
81 6
        return $this;
82
    }
83
84
    /**
85
     * Sets whether to skip or return "empty" rows.
86
     *
87
     * @param bool $shouldPreserveEmptyRows
88
     * @return AbstractReader
89
     */
90 24
    public function setShouldPreserveEmptyRows($shouldPreserveEmptyRows)
91
    {
92 24
        $this->readerOptions->setShouldPreserveEmptyRows($shouldPreserveEmptyRows);
93 24
        return $this;
94
    }
95
96
    /**
97
     * Prepares the reader to read the given file. It also makes sure
98
     * that the file exists and is readable.
99
     *
100
     * @api
101
     * @param  string $filePath Path of the file to be read
102
     * @return void
103
     * @throws \Box\Spout\Common\Exception\IOException If the file at the given path does not exist, is not readable or is corrupted
104
     */
105 309
    public function open($filePath)
106
    {
107 309
        if ($this->isStreamWrapper($filePath) && (!$this->doesSupportStreamWrapper() || !$this->isSupportedStreamWrapper($filePath))) {
108 15
            throw new IOException("Could not open $filePath for reading! Stream wrapper used is not supported for this type of file.");
109
        }
110
111 294
        if (!$this->isPhpStream($filePath)) {
112
            // we skip the checks if the provided file path points to a PHP stream
113 294
            if (!$this->globalFunctionsHelper->file_exists($filePath)) {
114 9
                throw new IOException("Could not open $filePath for reading! File does not exist.");
115 285
            } else if (!$this->globalFunctionsHelper->is_readable($filePath)) {
116 3
                throw new IOException("Could not open $filePath for reading! File is not readable.");
117
            }
118 282
        }
119
120
        try {
121 282
            $fileRealPath = $this->getFileRealPath($filePath);
122 282
            $this->openReader($fileRealPath);
123 267
            $this->isStreamOpened = true;
124 282
        } catch (\Exception $exception) {
125 15
            throw new IOException("Could not open $filePath for reading! ({$exception->getMessage()})");
126
        }
127 267
    }
128
129
    /**
130
     * Returns the real path of the given path.
131
     * If the given path is a valid stream wrapper, returns the path unchanged.
132
     *
133
     * @param string $filePath
134
     * @return string
135
     */
136 282
    protected function getFileRealPath($filePath)
137
    {
138 282
        if ($this->isSupportedStreamWrapper($filePath)) {
139 282
            return $filePath;
140
        }
141
142
        // Need to use realpath to fix "Can't open file" on some Windows setup
143
        return realpath($filePath);
144
    }
145
146
    /**
147
     * Returns the scheme of the custom stream wrapper, if the path indicates a stream wrapper is used.
148
     * For example, php://temp => php, s3://path/to/file => s3...
149
     *
150
     * @param string $filePath Path of the file to be read
151
     * @return string|null The stream wrapper scheme or NULL if not a stream wrapper
152
     */
153 309
    protected function getStreamWrapperScheme($filePath)
154
    {
155 309
        $streamScheme = null;
156 309
        if (preg_match('/^(\w+):\/\//', $filePath, $matches)) {
157 18
            $streamScheme = $matches[1];
158 18
        }
159 309
        return $streamScheme;
160
    }
161
162
    /**
163
     * Checks if the given path is an unsupported stream wrapper
164
     * (like local path, php://temp, mystream://foo/bar...).
165
     *
166
     * @param string $filePath Path of the file to be read
167
     * @return bool Whether the given path is an unsupported stream wrapper
168
     */
169 309
    protected function isStreamWrapper($filePath)
170
    {
171 309
        return ($this->getStreamWrapperScheme($filePath) !== null);
172
    }
173
174
    /**
175
     * Checks if the given path is an supported stream wrapper
176
     * (like php://temp, mystream://foo/bar...).
177
     * If the given path is a local path, returns true.
178
     *
179
     * @param string $filePath Path of the file to be read
180
     * @return bool Whether the given path is an supported stream wrapper
181
     */
182 285
    protected function isSupportedStreamWrapper($filePath)
183
    {
184 285
        $streamScheme = $this->getStreamWrapperScheme($filePath);
185 285
        return ($streamScheme !== null) ?
186 285
            in_array($streamScheme, $this->globalFunctionsHelper->stream_get_wrappers()) :
187 285
            true;
188
    }
189
190
    /**
191
     * Checks if a path is a PHP stream (like php://output, php://memory, ...)
192
     *
193
     * @param string $filePath Path of the file to be read
194
     * @return bool Whether the given path maps to a PHP stream
195
     */
196 294
    protected function isPhpStream($filePath)
197
    {
198 294
        $streamScheme = $this->getStreamWrapperScheme($filePath);
199 294
        return ($streamScheme === 'php');
200
    }
201
202
    /**
203
     * Returns an iterator to iterate over sheets.
204
     *
205
     * @api
206
     * @return \Iterator To iterate over sheets
207
     * @throws \Box\Spout\Reader\Exception\ReaderNotOpenedException If called before opening the reader
208
     */
209 270
    public function getSheetIterator()
210
    {
211 270
        if (!$this->isStreamOpened) {
212 3
            throw new ReaderNotOpenedException('Reader should be opened first.');
213
        }
214
215 267
        return $this->getConcreteSheetIterator();
216
    }
217
218
    /**
219
     * Closes the reader, preventing any additional reading
220
     *
221
     * @api
222
     * @return void
223
     */
224 255
    public function close()
225
    {
226 255
        if ($this->isStreamOpened) {
227 255
            $this->closeReader();
228
229 255
            $sheetIterator = $this->getConcreteSheetIterator();
230 255
            if ($sheetIterator) {
231 255
                $sheetIterator->end();
232 255
            }
233
234 255
            $this->isStreamOpened = false;
235 255
        }
236 255
    }
237
}
238