This repository has been archived by the owner on Jun 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
MediaUploadSubscriber.php
68 lines (58 loc) · 1.81 KB
/
MediaUploadSubscriber.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
<?php
namespace FroshWebP\Subscriber;
use Enlight\Event\SubscriberInterface;
use Enlight_Event_EventArgs;
use FroshWebP\Services\WebpEncoderFactory;
use Shopware\Bundle\MediaBundle\MediaServiceInterface;
use Shopware\Models\Media\Media;
/**
* Class MediaUploadSubscriber
*/
class MediaUploadSubscriber implements SubscriberInterface
{
/**
* @var MediaServiceInterface
*/
private $mediaService;
/**
* @var WebpEncoderFactory
*/
private $encoderFactory;
/**
* MediaUploadSubscriber constructor.
*
* @param MediaServiceInterface $mediaService
* @param WebpEncoderFactory $encoderFactory
*/
public function __construct(MediaServiceInterface $mediaService, WebpEncoderFactory $encoderFactory)
{
$this->mediaService = $mediaService;
$this->encoderFactory = $encoderFactory;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'Shopware\Models\Media\Media::postPersist' => 'onFileUploaded',
];
}
/**
* @param Enlight_Event_EventArgs $args
*/
public function onFileUploaded(Enlight_Event_EventArgs $args)
{
$runnableEncoders = WebpEncoderFactory::onlyRunnable($this->encoderFactory->getEncoders());
if (($encoder = current($runnableEncoders)) !== false) {
/** @var \Shopware\Models\Media\Media $media */
$media = $args->get('entity');
$webpPath = str_replace($media->getExtension(), 'webp', $media->getPath());
$im = imagecreatefromstring($this->mediaService->read($media->getPath()));
imagepalettetotruecolor($im);
$content = $encoder->encode($im, 80);
imagedestroy($im);
$this->mediaService->write($webpPath, $content);
}
}
}