Clustered::leaving()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * Clustered resources
4
 * User: moyo
5
 * Date: 2018/7/25
6
 * Time: 11:03 AM
7
 */
8
9
namespace Carno\HRPC\Client;
10
11
use Carno\Cluster\Classify\Scenes;
12
use Carno\Cluster\Resources;
13
use Carno\HRPC\Client\Chips\Modifier;
14
use Carno\HRPC\Client\Chips\Options;
15
use Carno\HRPC\Client\Exception\EndpointsNotFoundException;
16
use Carno\HTTP\Client;
17
use Carno\RPC\Contracts\Client\Cluster;
18
19
class Clustered implements Cluster
20
{
21
    use Options;
22
    use Modifier;
23
24
    /**
25
     * @var Resources
26
     */
27
    private $resources = null;
28
29
    /**
30
     * @var Endpoints[]
31
     */
32
    private $targets = [];
33
34
    /**
35
     * @var array
36
     */
37
    private $tags = [];
38
39
    /**
40
     * Clustered constructor.
41
     * @param Resources $resources
42
     * @param string ...$tags
43
     */
44
    public function __construct(Resources $resources, string ...$tags)
45
    {
46
        $this->resources = $resources;
47
        $this->tags = $tags;
48
    }
49
50
    /**
51
     * @return string[]
52
     */
53
    public function tags() : array
54
    {
55
        return $this->tags;
56
    }
57
58
    /**
59
     * @param string $server
60
     */
61
    public function joining(string $server) : void
62
    {
63
        $cluster =
64
            $this->targets[$server] ??
65
            $this->targets[$server] = $this->modifying(new Endpoints($server, $this->tags(), $this->options($server)))
66
        ;
67
68
        $this->resources->initialize(Scenes::SERVICE, '', $server, $cluster);
69
    }
70
71
    /**
72
     * @param string $server
73
     */
74
    public function leaving(string $server) : void
75
    {
76
        $this->resources->forget('', $server);
77
    }
78
79
    /**
80
     * @param string $server
81
     * @param string ...$tags
82
     * @return Client
83
     */
84
    public function picking(string $server, string ...$tags) : object
85
    {
86
        if (is_null($endpoints = $this->targets[$server] ?? null)) {
87
            throw new EndpointsNotFoundException();
88
        } else {
89
            return $endpoints->select(...$tags);
90
        }
91
    }
92
}
93