Nenhuma descrição

CacheTrait.php 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. trait CacheTrait
  19. {
  20. private $maxKeyLength = 64;
  21. /**
  22. * Gets the cached value if it is present in the cache when that is
  23. * available.
  24. */
  25. private function getCachedValue($k)
  26. {
  27. if (is_null($this->cache)) {
  28. return;
  29. }
  30. $key = $this->getFullCacheKey($k);
  31. if (is_null($key)) {
  32. return;
  33. }
  34. $cacheItem = $this->cache->getItem($key);
  35. if ($cacheItem->isHit()) {
  36. return $cacheItem->get();
  37. }
  38. }
  39. /**
  40. * Saves the value in the cache when that is available.
  41. */
  42. private function setCachedValue($k, $v)
  43. {
  44. if (is_null($this->cache)) {
  45. return;
  46. }
  47. $key = $this->getFullCacheKey($k);
  48. if (is_null($key)) {
  49. return;
  50. }
  51. $cacheItem = $this->cache->getItem($key);
  52. $cacheItem->set($v);
  53. $cacheItem->expiresAfter($this->cacheConfig['lifetime']);
  54. return $this->cache->save($cacheItem);
  55. }
  56. private function getFullCacheKey($key)
  57. {
  58. if (is_null($key)) {
  59. return;
  60. }
  61. $key = $this->cacheConfig['prefix'] . $key;
  62. // ensure we do not have illegal characters
  63. $key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $key);
  64. // Hash keys if they exceed $maxKeyLength (defaults to 64)
  65. if ($this->maxKeyLength && strlen($key) > $this->maxKeyLength) {
  66. $key = substr(hash('sha256', $key), 0, $this->maxKeyLength);
  67. }
  68. return $key;
  69. }
  70. }