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