forked from statamic/cms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageGeneratorTest.php
More file actions
460 lines (361 loc) · 17.4 KB
/
ImageGeneratorTest.php
File metadata and controls
460 lines (361 loc) · 17.4 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
<?php
namespace Tests\Imaging;
use Facades\Statamic\Imaging\ImageValidator;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Psr7\Response;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Local\LocalFilesystemAdapter;
use League\Flysystem\UnableToReadFile;
use League\Glide\Manipulators\Watermark;
use League\Glide\Server;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Events\GlideImageGenerated;
use Statamic\Exceptions\InvalidRemoteUrlException;
use Statamic\Facades\AssetContainer;
use Statamic\Facades\File;
use Statamic\Facades\Glide;
use Statamic\Imaging\GuzzleAdapter;
use Statamic\Imaging\ImageGenerator;
use Statamic\Imaging\RemoteUrlValidator;
use Statamic\Support\Str;
use Tests\PreventSavingStacheItemsToDisk;
use Tests\TestCase;
class ImageGeneratorTest extends TestCase
{
use PreventSavingStacheItemsToDisk;
public function setUp(): void
{
parent::setUp();
$this->clearGlideCache();
$this->app->bind(RemoteUrlValidator::class, function () {
return new RemoteUrlValidator(function ($host) {
return match ($host) {
'example.com' => [['ip' => '93.184.216.34']],
'internal.test' => [['ip' => '127.0.0.1']],
default => [],
};
});
});
}
#[Test]
public function it_generates_an_image_by_asset()
{
Event::fake();
$manifestCacheKey = 'asset::test_container::foo/hoff.jpg';
$manipulationCacheKey = 'asset::test_container::foo/hoff.jpg::4dbc41d8e3ba1ccd302641e509b48768';
$this->assertNull(Glide::cacheStore()->get($manifestCacheKey));
$this->assertNull(Glide::cacheStore()->get($manipulationCacheKey));
Storage::fake('test');
$file = UploadedFile::fake()->image('foo/hoff.jpg', 30, 60);
Storage::disk('test')->putFileAs('foo', $file, 'hoff.jpg');
$container = tap(AssetContainer::make('test_container')->disk('test'))->save();
$asset = tap($container->makeAsset('foo/hoff.jpg'))->save();
$this->assertCount(0, $this->generatedImagePaths());
ImageValidator::shouldReceive('isValidImage')
->andReturnTrue()
->once(); // Only one manipulation should happen because of cache.
// Generate the image twice to make sure it's cached.
foreach (range(1, 2) as $i) {
$path = $this->makeGenerator()->generateByAsset(
$asset,
$userParams = ['w' => 100, 'h' => 100]
);
}
// Since we can't really mock the server, we'll generate the md5 hash the same
// way it does. It will also include the fit parameter based on the asset's
// focal point since it does it automatically via our "auto_crop" setting.
$actualParams = array_merge($userParams, ['fit' => 'crop-50-50']);
$md5 = $this->getGlideMd5($asset->basename(), $actualParams);
$expectedCacheManifest = [$manipulationCacheKey];
$expectedPathPrefix = 'containers/test_container';
$expectedPath = "{$expectedPathPrefix}/foo/hoff.jpg/{$md5}/hoff.jpg";
$this->assertEquals($manifestCacheKey, ImageGenerator::assetCacheManifestKey($asset));
$this->assertEquals($expectedPathPrefix, ImageGenerator::assetCachePathPrefix($asset));
$this->assertEquals($expectedPath, $path);
$this->assertCount(1, $paths = $this->generatedImagePaths());
$this->assertContains($expectedPath, $paths);
$this->assertEquals($expectedCacheManifest, Glide::cacheStore()->get($manifestCacheKey));
$this->assertEquals($expectedPath, Glide::cacheStore()->get($manipulationCacheKey));
Event::assertDispatchedTimes(GlideImageGenerated::class, 1);
}
#[Test]
public function it_throws_unable_to_read_file_when_asset_is_not_a_valid_image()
{
Storage::fake('test');
$file = UploadedFile::fake()->create('foo/hoff.jpg', 100);
Storage::disk('test')->putFileAs('foo', $file, 'hoff.jpg');
$container = tap(AssetContainer::make('test_container')->disk('test'))->save();
$asset = tap($container->makeAsset('foo/hoff.jpg'))->save();
ImageValidator::shouldReceive('isValidImage')->andReturnFalse();
$this->expectException(UnableToReadFile::class);
$this->makeGenerator()->generateByAsset($asset, ['w' => 100]);
}
#[Test]
public function it_generates_cache_manifest_for_multiple_asset_manipulations()
{
Event::fake();
$manifestCacheKey = 'asset::test_container::foo/hoff.jpg';
$this->assertNull(Glide::cacheStore()->get($manifestCacheKey));
Storage::fake('test');
$file = UploadedFile::fake()->image('foo/hoff.jpg', 30, 60);
Storage::disk('test')->putFileAs('foo', $file, 'hoff.jpg');
$container = tap(AssetContainer::make('test_container')->disk('test'))->save();
$asset = tap($container->makeAsset('foo/hoff.jpg'))->save();
ImageValidator::shouldReceive('isValidImage')
->andReturnTrue()
->times(2); // Two manipulations should get cached.
// Generate the image twice to make sure it's cached.
foreach (range(1, 2) as $i) {
$this->makeGenerator()->generateByAsset(
$asset,
['w' => 100, 'h' => $i] // Ensure unique params so that two manipulations get cached.
);
}
Event::assertDispatchedTimes(GlideImageGenerated::class, 2);
$this->assertCount(2, $manifest = Glide::cacheStore()->get($manifestCacheKey));
$this->assertCount(2, $this->generatedImagePaths());
foreach ($manifest as $cacheKey) {
$this->assertTrue(Str::startsWith($cacheKey, 'asset::test_container::foo/hoff.jpg::'));
}
}
#[Test]
public function it_generates_an_image_by_local_path()
{
Event::fake();
$cacheKey = 'path::testimages/foo/hoff.jpg::4dbc41d8e3ba1ccd302641e509b48768';
$this->assertNull(Glide::cacheStore()->get($cacheKey));
$this->assertCount(0, $this->generatedImagePaths());
// Path relative to the "public" directory.
$imagePath = 'testimages/foo/hoff.jpg';
$image = UploadedFile::fake()->image('', 30, 60);
$contents = file_get_contents($image->getPathname());
File::put(public_path($imagePath), $contents);
ImageValidator::shouldReceive('isValidImage')
->andReturnTrue()
->once(); // Only one manipulation should happen because of cache.
// Generate the image twice to make sure it's cached.
foreach (range(1, 2) as $i) {
$path = $this->makeGenerator()->generateByPath(
$imagePath,
$userParams = ['w' => 100, 'h' => 100]
);
}
// Since we can't really mock the server, we'll generate the md5 hash the same
// way it does. It will not include the fit parameter since it's not an asset.
$md5 = $this->getGlideMd5($imagePath, $userParams);
$expectedPath = "paths/testimages/foo/hoff.jpg/{$md5}/hoff.jpg";
$this->assertEquals($expectedPath, $path);
$this->assertCount(1, $paths = $this->generatedImagePaths());
$this->assertContains($expectedPath, $paths);
$this->assertEquals($expectedPath, Glide::cacheStore()->get($cacheKey));
Event::assertDispatchedTimes(GlideImageGenerated::class, 1);
}
#[Test]
public function it_generates_an_image_by_external_url()
{
Event::fake();
$cacheKey = 'url::https://example.com/foo/hoff.jpg::4dbc41d8e3ba1ccd302641e509b48768';
$this->assertNull(Glide::cacheStore()->get($cacheKey));
$this->assertCount(0, $this->generatedImagePaths());
$this->app->bind('statamic.imaging.guzzle', function () {
$file = UploadedFile::fake()->image('', 30, 60);
$contents = file_get_contents($file->getPathname());
$response = new Response(200, [], $contents);
// Glide, Flysystem, or the Guzzle adapter will try to perform the requests
// at different points to check if the file exists or to get the content
// of it. Here we'll just mock the same response multiple times.
return new Client(['handler' => new MockHandler([
$response, $response, $response,
])]);
});
// Generate the image twice to make sure it's cached.
foreach (range(1, 2) as $i) {
$path = $this->makeGenerator()->generateByUrl(
'https://example.com/foo/hoff.jpg',
$userParams = ['w' => 100, 'h' => 100]
);
}
// Since we can't really mock the server, we'll generate the md5 hash the same
// way it does. It will not include the fit parameter since it's not an asset.
$md5 = $this->getGlideMd5('foo/hoff.jpg', $userParams);
// While writing this test I noticed that we don't include the domain in the
// cache path, so the same file path on two different domains will conflict.
// TODO: Fix this.
$expectedPath = "http/foo/hoff.jpg/{$md5}/hoff.jpg";
$this->assertEquals($expectedPath, $path);
$this->assertCount(1, $paths = $this->generatedImagePaths());
$this->assertContains($expectedPath, $paths);
$this->assertEquals($expectedPath, Glide::cacheStore()->get($cacheKey));
Event::assertDispatchedTimes(GlideImageGenerated::class, 1);
}
#[Test]
public function it_generates_an_image_by_external_url_with_query_string()
{
Event::fake();
$cacheKey = 'url::https://example.com/foo/hoff.jpg?query=david::4dbc41d8e3ba1ccd302641e509b48768';
$this->assertNull(Glide::cacheStore()->get($cacheKey));
$this->assertCount(0, $this->generatedImagePaths());
$this->app->bind('statamic.imaging.guzzle', function () {
$file = UploadedFile::fake()->image('', 30, 60);
$contents = file_get_contents($file->getPathname());
$response = new Response(200, [], $contents);
// Glide, Flysystem, or the Guzzle adapter will try to perform the requests
// at different points to check if the file exists or to get the content
// of it. Here we'll just mock the same response multiple times.
return new Client(['handler' => new MockHandler([
$response, $response, $response,
])]);
});
// Generate the image twice to make sure it's cached.
foreach (range(1, 2) as $i) {
$path = $this->makeGenerator()->generateByUrl(
'https://example.com/foo/hoff.jpg?query=david',
$userParams = ['w' => 100, 'h' => 100]
);
}
$qsHash = md5('query=david');
// Since we can't really mock the server, we'll generate the md5 hash the same
// way it does. It will not include the fit parameter since it's not an asset.
$md5 = $this->getGlideMd5("foo/hoff-{$qsHash}.jpg", $userParams);
// While writing this test I noticed that we don't include the domain in the
// cache path, so the same file path on two different domains will conflict.
// TODO: Fix this.
$expectedPath = "http/foo/hoff-{$qsHash}.jpg/{$md5}/hoff-{$qsHash}.jpg";
$this->assertEquals($expectedPath, $path);
$this->assertCount(1, $paths = $this->generatedImagePaths());
$this->assertContains($expectedPath, $paths);
$this->assertEquals($expectedPath, Glide::cacheStore()->get($cacheKey));
Event::assertDispatchedTimes(GlideImageGenerated::class, 1);
}
#[Test]
public function it_blocks_external_urls_that_target_non_public_ip_ranges()
{
$this->expectException(InvalidRemoteUrlException::class);
$this->expectExceptionMessage('Destination IP is not publicly routable.');
$this->makeGenerator()->generateByUrl('http://169.254.169.254/latest/meta-data/', ['w' => 100]);
}
#[Test]
public function it_blocks_watermark_urls_that_target_non_public_ip_ranges()
{
$this->expectException(InvalidRemoteUrlException::class);
$this->expectExceptionMessage('Destination IP is not publicly routable.');
$this->makeGenerator()->setParams(['mark' => 'http://127.0.0.1/watermark.png']);
}
#[Test]
public function the_watermark_disk_is_the_public_directory_by_default()
{
$generator = $this->makeGenerator();
$filesystem = $this->getWatermarkFilesystem($generator);
$this->assertLocalAdapter($adapter = $this->getAdapterFromFilesystem($filesystem));
$this->assertEquals(public_path().DIRECTORY_SEPARATOR, $this->getRootFromLocalAdapter($adapter));
}
#[Test]
public function the_watermark_disk_is_the_container_when_an_asset_is_provided()
{
// Make the asset to be used as the watermark.
Storage::fake('test');
$file = UploadedFile::fake()->image('foo/hoff.jpg', 30, 60);
Storage::disk('test')->putFileAs('foo', $file, 'hoff.jpg');
$container = tap(AssetContainer::make('test_container')->disk('test'))->save();
$asset = tap($container->makeAsset('foo/hoff.jpg'))->save();
$generator = $this->makeGenerator();
$generator->setParams(['mark' => $asset]);
$filesystem = $this->getWatermarkFilesystem($generator);
$this->assertSame($container->disk()->filesystem()->getDriver(), $filesystem);
$this->assertEquals(['mark' => 'foo/hoff.jpg'], $generator->getParams());
}
#[Test]
public function the_watermark_disk_is_the_container_when_an_asset_encoded_url_string_is_provided()
{
// Make the asset to be used as the watermark.
Storage::fake('test');
$file = UploadedFile::fake()->image('foo/hoff.jpg', 30, 60);
Storage::disk('test')->putFileAs('foo', $file, 'hoff.jpg');
$container = tap(AssetContainer::make('test_container')->disk('test'))->save();
$asset = tap($container->makeAsset('foo/hoff.jpg'))->save();
$generator = $this->makeGenerator();
$generator->setParams(['mark' => 'asset::'.base64_encode('test_container/foo/hoff.jpg')]);
$filesystem = $this->getWatermarkFilesystem($generator);
$this->assertSame($container->disk()->filesystem()->getDriver(), $filesystem);
$this->assertEquals(['mark' => 'foo/hoff.jpg'], $generator->getParams());
}
#[Test]
public function the_watermark_disk_is_a_local_adapter_when_a_path_is_provided()
{
$generator = $this->makeGenerator();
$generator->setParams(['mark' => 'foo/hoff.jpg']);
$filesystem = $this->getWatermarkFilesystem($generator);
$this->assertLocalAdapter($adapter = $this->getAdapterFromFilesystem($filesystem));
$this->assertEquals(public_path().DIRECTORY_SEPARATOR, $this->getRootFromLocalAdapter($adapter));
$this->assertEquals(['mark' => 'foo/hoff.jpg'], $generator->getParams());
}
#[Test]
#[DataProvider('guzzleWatermarkProvider')]
public function the_watermark_disk_is_a_guzzle_adapter_when_a_url_is_provided($protocol)
{
$generator = $this->makeGenerator();
$generator->setParams(['mark' => $protocol.'://example.com/foo/hoff.jpg']);
$filesystem = $this->getWatermarkFilesystem($generator);
$this->assertGuzzleAdapter($this->getAdapterFromFilesystem($filesystem));
$this->assertEquals(['mark' => 'foo/hoff.jpg'], $generator->getParams());
}
public static function guzzleWatermarkProvider()
{
return ['http' => ['http'], 'https' => ['https']];
}
private function getWatermarkFilesystem(ImageGenerator $generator)
{
$manipulators = $generator->getServer()->getApi()->getManipulators();
$watermark = collect($manipulators)->first(fn ($m) => $m instanceof Watermark);
return $watermark->getWatermarks();
}
private function makeGenerator()
{
return new ImageGenerator($this->app->make(Server::class));
}
private function clearGlideCache()
{
Glide::cacheStore()->flush();
File::delete($this->glideCachePath());
}
private function glideCachePath()
{
return 'storage/statamic/glide';
}
private function generatedImagePaths()
{
return File::getFilesRecursively($this->glideCachePath())
->map(fn ($path) => (string) Str::of($path)->after($this->glideCachePath().'/'))
->all();
}
private function getGlideMd5($basename, $params)
{
ksort($params);
return md5($basename.'?'.http_build_query($params));
}
private function assertLocalAdapter($adapter)
{
$this->assertInstanceOf(LocalFilesystemAdapter::class, $adapter);
}
private function assertGuzzleAdapter($adapter)
{
$this->assertInstanceOf(GuzzleAdapter::class, $adapter);
}
private function getRootFromLocalAdapter($adapter)
{
$reflection = new \ReflectionClass($adapter);
$property = $reflection->getProperty('prefixer');
$prefixer = $property->getValue($adapter);
return $prefixer->prefixPath('');
}
private function getAdapterFromFilesystem($filesystem)
{
$reflection = new \ReflectionClass($filesystem);
$property = $reflection->getProperty('adapter');
return $property->getValue($filesystem);
}
}