CacheTrait.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. /*
  3. * Copyright 2015 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace Google\Auth;
  18. use Psr\Cache\CacheItemPoolInterface;
  19. trait CacheTrait
  20. {
  21. /**
  22. * @var int
  23. */
  24. private $maxKeyLength = 64;
  25. /**
  26. * @var array<mixed>
  27. */
  28. private $cacheConfig;
  29. /**
  30. * @var ?CacheItemPoolInterface
  31. */
  32. private $cache;
  33. /**
  34. * Gets the cached value if it is present in the cache when that is
  35. * available.
  36. *
  37. * @param mixed $k
  38. *
  39. * @return mixed
  40. */
  41. private function getCachedValue($k)
  42. {
  43. if (is_null($this->cache)) {
  44. return null;
  45. }
  46. $key = $this->getFullCacheKey($k);
  47. if (is_null($key)) {
  48. return null;
  49. }
  50. $cacheItem = $this->cache->getItem($key);
  51. if ($cacheItem->isHit()) {
  52. return $cacheItem->get();
  53. }
  54. }
  55. /**
  56. * Saves the value in the cache when that is available.
  57. *
  58. * @param mixed $k
  59. * @param mixed $v
  60. * @return mixed
  61. */
  62. private function setCachedValue($k, $v)
  63. {
  64. if (is_null($this->cache)) {
  65. return null;
  66. }
  67. $key = $this->getFullCacheKey($k);
  68. if (is_null($key)) {
  69. return null;
  70. }
  71. $cacheItem = $this->cache->getItem($key);
  72. $cacheItem->set($v);
  73. $cacheItem->expiresAfter($this->cacheConfig['lifetime']);
  74. return $this->cache->save($cacheItem);
  75. }
  76. /**
  77. * @param null|string $key
  78. * @return null|string
  79. */
  80. private function getFullCacheKey($key)
  81. {
  82. if (is_null($key)) {
  83. return null;
  84. }
  85. $key = $this->cacheConfig['prefix'] . $key;
  86. // ensure we do not have illegal characters
  87. $key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $key);
  88. // Hash keys if they exceed $maxKeyLength (defaults to 64)
  89. if ($this->maxKeyLength && strlen($key) > $this->maxKeyLength) {
  90. $key = substr(hash('sha256', $key), 0, $this->maxKeyLength);
  91. }
  92. return $key;
  93. }
  94. }