|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of the eZ Publish Kernel package. |
|
5
|
|
|
* |
|
6
|
|
|
* @copyright Copyright (C) eZ Systems AS. All rights reserved. |
|
7
|
|
|
* @license For full copyright and license information view LICENSE file distributed with this source code. |
|
8
|
|
|
*/ |
|
9
|
|
|
namespace eZ\Bundle\EzPublishCoreBundle\Imagine\PlaceholderProvider; |
|
10
|
|
|
|
|
11
|
|
|
use eZ\Bundle\EzPublishCoreBundle\Imagine\PlaceholderProvider; |
|
12
|
|
|
use eZ\Publish\Core\FieldType\Image\Value as ImageValue; |
|
13
|
|
|
use RuntimeException; |
|
14
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Remote placeholder provider e.g. http://placekitten.com. |
|
18
|
|
|
*/ |
|
19
|
|
|
class RemoteProvider implements PlaceholderProvider |
|
20
|
|
|
{ |
|
21
|
|
|
/** |
|
22
|
|
|
* {@inheritdoc} |
|
23
|
|
|
*/ |
|
24
|
|
|
public function getPlaceholder(ImageValue $value, array $options = []): string |
|
25
|
|
|
{ |
|
26
|
|
|
$options = $this->resolveOptions($options); |
|
27
|
|
|
|
|
28
|
|
|
$path = $this->getTemporaryPath(); |
|
29
|
|
|
$placeholderUrl = $this->getPlaceholderUrl($options['url_pattern'], $value); |
|
30
|
|
|
|
|
31
|
|
|
try { |
|
32
|
|
|
$handler = curl_init(); |
|
33
|
|
|
|
|
34
|
|
|
curl_setopt_array($handler, [ |
|
35
|
|
|
CURLOPT_URL => $placeholderUrl, |
|
36
|
|
|
CURLOPT_FILE => fopen($path, 'wb'), |
|
37
|
|
|
CURLOPT_TIMEOUT => $options['timeout'], |
|
38
|
|
|
CURLOPT_FAILONERROR => true, |
|
39
|
|
|
]); |
|
40
|
|
|
|
|
41
|
|
|
if (curl_exec($handler) === false) { |
|
42
|
|
|
throw new RuntimeException("Unable to download placeholder for {$value->id} ($placeholderUrl): " . curl_error($handler)); |
|
43
|
|
|
} |
|
44
|
|
|
} finally { |
|
45
|
|
|
curl_close($handler); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return $path; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
View Code Duplication |
private function getPlaceholderUrl(string $urlPattern, ImageValue $value): string |
|
52
|
|
|
{ |
|
53
|
|
|
return strtr($urlPattern, [ |
|
54
|
|
|
'%id%' => $value->id, |
|
55
|
|
|
'%width%' => $value->width, |
|
56
|
|
|
'%height%' => $value->height, |
|
57
|
|
|
]); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
private function getTemporaryPath(): string |
|
61
|
|
|
{ |
|
62
|
|
|
return stream_get_meta_data(tmpfile())['uri']; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
private function resolveOptions(array $options): array |
|
66
|
|
|
{ |
|
67
|
|
|
$resolver = new OptionsResolver(); |
|
68
|
|
|
$resolver->setDefaults([ |
|
69
|
|
|
'url_pattern' => '', |
|
70
|
|
|
'timeout' => 5, |
|
71
|
|
|
]); |
|
72
|
|
|
$resolver->setAllowedTypes('url_pattern', 'string'); |
|
73
|
|
|
$resolver->setAllowedTypes('timeout', 'int'); |
|
74
|
|
|
|
|
75
|
|
|
return $resolver->resolve($options); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|