ImaggaService   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 29
c 0
b 0
f 0
dl 0
loc 62
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A tagImage() 0 31 5
A __construct() 0 19 1
1
<?php
2
3
namespace App\Service;
4
5
use App\Entity\Image;
6
use Doctrine\ORM\EntityManagerInterface;
7
use ErrorException;
8
use GuzzleHttp\Client;
9
use GuzzleHttp\HandlerStack;
10
use Spatie\GuzzleRateLimiterMiddleware\RateLimiterMiddleware;
11
12
class ImaggaService implements ImageTaggingServiceInterface
13
{
14
    /** @var Client */
15
    private $guzzle;
16
17
    /** @var EntityManagerInterface */
18
    private $entityManager;
19
20
    public function __construct(
21
        string $imaggaApiKey,
22
        string $imaggaApiSecret,
23
        string $baseUri,
24
        EntityManagerInterface $entityManager)
25
    {
26
        $this->entityManager = $entityManager;
27
28
        $stack = HandlerStack::create();
29
        // TODO: Parameterise rate limit
30
        $stack->push(RateLimiterMiddleware::perSecond(1));
31
32
        $this->guzzle = new Client([
33
            'handler' => $stack,
34
            // TODO: Parameterise URI
35
            'base_uri' => $baseUri,
36
            'auth' => [
37
                $imaggaApiKey,
38
                $imaggaApiSecret
39
            ]
40
        ]);
41
    }
42
43
    public function tagImage(Image $image, bool $overwriteExisting = false): bool
44
    {
45
        if ($overwriteExisting === false && $image->getAutoTagsCount() > 0) {
46
            return false;
47
        }
48
49
        $response = $this->guzzle->request('GET', '/v2/tags', [
50
            'query' => [
51
                'image_url' => $image->getMediumImageUri(),
52
                // TODO: Find a better way of faking this in the dev environment
53
                // Maybe just always tag the images with some test tags?
54
                // 'image_url' => 'https://omm.gothick.org.uk/media/cache/srcset_576/uploads/images/20210328-mg-9921-terry-house-6067172c952d1544478055.jpg',
55
                'threshold' => 15.0
56
            ]
57
        ]);
58
59
        $content = (string) $response->getBody();
60
        $imagga_result = json_decode($content);
61
62
        if ($imagga_result->status->type != 'success') {
63
            throw new ErrorException("Error returned from imagga: " . $imagga_result->status->text);
64
        }
65
66
        $tags = [];
67
        foreach($imagga_result->result->tags as $tag) {
68
            $tags[] = $tag->tag->en;
69
        }
70
        $image->setAutoTags($tags);
71
        $this->entityManager->persist($image);
72
        $this->entityManager->flush(); // Calling the API's a lot more overhead; we might as well flush on every image.
73
        return true;
74
    }
75
}
76