MemcacheProfilerStorage.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Profiler;
  11. use Memcache;
  12. /**
  13. * Memcache Profiler Storage
  14. *
  15. * @author Andrej Hudec <pulzarraider@gmail.com>
  16. */
  17. class MemcacheProfilerStorage extends BaseMemcacheProfilerStorage
  18. {
  19. /**
  20. * @var Memcache
  21. */
  22. private $memcache;
  23. /**
  24. * Internal convenience method that returns the instance of the Memcache
  25. *
  26. * @return Memcache
  27. *
  28. * @throws \RuntimeException
  29. */
  30. protected function getMemcache()
  31. {
  32. if (null === $this->memcache) {
  33. if (!preg_match('#^memcache://(?(?=\[.*\])\[(.*)\]|(.*)):(.*)$#', $this->dsn, $matches)) {
  34. throw new \RuntimeException(sprintf('Please check your configuration. You are trying to use Memcache with an invalid dsn "%s". The expected format is "memcache://[host]:port".', $this->dsn));
  35. }
  36. $host = $matches[1] ?: $matches[2];
  37. $port = $matches[3];
  38. $memcache = new Memcache;
  39. $memcache->addServer($host, $port);
  40. $this->memcache = $memcache;
  41. }
  42. return $this->memcache;
  43. }
  44. /**
  45. * Set instance of the Memcache
  46. *
  47. * @param Memcache $memcache
  48. */
  49. public function setMemcache($memcache)
  50. {
  51. $this->memcache = $memcache;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. protected function getValue($key)
  57. {
  58. return $this->getMemcache()->get($key);
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. protected function setValue($key, $value, $expiration = 0)
  64. {
  65. return $this->getMemcache()->set($key, $value, false, time() + $expiration);
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. protected function delete($key)
  71. {
  72. return $this->getMemcache()->delete($key);
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. protected function appendValue($key, $value, $expiration = 0)
  78. {
  79. $memcache = $this->getMemcache();
  80. if (method_exists($memcache, 'append')) {
  81. //Memcache v3.0
  82. if (!$result = $memcache->append($key, $value, false, $expiration)) {
  83. return $memcache->set($key, $value, false, $expiration);
  84. }
  85. return $result;
  86. }
  87. //simulate append in Memcache <3.0
  88. $content = $memcache->get($key);
  89. return $memcache->set($key, $content.$value, false, $expiration);
  90. }
  91. }