34d4ac0292f0e590b3cdc4c59dc57377a324c266
[yaffs-website] / web / modules / contrib / memcache / src / DrupalMemcached.php
1 <?php
2
3 /**
4  * @file
5  * Contains \Drupal\memcache\DrupalMemcached.
6  */
7
8 namespace Drupal\memcache;
9
10 /**
11  * Class DrupalMemcached.
12  */
13 class DrupalMemcached extends DrupalMemcacheBase {
14
15   /**
16    * {@inheritdoc}
17    */
18   public function __construct(DrupalMemcacheConfig $settings) {
19     parent::__construct($settings);
20
21     $this->memcache = new \Memcached();
22
23     $default_opts = array(
24       \Memcached::OPT_COMPRESSION => FALSE,
25       \Memcached::OPT_DISTRIBUTION => \Memcached::DISTRIBUTION_CONSISTENT,
26     );
27     foreach ($default_opts as $key => $value) {
28       $this->memcache->setOption($key, $value);
29     }
30     // See README.txt for setting custom Memcache options when using the
31     // memcached PECL extension.
32     foreach ($this->settings->get('options', []) as $key => $value) {
33       $this->memcache->setOption($key, $value);
34     }
35   }
36
37   /**
38    * {@inheritdoc}
39    */
40   public function addServer($server_path, $persistent = FALSE) {
41     list($host, $port) = explode(':', $server_path);
42
43     if ($host == 'unix') {
44       // Memcached expects just the path to the socket without the protocol
45       $host = substr($host, 7);
46       // Port is always 0 for unix sockets.
47       $port = 0;
48     }
49
50     return $this->memcache->addServer($host, $port, $persistent);
51   }
52
53   /**
54    * {@inheritdoc}
55    */
56   public function close() {
57     $this->memcache->quit();
58   }
59
60   /**
61    * {@inheritdoc}
62    */
63   public function set($key, $value, $exp = 0, $flag = FALSE) {
64     $full_key = $this->key($key);
65     return $this->memcache->set($full_key, $value, $exp);
66   }
67
68   /**
69    * {@inheritdoc}
70    */
71   public function getMulti(array $keys) {
72     $full_keys = array();
73
74     foreach ($keys as $cid) {
75       $full_key = $this->key($cid);
76       $full_keys[$cid] = $full_key;
77     }
78
79     $cas_tokens = NULL;
80     $results = $this->memcache->getMulti($full_keys, $cas_tokens, \Memcached::GET_PRESERVE_ORDER);
81
82     // If $results is FALSE, convert it to an empty array.
83     if (!$results) {
84       $results = array();
85     }
86
87     // Convert the full keys back to the cid.
88     $cid_results = array();
89     $cid_lookup = array_flip($full_keys);
90
91     foreach (array_filter($results) as $key => $value) {
92       $cid_results[$cid_lookup[$key]] = $value;
93     }
94
95     return $cid_results;
96   }
97
98 }