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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace Illuminate\Cache;
use Memcached;
use RuntimeException;
class MemcachedConnector
{
/**
* Create a new Memcached connection.
*
* @param array $servers
* @param string|null $connectionId
* @param array $options
* @param array $credentials
* @return \Memcached
*
* @throws \RuntimeException
*/
public function connect(
array $servers, $connectionId = null,
array $options = [], array $credentials = []
) {
$memcached = $this->getMemcached(
$connectionId, $credentials, $options
);
if (! $memcached->getServerList()) {
// For each server in the array, we'll just extract the configuration and add
// the server to the Memcached connection. Once we have added all of these
// servers we'll verify the connection is successful and return it back.
foreach ($servers as $server) {
$memcached->addServer(
$server['host'], $server['port'], $server['weight']
);
}
}
return $this->validateConnection($memcached);
}
/**
* Get a new Memcached instance.
*
* @param string|null $connectionId
* @param array $credentials
* @param array $options
* @return \Memcached
*/
protected function getMemcached($connectionId, array $credentials, array $options)
{
$memcached = $this->createMemcachedInstance($connectionId);
if (count($credentials) == 2) {
$this->setCredentials($memcached, $credentials);
}
if (count($options)) {
$memcached->setOptions($options);
}
return $memcached;
}
/**
* Create the Memcached instance.
*
* @param string|null $connectionId
* @return \Memcached
*/
protected function createMemcachedInstance($connectionId)
{
return empty($connectionId) ? new Memcached : new Memcached($connectionId);
}
/**
* Set the SASL credentials on the Memcached connection.
*
* @param \Memcached $memcached
* @param array $credentials
* @return void
*/
protected function setCredentials($memcached, $credentials)
{
list($username, $password) = $credentials;
$memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$memcached->setSaslAuthData($username, $password);
}
/**
* Validate the given Memcached connection.
*
* @param \Memcached $memcached
* @return \Memcached
*/
protected function validateConnection($memcached)
{
$status = $memcached->getVersion();
if (! is_array($status)) {
throw new RuntimeException('No Memcached servers added.');
}
if (in_array('255.255.255', $status) && count(array_unique($status)) === 1) {
throw new RuntimeException('Could not establish Memcached connection.');
}
return $memcached;
}
}