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