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