Cache.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace WhichBrowser;
  3. use Psr\Cache\CacheItemPoolInterface;
  4. trait Cache
  5. {
  6. private $cache;
  7. private $expires;
  8. /**
  9. * @var boolean $cached Was this result retrieve from the cache?
  10. */
  11. public $cached = false;
  12. /**
  13. * Enable caching of results
  14. *
  15. * @param object $cache An PSR-6 cache pool (an object that implements Psr\Cache\CacheItemPoolInterface)
  16. * @param int $expires Optional the number of seconds after which a cached item expires, default is 15 minutes
  17. */
  18. public function setCache($cache, $expires = 900)
  19. {
  20. $this->cache = $cache;
  21. $this->expires = $expires;
  22. }
  23. /**
  24. * Apply cached data to the main Parser object
  25. *
  26. * @internal
  27. *
  28. * @param array $data An array with a key for every property it needs to apply
  29. */
  30. private function applyCachedData($data)
  31. {
  32. foreach ($data as $key => $value) {
  33. $this->$key = $value;
  34. }
  35. $this->cached = true;
  36. }
  37. /**
  38. * Retrieve the data that can be cached from the main Parser object
  39. *
  40. * @internal
  41. *
  42. * @return array An array with a key for every property that will be cached
  43. */
  44. private function retrieveCachedData()
  45. {
  46. return [
  47. 'browser' => $this->browser,
  48. 'engine' => $this->engine,
  49. 'os' => $this->os,
  50. 'device' => $this->device,
  51. 'camouflage' => $this->camouflage,
  52. 'features' => $this->features
  53. ];
  54. }
  55. /**
  56. * Retrieve the result from the cache, or analyse and store in the cache
  57. *
  58. * @internal
  59. *
  60. * @param array|string $headers An array with all of the headers or a string with just the User-Agent header
  61. *
  62. * @return boolean did we actually retrieve or analyse results
  63. */
  64. private function analyseWithCache($headers, $options = [])
  65. {
  66. if (isset($options['cache'])) {
  67. if (isset($options['cacheExpires'])) {
  68. $this->setCache($options['cache'], $options['cacheExpires']);
  69. } else {
  70. $this->setCache($options['cache']);
  71. }
  72. }
  73. if ($this->cache instanceof \Qii\Cache\Memcached) {
  74. $cacheId = 'whichbrowser_' . md5(serialize($headers));
  75. $item = unserialize($this->cache->get($cacheId));
  76. if ($item) {
  77. $this->applyCachedData($item);
  78. } else {
  79. $analyser = new Analyser($headers, $options);
  80. $analyser->setdata($this);
  81. $analyser->analyse();
  82. $data = serialize($this->retrieveCachedData());
  83. $this->cache->set($cacheId, $data, ['life_time' => time() + $this->expires]);
  84. }
  85. return true;
  86. }
  87. }
  88. }