Completed
Push — master ( f351fc...15d6c3 )
by Paweł
18s queued 11s
created

ImageConversionConsumer   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 115
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 13
dl 0
loc 115
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
B execute() 0 51 7
A markArticlesMediaAsUpdated() 0 8 2
A getImageAsResource() 0 23 4
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Core Bundle.
7
 *
8
 * Copyright 2017 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2017 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\Consumer;
18
19
use BadFunctionCallException;
20
use DateTime;
21
use function imagewebp;
22
use Doctrine\ORM\EntityManagerInterface;
23
use Exception;
24
use InvalidArgumentException;
25
use JMS\Serializer\Exception\RuntimeException;
26
use JMS\Serializer\SerializerInterface;
27
use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
28
use PhpAmqpLib\Message\AMQPMessage;
29
use Psr\Log\LoggerInterface;
30
use SWP\Bundle\ContentBundle\Manager\MediaManagerInterface;
31
use SWP\Bundle\ContentBundle\Model\FileInterface;
32
use SWP\Bundle\ContentBundle\Model\ImageRenditionInterface;
33
use SWP\Bundle\CoreBundle\Model\ImageInterface;
34
use SWP\Bundle\CoreBundle\Model\Tenant;
35
use SWP\Component\MultiTenancy\Context\TenantContextInterface;
36
use SWP\Component\MultiTenancy\Model\TenantInterface;
37
use SWP\Component\Storage\Repository\RepositoryInterface;
38
use Symfony\Component\Filesystem\Filesystem;
39
use Symfony\Component\HttpFoundation\File\UploadedFile;
40
41
class ImageConversionConsumer implements ConsumerInterface
42
{
43
    protected $serializer;
44
45
    protected $logger;
46
47
    protected $imageRenditionRepository;
48
49
    protected $mediaManager;
50
51
    protected $tenantContext;
52
53
    protected $entityManager;
54
55
    public function __construct(
56
        SerializerInterface $serializer,
57
        LoggerInterface $logger,
58
        RepositoryInterface $imageRenditionRepository,
59
        MediaManagerInterface $mediaManager,
60
        TenantContextInterface $tenantContext,
61
        EntityManagerInterface $entityManager
62
    ) {
63
        $this->serializer = $serializer;
64
        $this->logger = $logger;
65
        $this->imageRenditionRepository = $imageRenditionRepository;
66
        $this->mediaManager = $mediaManager;
67
        $this->tenantContext = $tenantContext;
68
        $this->entityManager = $entityManager;
69
    }
70
71
    public function execute(AMQPMessage $message): int
72
    {
73
        sleep(1); // wait for data to be flushed (really) in database
74
75
        try {
76
            ['image' => $image, 'tenantId' => $tenantId] = unserialize($message->body, [false]);
0 ignored issues
show
Bug introduced by
The variable $image seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
Bug introduced by
The variable $tenantId does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
77
            if (($tenant = $this->entityManager->find(Tenant::class, $tenantId)) instanceof TenantInterface) {
78
                $this->tenantContext->setTenant($tenant);
79
            }
80
81
            if (null === $image) {
0 ignored issues
show
Bug introduced by
The variable $image seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
82
                throw new InvalidArgumentException('Missing image data');
83
            }
84
        } catch (RuntimeException $e) {
85
            $this->logger->error('Message REJECTED: '.$e->getMessage(), ['exception' => $e->getTraceAsString()]);
86
87
            return ConsumerInterface::MSG_REJECT;
88
        }
89
90
        /** @var ImageInterface $image */
91
        $image = $this->entityManager->merge($image);
0 ignored issues
show
Bug introduced by
The variable $image seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
92
        $mediaId = $image->getAssetId();
93
        $tempLocation = rtrim(sys_get_temp_dir(), '/').DIRECTORY_SEPARATOR.sha1($mediaId);
94
95
        try {
96
            if (!function_exists('imagewebp')) {
97
                throw new BadFunctionCallException('"imagewebp" function is missing. Looks like GD was compiled without webp support');
98
            }
99
            imagewebp($this->getImageAsResource($image), $tempLocation);
100
            $uploadedFile = new UploadedFile($tempLocation, $mediaId, 'image/webp', strlen($tempLocation), null, true);
101
            $this->mediaManager->saveFile($uploadedFile, $mediaId);
102
103
            $this->logger->info(sprintf('File "%s" converted successfully to WEBP', $mediaId));
104
105
            $image->addVariant(ImageInterface::VARIANT_WEBP);
106
            $this->markArticlesMediaAsUpdated($image);
107
108
            $this->entityManager->flush();
109
        } catch (Exception $e) {
110
            $this->logger->error('File NOT converted '.$e->getMessage(), ['exception' => $e->getTraceAsString()]);
111
112
            return ConsumerInterface::MSG_REJECT;
113
        } finally {
114
            $filesystem = new Filesystem();
115
            if ($filesystem->exists($tempLocation)) {
116
                $filesystem->remove($tempLocation);
117
            }
118
        }
119
120
        return ConsumerInterface::MSG_ACK;
121
    }
122
123
    private function markArticlesMediaAsUpdated($image)
124
    {
125
        /** @var ImageRenditionInterface[] $articleMedia */
126
        $articleMedia = $this->imageRenditionRepository->findBy(['image' => $image]);
127
        foreach ($articleMedia as $media) {
128
            $media->getMedia()->getArticle()->setMediaUpdatedAt(new DateTime());
129
        }
130
    }
131
132
    private function getImageAsResource(FileInterface $asset)
133
    {
134
        $filesystem = new Filesystem();
135
        $tempLocation = rtrim(sys_get_temp_dir(), '/').DIRECTORY_SEPARATOR.sha1($asset->getAssetId());
136
        $filesystem->dumpFile($tempLocation, $this->mediaManager->getFile($asset));
137
138
        $resource = null;
139
        $size = getimagesize($tempLocation);
140
        switch ($size['mime']) {
141
            case 'image/jpeg':
142
                $resource = imagecreatefromjpeg($tempLocation); //jpeg file
143
                break;
144
            case 'image/gif':
145
                $resource = imagecreatefromgif($tempLocation); //gif file
146
                break;
147
            case 'image/png':
148
                $resource = imagecreatefrompng($tempLocation); //png file
149
                break;
150
        }
151
        $filesystem->remove($tempLocation);
152
153
        return $resource;
154
    }
155
}
156