forked from sonata-project/SonataMediaBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFormatThumbnail.php
108 lines (94 loc) · 3.03 KB
/
FormatThumbnail.php
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
<?php
/*
* This file is part of the Sonata project.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\MediaBundle\Thumbnail;
use Sonata\MediaBundle\Model\MediaInterface;
use Sonata\MediaBundle\Provider\MediaProviderInterface;
class FormatThumbnail implements ThumbnailInterface
{
private $defaultFormat;
/**
* @param string $defaultFormat
*/
public function __construct($defaultFormat)
{
$this->defaultFormat = $defaultFormat;
}
/**
* {@inheritdoc}
*/
public function generatePublicUrl(MediaProviderInterface $provider, MediaInterface $media, $format)
{
if ($format == 'reference') {
$path = $provider->getReferenceImage($media);
} else {
$path = sprintf('%s/thumb_%s_%s.%s', $provider->generatePath($media), $media->getId(), $format, $this->getExtension($media));
}
return $path;
}
/**
* {@inheritdoc}
*/
public function generatePrivateUrl(MediaProviderInterface $provider, MediaInterface $media, $format)
{
return sprintf('%s/thumb_%s_%s.%s',
$provider->generatePath($media),
$media->getId(),
$format,
$this->getExtension($media)
);
}
/**
* {@inheritdoc}
*/
public function generate(MediaProviderInterface $provider, MediaInterface $media)
{
if (!$provider->requireThumbnails()) {
return;
}
$referenceFile = $provider->getReferenceFile($media);
foreach ($provider->getFormats() as $format => $settings) {
if (substr($format, 0, strlen($media->getContext())) == $media->getContext() || $format === 'admin') {
$provider->getResizer()->resize(
$media,
$referenceFile,
$provider->getFilesystem()->get($provider->generatePrivateUrl($media, $format), true),
$this->getExtension($media),
$settings
);
}
}
}
/**
* {@inheritdoc}
*/
public function delete(MediaProviderInterface $provider, MediaInterface $media)
{
// delete the differents formats
foreach ($provider->getFormats() as $format => $definition) {
$path = $provider->generatePrivateUrl($media, $format);
if ($path && $provider->getFilesystem()->has($path)) {
$provider->getFilesystem()->delete($path);
}
}
}
/**
* @param \Sonata\MediaBundle\Model\MediaInterface $media
*
* @return string the file extension for the $media, or the $defaultExtension if not available
*/
protected function getExtension(MediaInterface $media)
{
$ext = $media->getExtension();
if (!is_string($ext) || strlen($ext) < 3) {
$ext = $this->defaultFormat;
}
return $ext;
}
}