TinyPngAssetListener   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 16
c 1
b 0
f 0
dl 0
loc 39
rs 10
ccs 9
cts 12
cp 0.75

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 5 1
A onImageSave() 0 16 3
1
<?php
2
3
namespace TinyPngBundle\EventListener;
4
5
use Pimcore\Event\AssetEvents;
6
use Pimcore\Event\Model\AssetEvent;
7
use Pimcore\Log\ApplicationLogger;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
use TinyPngBundle\Helper\AssetHelper;
10
use TinyPngBundle\Service\TinyPngService;
11
12
/**
13
 * Class TinyPngAssetListener
14
 * @package TinyPngBundle\EventListener
15
 */
16
class TinyPngAssetListener implements EventSubscriberInterface
17
{
18
19
    private $mimeTypes = [
20
        'image/jpeg',
21
        'image/png'
22
    ];
23
24
    /**
25
     * @return array
26
     */
27 1
    public static function getSubscribedEvents()
28
    {
29
        return [
30 1
            AssetEvents::POST_ADD => ['onImageSave'],
31 1
            AssetEvents::POST_UPDATE => ['onImageSave']
32
        ];
33
    }
34
35
    /**
36
     * @param AssetEvent $event
37
     * @return bool
38
     */
39 2
    public function onImageSave(AssetEvent $event) : bool
40
    {
41 2
        if (!in_array($event->getAsset()->getMimetype(), $this->mimeTypes)) {
42 1
            return false;
43
        }
44
45
        try {
46 1
            (new TinyPngService())->minimize($event->getAsset());
47 1
        } catch (\Exception $e) {
48 1
            (ApplicationLogger::getInstance())->error($e->getMessage(), [
49
                'relatedObject' => $event->getAsset(),
50
                'component' => 'TinyPNG'
51
            ]);
52
        }
53
54
        return true;
55
    }
56
}
57