TinyPngAssetListener::onImageSave()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.3332

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 16
rs 9.9666
ccs 6
cts 9
cp 0.6667
cc 3
nc 3
nop 1
crap 3.3332
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