Test Failed
Pull Request — master (#12)
by
unknown
02:46
created

ProtocolTool   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 15
c 1
b 0
f 1
dl 0
loc 56
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 7 2
A init() 0 9 2
A decode() 0 7 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Seasx\SeasLogger\Kafka;
5
6
use Exception;
7
use Seasx\SeasLogger\Exceptions\NotSupportedException;
8
9
class ProtocolTool
10
{
11
    /**
12
     * protocol request code
13
     */
14
    public const PRODUCE_REQUEST = 0;
15
    public const METADATA_REQUEST = 3;
16
17
    /**
18
     * @var Protocol[]
19
     */
20
    protected static $objects = [];
21
22
    /**
23
     * @param string $version
24
     */
25
    public static function init(string $version): void
26
    {
27
        $class = [
28
            Protocol::PRODUCE_REQUEST => Produce::class,
29
            Protocol::METADATA_REQUEST => Metadata::class,
30
        ];
31
32
        foreach ($class as $key => $className) {
33
            self::$objects[$key] = new $className($version);
34
        }
35
    }
36
37
    /**
38
     * @param int $key
39
     * @param array $payloads
40
     * @return string
41
     * @throws Exception
42
     */
43
    public static function encode(int $key, array $payloads): string
44
    {
45
        if (!isset(self::$objects[$key])) {
46
            throw new NotSupportedException('Not support api key, key:' . $key);
47
        }
48
49
        return self::$objects[$key]->encode($payloads);
50
    }
51
52
    /**
53
     * @param int $key
54
     * @param string $data
55
     * @return array
56
     * @throws Exception
57
     */
58
    public static function decode(int $key, string $data): array
59
    {
60
        if (!isset(self::$objects[$key])) {
61
            throw new NotSupportedException('Not support api key, key:' . $key);
62
        }
63
64
        return self::$objects[$key]->decode($data);
65
    }
66
}
67