Passed
Push — feature/initial-implementation ( f3915b...fbd338 )
by Fike
02:22
created

MappingClient::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AmaTeam\ElasticSearch\Client;
6
7
use AmaTeam\ElasticSearch\API\Client\MappingClientInterface;
8
use AmaTeam\ElasticSearch\API\Mapping\MappingInterface;
9
use AmaTeam\ElasticSearch\Mapping\Mapping;
10
use AmaTeam\ElasticSearch\Mapping\Type\RootType;
11
use Elasticsearch\Client;
12
use Elasticsearch\Common\Exceptions\Missing404Exception;
13
14
class MappingClient implements MappingClientInterface
15
{
16
    /**
17
     * @var Client
18
     */
19
    private $client;
20
21
    /**
22
     * @param Client $client
23
     */
24
    public function __construct(Client $client)
25
    {
26
        $this->client = $client;
27
    }
28
29
    public function apply(string $index, string $type, MappingInterface $mapping): void
30
    {
31
        $serialized = Mapping::asObject($mapping);
32
        unset($serialized->type);
33
        $parameters = [
34
            'index' => $index,
35
            'type' => $type,
36
            'body' => [$type => $serialized]
37
        ];
38
        $this
39
            ->client
40
            ->indices()
41
            ->putMapping($parameters);
42
    }
43
44
    public function get(string $index, string $type): ?MappingInterface
45
    {
46
        try {
47
            $data = $this
48
                ->client
49
                ->indices()
50
                ->getMapping(['index' => $index, 'type' => $type]);
51
            $mapping = $data[$index]['mappings'][$type];
52
            return Mapping::fromArray($mapping)->setType(RootType::ID);
53
        } catch (Missing404Exception $e) {
54
            return null;
55
        }
56
    }
57
}
58