Completed
Pull Request — master (#366)
by Beñat
04:52
created

ElasticsearchUserView   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 39
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A userOfId() 0 10 2
A save() 0 9 1
A normalizeElasticsearchData() 0 4 1
1
<?php
2
3
/*
4
 * This file is part of the Kreta package.
5
 *
6
 * (c) Beñat Espiña <[email protected]>
7
 * (c) Gorka Laucirica <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
declare(strict_types=1);
14
15
namespace Kreta\Notifier\Infrastructure\Domain\ReadModel\Inbox;
16
17
use Elasticsearch\Client;
18
use Kreta\Notifier\Domain\Model\Inbox\UserId;
19
use Kreta\Notifier\Domain\ReadModel\Inbox\User;
20
use Kreta\Notifier\Domain\ReadModel\Inbox\UserView;
21
22
final class ElasticsearchUserView implements UserView
23
{
24
    private $elasticsearch;
25
    private $index;
26
    private $type;
27
28
    public function __construct(Client $elasticsearch, string $index, string $type)
29
    {
30
        $this->elasticsearch = $elasticsearch;
31
        $this->index = $index;
32
        $this->type = $type;
33
    }
34
35
    public function userOfId(UserId $userId) : ?User
36
    {
37
        $userData = $this->elasticsearch->get([
38
            'index' => $this->index,
39
            'type'  => $this->type,
40
            'id'    => $userId->id(),
41
        ]);
42
43
        return empty($userData) ? null : User::fromArray($this->normalizeElasticsearchData($userData));
44
    }
45
46
    public function save(User $user) : void
47
    {
48
        $this->elasticsearch->index([
49
            'index' => $this->index,
50
            'type'  => $this->type,
51
            'id'    => $user->id,
52
            'body'  => [],
53
        ]);
54
    }
55
56
    private function normalizeElasticsearchData(array $elasticsearchData) : array
57
    {
58
        return array_merge(['id' => $elasticsearchData['_id']], $elasticsearchData['_source']);
59
    }
60
}
61