Passed
Pull Request — master (#48)
by Anatoly
52:04
created

FileStream::getFilename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 6
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Nekhay <[email protected]>
7
 * @copyright Copyright (c) 2018, Anatoly Nekhay
8
 * @license https://github.com/sunrise-php/http-message/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/http-message
10
 */
11
12
namespace Sunrise\Http\Message\Stream;
13
14
use Sunrise\Http\Message\Exception\InvalidArgumentException;
15
use Sunrise\Http\Message\Stream;
16
use Throwable;
17
18
use function fopen;
19
use function is_resource;
20
use function sprintf;
21
22
final class FileStream extends Stream
23
{
24
    /**
25
     * @throws InvalidArgumentException
26
     */
27 5
    public function __construct(string $filename, string $mode)
28
    {
29 5
        parent::__construct(self::openFile($filename, $mode));
30
    }
31
32
    public function getFilename(): string
33
    {
34
        /** @var string $filename */
35
        $filename = $this->getMetadata('uri');
36
37
        return $filename;
38
    }
39
40
    /**
41
     * @return resource
42
     *
43
     * @throws InvalidArgumentException
44
     */
45 5
    private static function openFile(string $filename, string $mode)
46
    {
47
        try {
48 5
            $resource = @fopen($filename, $mode);
49
        } catch (Throwable $e) {
50
            $resource = false;
51
        }
52
53 5
        if (!is_resource($resource)) {
54 1
            throw new InvalidArgumentException(sprintf(
55 1
                'Unable to open the file "%s" in the mode "%s"',
56 1
                $filename,
57 1
                $mode,
58 1
            ));
59
        }
60
61 4
        return $resource;
62
    }
63
}
64