Passed
Push — devel-3.0 ( 40e719...463a23 )
by Rubén
03:27
created

FileHandler::read()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 4
nop 0
dl 0
loc 15
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * sysPass
4
 *
5
 * @author    nuxsmin
6
 * @link      https://syspass.org
7
 * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
8
 *
9
 * This file is part of sysPass.
10
 *
11
 * sysPass is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation, either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * sysPass is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 *  along with sysPass.  If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace SP\Storage\File;
26
27
use SP\Util\Util;
28
29
/**
30
 * Class FileHandler
31
 *
32
 * @package SP\Storage\File;
33
 */
34
final class FileHandler
35
{
36
    const CHUNK_LENGTH = 8192;
37
    const CHUNK_FACTOR = 3;
38
    /**
39
     * @var string
40
     */
41
    protected $file;
42
    /**
43
     * @var resource
44
     */
45
    protected $handle;
46
47
    /**
48
     * FileHandler constructor.
49
     *
50
     * @param string $file
51
     */
52
    public function __construct(string $file)
53
    {
54
        $this->file = $file;
55
    }
56
57
    /**
58
     * Writes data into file
59
     *
60
     * @param $data
61
     *
62
     * @return FileHandler
63
     * @throws FileException
64
     */
65
    public function write($data)
66
    {
67
        if (!is_resource($this->handle)) {
68
            $this->open('wb');
69
        }
70
71
        if (@fwrite($this->handle, $data) === false) {
0 ignored issues
show
Bug introduced by
It seems like $this->handle can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, 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

71
        if (@fwrite(/** @scrutinizer ignore-type */ $this->handle, $data) === false) {
Loading history...
72
            throw new FileException(sprintf(__('No es posible escribir en el archivo (%s)'), $this->file));
73
        }
74
75
        return $this;
76
    }
77
78
    /**
79
     * Opens the file
80
     *
81
     * @param $mode
82
     *
83
     * @return resource
84
     * @throws FileException
85
     */
86
    public function open($mode = 'r')
87
    {
88
        if (($this->handle = @fopen($this->file, $mode)) === false) {
0 ignored issues
show
Documentation Bug introduced by
It seems like @fopen($this->file, $mode) can also be of type false. However, the property $handle is declared as type resource. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
89
            throw new FileException(sprintf(__('No es posible abrir el archivo (%s)'), $this->file));
90
        }
91
92
        return $this->handle;
93
    }
94
95
    /**
96
     * Reads data from file into a string
97
     *
98
     * @return string Data read from file
99
     * @throws FileException
100
     */
101
    public function readToString(): string
102
    {
103
        if (($data = file_get_contents($this->file)) === false) {
104
            throw new FileException(sprintf(__('No es posible leer desde el archivo (%s)'), $this->file));
105
        }
106
107
        return $data;
108
    }
109
110
    /**
111
     * Reads data from file into an array
112
     *
113
     * @throws FileException
114
     */
115
    public function readToArray(): array
116
    {
117
        if (($data = @file($this->file, FILE_SKIP_EMPTY_LINES)) === false) {
118
            throw new FileException(sprintf(__('No es posible leer desde el archivo (%s)'), $this->file));
119
        }
120
121
        return $data;
122
    }
123
124
    /**
125
     * Reads data from file into a string
126
     *
127
     * @param string $data Data to write into file
128
     *
129
     * @return FileHandler
130
     * @throws FileException
131
     */
132
    public function save($data)
133
    {
134
        if (file_put_contents($this->file, $data, LOCK_EX) === false) {
135
            throw new FileException(sprintf(__('No es posible escribir en el archivo (%s)'), $this->file));
136
        }
137
138
        return $this;
139
    }
140
141
    /**
142
     * Reads data from file
143
     *
144
     * @return string Data read from file
145
     * @throws FileException
146
     */
147
    public function read()
148
    {
149
        if (!is_resource($this->handle)) {
150
            $this->open('rb');
151
        }
152
153
        $data = '';
154
155
        while (!feof($this->handle)) {
0 ignored issues
show
Bug introduced by
It seems like $this->handle can also be of type false; however, parameter $handle of feof() does only seem to accept resource, 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

155
        while (!feof(/** @scrutinizer ignore-type */ $this->handle)) {
Loading history...
156
            $data .= fread($this->handle, self::CHUNK_LENGTH);
0 ignored issues
show
Bug introduced by
It seems like $this->handle can also be of type false; however, parameter $handle of fread() does only seem to accept resource, 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

156
            $data .= fread(/** @scrutinizer ignore-type */ $this->handle, self::CHUNK_LENGTH);
Loading history...
157
        }
158
159
        $this->close();
160
161
        return $data;
162
    }
163
164
    /**
165
     * Closes the file
166
     *
167
     * @throws FileException
168
     * @return FileHandler
169
     */
170
    public function close()
171
    {
172
        if (!is_resource($this->handle) || @fclose($this->handle) === false) {
173
            throw new FileException(sprintf(__('No es posible cerrar el archivo (%s)'), $this->file));
174
        }
175
176
        return $this;
177
    }
178
179
    /**
180
     * @param callable $chunker
181
     * @param float    $rate
182
     *
183
     * @throws FileException
184
     */
185
    public function readChunked(callable $chunker = null, float $rate = null)
186
    {
187
        $maxRate = Util::getMaxDownloadChunk() / self::CHUNK_FACTOR;
188
189
        if ($rate === null || $rate > $maxRate) {
190
            $rate = $maxRate;
191
        }
192
193
        if (!is_resource($this->handle)) {
194
            $this->open('rb');
195
        }
196
197
        while (!feof($this->handle)) {
0 ignored issues
show
Bug introduced by
It seems like $this->handle can also be of type false; however, parameter $handle of feof() does only seem to accept resource, 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

197
        while (!feof(/** @scrutinizer ignore-type */ $this->handle)) {
Loading history...
198
            if ($chunker !== null) {
199
                $chunker(fread($this->handle, round($rate)));
0 ignored issues
show
Bug introduced by
round($rate) of type double is incompatible with the type integer expected by parameter $length of fread(). ( Ignorable by Annotation )

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

199
                $chunker(fread($this->handle, /** @scrutinizer ignore-type */ round($rate)));
Loading history...
Bug introduced by
It seems like $this->handle can also be of type false; however, parameter $handle of fread() does only seem to accept resource, 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

199
                $chunker(fread(/** @scrutinizer ignore-type */ $this->handle, round($rate)));
Loading history...
200
            } else {
201
                print fread($this->handle, round($rate));
202
                ob_flush();
203
                flush();
204
            }
205
        }
206
207
        $this->close();
208
    }
209
210
    /**
211
     * Checks if the file is writable
212
     *
213
     * @throws FileException
214
     * @return FileHandler
215
     */
216
    public function checkIsWritable()
217
    {
218
        if (!is_writable($this->file) && @touch($this->file) === false) {
219
            throw new FileException(sprintf(__('No es posible escribir el archivo (%s)'), $this->file));
220
        }
221
222
        return $this;
223
    }
224
225
    /**
226
     * Checks if the file exists
227
     *
228
     * @throws FileException
229
     * @return FileHandler
230
     */
231
    public function checkFileExists()
232
    {
233
        if (!file_exists($this->file)) {
234
            throw new FileException(sprintf(__('Archivo no encontrado (%s)'), $this->file));
235
        }
236
237
        return $this;
238
    }
239
240
    /**
241
     * @return string
242
     */
243
    public function getFile(): string
244
    {
245
        return $this->file;
246
    }
247
248
    /**
249
     * @param bool $isExceptionOnZero
250
     *
251
     * @return int
252
     * @throws FileException
253
     */
254
    public function getFileSize($isExceptionOnZero = false): int
255
    {
256
        $size = filesize($this->file);
257
258
        if ($size === false || ($isExceptionOnZero === true && $size === 0)) {
259
            throw new FileException(sprintf(__('No es posible leer el archivo (%s)'), $this->file));
260
        }
261
262
        return $size;
263
    }
264
265
    /**
266
     * Clears the stat cache for the given file
267
     *
268
     * @return FileHandler
269
     */
270
    public function clearCache()
271
    {
272
        clearstatcache(true, $this->file);
273
274
        return $this;
275
    }
276
277
    /**
278
     * Deletes a file
279
     *
280
     * @return FileHandler
281
     * @throws FileException
282
     */
283
    public function delete()
284
    {
285
        if (@unlink($this->file) === false) {
286
            throw new FileException(sprintf(__('No es posible eliminar el archivo (%s)'), $this->file));
287
        }
288
289
        return $this;
290
    }
291
292
    /**
293
     * Returns the content type in MIME format
294
     *
295
     * @return string
296
     * @throws FileException
297
     */
298
    public function getFileType(): string
299
    {
300
        $this->checkIsReadable();
301
302
        return mime_content_type($this->file);
303
    }
304
305
    /**
306
     * Checks if the file is readable
307
     *
308
     * @throws FileException
309
     * @return FileHandler
310
     */
311
    public function checkIsReadable()
312
    {
313
        if (!is_readable($this->file)) {
314
            throw new FileException(sprintf(__('No es posible leer el archivo (%s)'), $this->file));
315
        }
316
317
        return $this;
318
    }
319
320
    /**
321
     * @return int
322
     * @throws FileException
323
     */
324
    public function getFileTime(): int
325
    {
326
        $this->checkIsReadable();
327
328
        return filemtime($this->file) ?: 0;
329
    }
330
}