Completed
Push — master ( f9ed8e...69cc3d )
by Matt
04:47
created

GoogleImageTaggingService   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
dl 0
loc 45
rs 10
c 1
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
A tagImage() 0 22 4
1
<?php
2
3
namespace App\Service;
4
5
use App\Entity\Image;
6
use Doctrine\ORM\EntityManagerInterface;
7
use Google\Cloud\Vision\V1\Feature;
8
use Google\Cloud\Vision\V1\Feature\Type;
9
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
10
11
class GoogleImageTaggingService implements ImageTaggingServiceInterface
12
{
13
    /** @var EntityManagerInterface */
14
    private $entityManager;
15
16
    /** @var ImageAnnotatorClient */
17
    private $client;
18
19
    public function __construct(
20
        $apiKey,
0 ignored issues
show
Unused Code introduced by
The parameter $apiKey is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

20
        /** @scrutinizer ignore-unused */ $apiKey,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
21
        $projectId,
22
        $serviceAccountFile,
23
        EntityManagerInterface $entityManager
24
    )
25
    {
26
        //dd(file_get_contents($serviceAccountFile));
27
        $this->client = new ImageAnnotatorClient([
28
            'projectId' => $projectId,
29
            'credentials' => $serviceAccountFile
30
        ]);
31
        $this->entityManager = $entityManager;
32
    }
33
34
    public function tagImage(Image $image, bool $overwriteExisting = false): bool
35
    {
36
        if ($overwriteExisting === false && $image->getAutoTagsCount() > 0) {
37
            return false;
38
        }
39
40
        $feature = new Feature();
41
        $feature->setType(Type::LABEL_DETECTION);
42
        $feature->setMaxResults(15);
43
        $result = $this->client->annotateImage(
44
            $image->getMediumImageUri(),
45
            [$feature]
46
        );
47
48
        $tags = [];
49
        foreach ($result->getLabelAnnotations() as $annotation) {
50
            $tags[] = $annotation->getDescription();
51
        }
52
        $image->setAutoTags($tags);
53
        $this->entityManager->persist($image);
54
        $this->entityManager->flush(); // Calling the API's a lot more overhead; we might as well flush on every image.
55
        return true;
56
    }
57
}