-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResourceFactory.php
More file actions
259 lines (229 loc) 路 8.04 KB
/
Copy pathResourceFactory.php
File metadata and controls
259 lines (229 loc) 路 8.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
<?php
declare(strict_types=1);
namespace SixtyEightPublishers\ImageStorage\Resource;
use Intervention\Image\Exception\ImageException;
use Intervention\Image\Image;
use Intervention\Image\ImageManager;
use League\Flysystem\FilesystemException as LeagueFilesystemException;
use League\Flysystem\FilesystemReader;
use League\Flysystem\UnableToReadFile;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
use SixtyEightPublishers\FileStorage\Exception\FileNotFoundException;
use SixtyEightPublishers\FileStorage\Exception\FilesystemException;
use SixtyEightPublishers\FileStorage\PathInfoInterface;
use SixtyEightPublishers\FileStorage\Resource\ResourceFactoryInterface;
use SixtyEightPublishers\FileStorage\Resource\ResourceInterface;
use SixtyEightPublishers\ImageStorage\Modifier\Facade\ModifierFacadeInterface;
use SixtyEightPublishers\ImageStorage\PathInfoInterface as ImagePathInfoInterface;
use SixtyEightPublishers\ImageStorage\Persistence\ImagePersisterInterface;
use function error_clear_last;
use function error_get_last;
use function fclose;
use function file_put_contents;
use function filter_var;
use function fopen;
use function fwrite;
use function get_debug_type;
use function implode;
use function is_file;
use function is_string;
use function parse_url;
use function sprintf;
use function stream_context_create;
use function sys_get_temp_dir;
use function tempnam;
final class ResourceFactory implements ResourceFactoryInterface
{
public function __construct(
private readonly FilesystemReader $filesystemReader,
private readonly ImageManager $imageManager,
private readonly ModifierFacadeInterface $modifierFacade,
) {}
/**
* @throws FileNotFoundException
* @throws LeagueFilesystemException
* @throws FilesystemException
*/
public function createResource(PathInfoInterface $pathInfo): ResourceInterface
{
if ($pathInfo instanceof ImagePathInfoInterface && null !== $pathInfo->getModifiers()) {
$sourcePathInfo = $pathInfo->withModifiers(null);
}
$path = isset($sourcePathInfo) ? $sourcePathInfo->getPath() : $pathInfo->getPath();
$filesystemPath = ImagePersisterInterface::FILESYSTEM_PREFIX_SOURCE . $path;
if (false === $this->filesystemReader->fileExists($filesystemPath)) {
throw new FileNotFoundException($path);
}
try {
$source = $this->filesystemReader->readStream($filesystemPath);
} catch (UnableToReadFile $e) {
throw new FilesystemException(sprintf(
'Unable to read file "%s".',
$path,
), 0, $e);
} catch (LeagueFilesystemException $e) {
throw new FilesystemException($e->getMessage(), 0, $e);
}
return $this->createTmpFileResource(
pathInfo: $pathInfo,
location: $path,
source: $source,
);
}
public function createResourceFromFile(PathInfoInterface $pathInfo, string $filename): ResourceInterface
{
if (!filter_var($filename, FILTER_VALIDATE_URL)) {
return new ImageResource(
pathInfo: $pathInfo,
image: $this->makeImage(
source: $filename,
location: $filename,
),
localFilename: $filename,
modifierFacade: $this->modifierFacade,
);
}
error_clear_last();
$headers = [
"Accept-language: en\r\n",
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n",
];
$parsedUrl = parse_url($filename) ?: [];
if (isset($parsedUrl['scheme'], $parsedUrl['host'])) {
$headers[] = sprintf(
"Referer: %s://%s\r\n",
$parsedUrl['scheme'],
$parsedUrl['host'],
);
}
$context = stream_context_create(
options: [
'http' => [
'method' => 'GET',
'protocol_version' => 1.1,
'follow_location' => true,
'header' => implode('', $headers),
],
],
);
$source = @fopen(
filename: $filename,
mode: 'rb',
context: $context,
);
if (false === $source) {
throw new FilesystemException(
message: sprintf(
'Can not read stream from url "%s". %s',
$filename,
error_get_last()['message'] ?? '',
),
);
}
return $this->createTmpFileResource(
pathInfo: $pathInfo,
location: $filename,
source: $source,
);
}
public function createResourceFromPsrStream(PathInfoInterface $pathInfo, StreamInterface $stream): ResourceInterface
{
if ($stream->isSeekable()) {
try {
$stream->rewind();
} catch (RuntimeException $e) {
# ignore
}
}
$uri = $stream->getMetadata('uri');
if (is_string($uri) && @is_file($uri)) {
return new ImageResource(
pathInfo: $pathInfo,
image: $this->makeImage(
source: $stream,
location: $uri,
),
localFilename: $uri,
modifierFacade: $this->modifierFacade,
);
}
return $this->createTmpFileResource(
pathInfo: $pathInfo,
location: get_debug_type($stream),
source: $stream,
);
}
/**
* @throws FilesystemException
*/
private function createTmpFileResource(PathInfoInterface $pathInfo, string $location, mixed $source): TmpFileImageResource
{
$tmpFilename = (string) tempnam(sys_get_temp_dir(), '68Publishers_ImageStorage');
if ($source instanceof StreamInterface) {
$tmpStream = @fopen($tmpFilename, 'wb');
if (false === $tmpStream) {
throw new FilesystemException(
message: sprintf(
'Unable to open tmp file "%s" for writing.',
$tmpFilename,
),
);
}
try {
while (!$source->eof()) {
$chunk = $source->read(8192);
if ('' === $chunk) {
break;
}
fwrite($tmpStream, $chunk);
}
} catch (RuntimeException $e) {
throw new FilesystemException(
message: sprintf(
'Unable to write tmp file for "%s". %s',
$location,
$e->getMessage(),
),
previous: $e,
);
} finally {
fclose($tmpStream);
}
} elseif (false === file_put_contents($tmpFilename, $source)) {
throw new FilesystemException(
message: sprintf(
'Unable to write tmp file for "%s".',
$location,
),
);
}
return new TmpFileImageResource(
pathInfo: $pathInfo,
image: $this->makeImage(
source: $tmpFilename,
location: $location,
),
modifierFacade: $this->modifierFacade,
tmpFile: new TmpFile($tmpFilename),
);
}
/**
* @throws FilesystemException
*/
private function makeImage(mixed $source, string $location): Image
{
try {
return $this->imageManager->make($source);
} catch (ImageException $e) {
throw new FilesystemException(
message: sprintf(
'Unable to create image "%s". %s',
$location,
$e->getMessage(),
),
previous: $e,
);
}
}
}