Yaffs site version 1.1
[yaffs-website] / web / modules / contrib / memcache / src / DrupalMemcacheBase.php
1 <?php
2
3 /**
4  * @file
5  * Contains \Drupal\memcache\DrupalMemcacheBase.
6  */
7
8 namespace Drupal\memcache;
9
10 use Psr\Log\LogLevel;
11
12 /**
13  * Class DrupalMemcacheBase.
14  */
15 abstract class DrupalMemcacheBase implements DrupalMemcacheInterface {
16
17   /**
18    * The memcache config object.
19    *
20    * @var \Drupal\memcache\DrupalMemcacheConfig
21    */
22   protected $settings;
23
24   /**
25    * The memcache object.
26    *
27    * @var mixed
28    *   E.g. \Memcache|\Memcached
29    */
30   protected $memcache;
31
32   /**
33    * The hash algorithm to pass to hash(). Defaults to 'sha1'
34    *
35    * @var string
36    */
37   protected $hashAlgorithm;
38
39   /**
40    * The prefix memcache key for all keys.
41    *
42    * @var string
43    */
44   protected $prefix;
45
46   /**
47    * Constructs a DrupalMemcacheBase object.
48    *
49    * @param \Drupal\memcache\DrupalMemcacheConfig
50    *   The memcache config object.
51    */
52   public function __construct(DrupalMemcacheConfig $settings) {
53     $this->settings = $settings;
54
55     $this->hashAlgorithm = $this->settings->get('key_hash_algorithm', 'sha1');
56     $this->prefix = $this->settings->get('key_prefix', '');
57   }
58
59   /**
60    * {@inheritdoc}
61    */
62   public function get($key) {
63     $full_key = $this->key($key);
64
65     $track_errors = ini_set('track_errors', '1');
66     $php_errormsg = '';
67     $result = @$this->memcache->get($full_key);
68
69     if (!empty($php_errormsg)) {
70       register_shutdown_function('memcache_log_warning', LogLevel::WARNING, 'Exception caught in DrupalMemcacheBase::get: !msg', array('!msg' => $php_errormsg));
71       $php_errormsg = '';
72     }
73     ini_set('track_errors', $track_errors);
74
75     return $result;
76   }
77
78   /**
79    * {@inheritdoc}
80    */
81   public function key($key) {
82     $full_key = urlencode($this->prefix . '-' . $key);
83
84     // Memcache only supports key lengths up to 250 bytes.  If we have generated
85     // a longer key, we shrink it to an acceptable length with a configurable
86     // hashing algorithm. Sha1 was selected as the default as it performs
87     // quickly with minimal collisions.
88     if (strlen($full_key) > 250) {
89       $full_key = urlencode(hash($this->hashAlgorithm, $this->prefix . '-' . $key));
90     }
91
92     return $full_key;
93   }
94
95   /**
96    * {@inheritdoc}
97    */
98   public function delete($key) {
99     $full_key = $this->key($key);
100     return $this->memcache->delete($full_key, 0);
101   }
102
103   /**
104    * {@inheritdoc}
105    */
106   public function flush() {
107     $this->memcache->flush();
108   }
109
110 }