Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Memcached.php
Go to the documentation of this file.
1 <?php
7 
9 {
13  const DEFAULT_SLAB_SIZE = 1048576;
14 
18  const CODE_WORD = '{splitted}';
19 
26  public function __construct(array $options = [])
27  {
28  parent::__construct($options);
29 
30  if (!isset($options['slab_size']) || !is_numeric($options['slab_size'])) {
31  if (isset($options['slab_size'])) {
32  throw new \Magento\Framework\Exception\LocalizedException(
33  new \Magento\Framework\Phrase(
34  "Invalid value for the node <slab_size>. Expected to be positive integer."
35  )
36  );
37  }
38 
39  $this->_options['slab_size'] = self::DEFAULT_SLAB_SIZE;
40  } else {
41  $this->_options['slab_size'] = $options['slab_size'];
42  }
43  }
44 
52  protected function _getChunkId($id, $index)
53  {
54  return "{$id}[{$index}]";
55  }
56 
64  protected function _cleanTheMess($id, $chunks)
65  {
66  for ($i = 0; $i < $chunks; $i++) {
67  $this->remove($this->_getChunkId($id, $i));
68  }
69 
70  $this->remove($id);
71  }
72 
82  public function save($data, $id, $tags = [], $specificLifetime = false)
83  {
84  if (is_string($data) && strlen($data) > $this->_options['slab_size']) {
85  $dataChunks = str_split($data, $this->_options['slab_size']);
86 
87  for ($i = 0, $cnt = count($dataChunks); $i < $cnt; $i++) {
88  $chunkId = $this->_getChunkId($id, $i);
89 
90  if (!parent::save($dataChunks[$i], $chunkId, $tags, $specificLifetime)) {
91  $this->_cleanTheMess($id, $i + 1);
92  return false;
93  }
94  }
95 
96  $data = self::CODE_WORD . '|' . $i;
97  }
98 
99  return parent::save($data, $id, $tags, $specificLifetime);
100  }
101 
109  public function load($id, $doNotTestCacheValidity = false)
110  {
111  $data = parent::load($id, $doNotTestCacheValidity);
112 
113  if (is_string($data) && substr($data, 0, strlen(self::CODE_WORD)) == self::CODE_WORD) {
114  // Seems we've got chunked data
115 
116  $arr = explode('|', $data);
117  $chunks = isset($arr[1]) ? $arr[1] : false;
118  $chunkData = [];
119 
120  if ($chunks && is_numeric($chunks)) {
121  for ($i = 0; $i < $chunks; $i++) {
122  $chunk = parent::load($this->_getChunkId($id, $i), $doNotTestCacheValidity);
123 
124  if (false === $chunk) {
125  // Some chunk in chain was not found, we can not glue-up the data:
126  // clean the mess and return nothing
127 
128  $this->_cleanTheMess($id, $chunks);
129  return false;
130  }
131 
132  $chunkData[] = $chunk;
133  }
134 
135  return implode('', $chunkData);
136  }
137  }
138 
139  // Data has not been splitted to chunks on save
140  return $data;
141  }
142 }
$id
Definition: fieldset.phtml:14
save($data, $id, $tags=[], $specificLifetime=false)
Definition: Memcached.php:82
load($id, $doNotTestCacheValidity=false)
Definition: Memcached.php:109
$i
Definition: gallery.phtml:31
$index
Definition: list.phtml:44