Passed
Branch feature/refactoring (13cbf0)
by Alexey
03:46
created

LazyStream   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 76.47%

Importance

Changes 0
Metric Value
wmc 8
eloc 12
c 0
b 0
f 0
dl 0
loc 59
ccs 13
cts 17
cp 0.7647
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A replaceFilename() 0 3 1
A createStream() 0 9 4
A __construct() 0 4 1
A setFilename() 0 3 1
A getFilename() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nelexa\GPlay\Util;
6
7
use GuzzleHttp\Psr7\StreamDecoratorTrait;
8
use Psr\Http\Message\StreamInterface;
9
use function GuzzleHttp\Psr7\stream_for;
10
use function GuzzleHttp\Psr7\try_fopen;
11
12
/**
13
 * Lazily reads or writes to a file that is opened only after an IO operation
14
 * take place on the stream.
15
 *
16
 * @internal
17
 */
18
final class LazyStream implements StreamInterface
19
{
20
    use StreamDecoratorTrait;
21
22
    /** @var string File to open */
23
    private $filename;
24
25
    /** @var string $mode */
26
    private $mode;
27
28
    /**
29
     * @param string $filename File to lazily open
30
     * @param string $mode     fopen mode to use when opening the stream
31
     */
32 4
    public function __construct(string $filename, string $mode)
33
    {
34 4
        $this->filename = $filename;
35 4
        $this->mode = $mode;
36 4
    }
37
38
    /**
39
     * @param string $from
40
     * @param string $to
41
     */
42 2
    public function replaceFilename(string $from, string $to): void
43
    {
44 2
        $this->filename = str_replace($from, $to, $this->filename);
45 2
    }
46
47
    /**
48
     * @return string
49
     */
50 3
    public function getFilename(): string
51
    {
52 3
        return $this->filename;
53
    }
54
55
    /**
56
     * @param string $filename
57
     */
58
    public function setFilename(string $filename): void
59
    {
60
        $this->filename = $filename;
61
    }
62
63
    /**
64
     * Creates the underlying stream lazily when required.
65
     *
66
     * @return StreamInterface
67
     */
68 4
    protected function createStream()
69
    {
70 4
        $dir = \dirname($this->filename);
71
72 4
        if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
73
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir));
74
        }
75
76 4
        return stream_for(try_fopen($this->filename, $this->mode));
77
    }
78
}
79