|
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
|
|
|
|