Landmark::detect()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 12
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 21
rs 9.8666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AhmadMayahi\Vision\Detectors;
6
7
use AhmadMayahi\Vision\Contracts\Detectable;
8
use AhmadMayahi\Vision\Data\Landmark as LandmarkData;
9
use AhmadMayahi\Vision\Data\Location as LocationData;
10
use AhmadMayahi\Vision\Support\AbstractDetector;
11
use AhmadMayahi\Vision\Traits\Arrayable;
12
use AhmadMayahi\Vision\Traits\Jsonable;
13
use Generator;
14
use Google\Cloud\Vision\V1\EntityAnnotation;
15
use Google\Cloud\Vision\V1\LocationInfo;
16
use Google\Protobuf\Internal\RepeatedField;
17
18
/**
19
 * @see https://cloud.google.com/vision/docs/detecting-landmarks
20
 */
21
class Landmark extends AbstractDetector implements Detectable
22
{
23
    use Arrayable;
24
    use Jsonable;
25
26
    public function getOriginalResponse(): RepeatedField
27
    {
28
        $response = $this
29
            ->imageAnnotatorClient
30
            ->landmarkDetection($this->file->toVisionFile());
31
32
        return $response->getLandmarkAnnotations();
33
    }
34
35
    public function detect(): ?Generator
36
    {
37
        $response = $this->getOriginalResponse();
38
39
        if (0 === $response->count()) {
40
            return null;
41
        }
42
43
        /** @var EntityAnnotation $entity */
44
        foreach ($response as $entity) {
45
            yield new LandmarkData(
46
                name: $entity->getDescription(),
47
                locations: array_map(function (LocationInfo $location) {
48
                    $info = $location->getLatLng();
49
50
                    if (is_null($info)) {
51
                        return null;
52
                    }
53
54
                    return new LocationData($info->getLatitude(), $info->getLongitude());
55
                }, iterator_to_array($entity->getLocations()->getIterator()))
56
            );
57
        }
58
    }
59
}
60