Completed
Pull Request — master (#226)
by Adrien
02:44
created

AbstractReader::setGlobalFunctionsHelper()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

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