/
ClickHouseClientTrait.php
92 lines (76 loc) · 2.64 KB
/
ClickHouseClientTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
namespace Borislav\Clickhouse\Traits;
use Borislav\Clickhouse\ClickHouseRepository;
use Borislav\Clickhouse\Client\Adapter\ClickHouseClientAdapter;
use Borislav\Clickhouse\Client\Adapter\Interfaces\ClickHouseClientAdapterInterface;
use Borislav\Clickhouse\Exception\ClickHouseNotImplementedException;
use Borislav\Clickhouse\Exception\ClickHouseReflectionException;
use Borislav\Clickhouse\Traits\Interfaces\ClickHouseClientTraitInterface;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Throwable;
trait ClickHouseClientTrait
{
private static ClickHouseClientAdapterInterface|null $clickhouse = null;
/**
* @return ClickHouseClientAdapterInterface
*
* @throws ClickHouseNotImplementedException
* @throws ClickHouseReflectionException
*/
public function clickhouse(): ClickHouseClientAdapterInterface
{
if (!$this instanceof ClickHouseClientTraitInterface) {
throw new ClickHouseNotImplementedException(
'cannot get ClickHouse client because the ClickHouseClientTraitInterface is not implemented.'
);
}
if (!is_null(self::$clickhouse)) return self::$clickhouse;
$reflectedClickHouseClientAdapter = new ReflectionClass(
ClickHouseClientAdapter::class
);
$clientMethod = null;
foreach( /** @var ReflectionMethod $method */
$reflectedClickHouseClientAdapter
->getMethods() as $method
) {
try {
if (!$method->hasReturnType()) continue;
if (is_string($name = $method->getReturnType()?->getName())) {
if (strcasecmp($name, ClickHouseClientAdapterInterface::class) === 0) {
$clientMethod = $method;
}
}
} catch (Throwable) {
continue;
}
}
if (is_null($clientMethod)) {
throw new ClickHouseReflectionException(
'unable to continue execution because the ClickHouse method, which provide a client was not found.'
);
}
$constructor = $reflectedClickHouseClientAdapter
->getConstructor();
if (is_null($constructor)) {
throw new ClickHouseReflectionException(
'unable to continue execution because cannot create instance of ClickHouseRepository. Internal error.'
);
}
$constructor->setAccessible(true);
$clientMethod->setAccessible(true);
try {
/** @var ClickHouseRepository $objectOfClickHouseRepository */
$objectOfClickHouseClientAdapter = $reflectedClickHouseClientAdapter
->newInstanceWithoutConstructor();
$constructor->invoke($objectOfClickHouseClientAdapter);
self::$clickhouse = $clientMethod->invoke($objectOfClickHouseClientAdapter);
return self::$clickhouse;
} catch (ReflectionException $e) {
throw new ClickHouseReflectionException(
$e->getMessage()
);
}
}
}