Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
memcachedconnectionconfigurator.php
1<?php
2
4
7
9{
10 protected array $config;
11 protected array $servers = [];
12
13 public function __construct(array $config)
14 {
15 if (!extension_loaded('memcached'))
16 {
17 throw new NotSupportedException('memcached extension is not loaded.');
18 }
19
20 $this->config = $config;
21
22 $this->addServers($this->getConfig());
23 }
24
26 {
27 $servers = $config['servers'] ?? [];
28
29 if (isset($config['host'], $config['port']))
30 {
31 array_unshift($servers, [
32 'host' => $config['host'],
33 'port' => $config['port'],
34 ]);
35 }
36
37 foreach ($servers as $server)
38 {
39 if (!isset($server['weight']) || $server['weight'] <= 0)
40 {
41 $server['weight'] = 1;
42 }
43
44 $this->servers[] = [
45 $server['host'] ?? 'localhost',
46 $server['port'] ?? '11211',
47 $server['weight']
48 ];
49 }
50
51 return $this;
52 }
53
54 public function getConfig(): array
55 {
56 return $this->config;
57 }
58
59 public function createConnection(): ?\Memcached
60 {
61 if (!$this->servers)
62 {
63 throw new NotSupportedException('Empty server list to memcache connection.');
64 }
65
66 $connectionTimeout = $this->getConfig()['connectionTimeout'] ?? 1;
67 $serializer = $this->getConfig()['serializer'] ?? \Memcached::SERIALIZER_PHP;
68
69 $connection = new \Memcached();
70 $connection->setOption(\Memcached::OPT_CONNECT_TIMEOUT, $connectionTimeout);
71 $connection->setOption(\Memcached::OPT_SERIALIZER, $serializer);
72
73 $result = false;
74 if (!empty($this->servers))
75 {
76 foreach ($this->servers as $server)
77 {
78 $success = $connection->addServer(
79 $server['host'],
80 $server['port'],
81 $server['weight']
82 );
83
84 if ($success)
85 {
86 $result = $success;
87 }
88 }
89
90 $error = error_get_last();
91 if (isset($error['type']) && $error['type'] === E_WARNING)
92 {
93 $exception = new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']);
94 $application = Application::getInstance();
95 $exceptionHandler = $application->getExceptionHandler();
96 $exceptionHandler->writeToLog($exception);
97 }
98 }
99
100 return $result? $connection : null;
101 }
102}