1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace DigitalCz\DigiSign\Stream; |
6
|
|
|
|
7
|
|
|
use DigitalCz\DigiSign\Exception\RuntimeException; |
8
|
|
|
use InvalidArgumentException; |
9
|
|
|
|
10
|
|
|
final class FileStream |
11
|
|
|
{ |
12
|
|
|
/** @var resource */ |
13
|
|
|
private $handle; |
14
|
|
|
|
15
|
|
|
/** @var int|null */ |
16
|
|
|
private $size; |
17
|
|
|
|
18
|
|
|
/** @var string|null */ |
19
|
|
|
private $filename; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param resource $handle |
23
|
|
|
*/ |
24
|
|
|
public function __construct($handle, ?int $size = null, ?string $filename = null) |
25
|
|
|
{ |
26
|
|
|
if (!is_resource($handle)) { |
27
|
|
|
throw new InvalidArgumentException('Invalid $handle, resource is expected'); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$this->handle = $handle; |
31
|
|
|
$this->size = $size; |
32
|
|
|
$this->filename = $filename; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public static function open(string $path): self |
36
|
|
|
{ |
37
|
|
|
$handle = @fopen($path, 'rb+'); |
38
|
|
|
|
39
|
|
|
if ($handle === false) { |
40
|
|
|
throw new RuntimeException('Failed to open file ' . $path); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$size = @filesize($path); |
44
|
|
|
|
45
|
|
|
if ($size === false) { |
46
|
|
|
throw new RuntimeException('Failed to get size of ' . $path); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return new self($handle, $size, basename($path)); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param string $path Path to directory or file |
54
|
|
|
*/ |
55
|
|
|
public function save(string $path): void |
56
|
|
|
{ |
57
|
|
|
if (is_dir($path)) { |
58
|
|
|
$path .= DIRECTORY_SEPARATOR . $this->getFilename(); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$handle = fopen($path, 'wb+'); |
62
|
|
|
|
63
|
|
|
if ($handle === false) { |
64
|
|
|
throw new RuntimeException('Failed to open/create file ' . $path); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$bytes = stream_copy_to_stream($this->getHandle(), $handle); |
68
|
|
|
|
69
|
|
|
if ($bytes === false) { |
70
|
|
|
throw new RuntimeException('Failed to write into ' . $path); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @return resource |
76
|
|
|
*/ |
77
|
|
|
public function getHandle() |
78
|
|
|
{ |
79
|
|
|
return $this->handle; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
public function getSize(): ?int |
83
|
|
|
{ |
84
|
|
|
return $this->size; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
public function setFilename(?string $filename): void |
88
|
|
|
{ |
89
|
|
|
$this->filename = $filename; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
public function getFilename(): ?string |
93
|
|
|
{ |
94
|
|
|
return $this->filename; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|