1<?php
2/*
3 * Copyright 2020 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
18namespace Google\Auth;
19
20use Google\Auth\Credentials\GCECredentials;
21use Psr\Cache\CacheItemPoolInterface;
22
23/**
24 * A class to implement caching for calls to GCECredentials::onGce. This class
25 * is used automatically when you pass a `Psr\Cache\CacheItemPoolInterface`
26 * cache object to `ApplicationDefaultCredentials::getCredentials`.
27 *
28 * ```
29 * $sysvCache = new Google\Auth\SysvCacheItemPool();
30 * $creds = Google\Auth\ApplicationDefaultCredentials::getCredentials(
31 *     $scope,
32 *     null,
33 *     null,
34 *     $sysvCache
35 * );
36 * ```
37 */
38class GCECache
39{
40    const GCE_CACHE_KEY = 'google_auth_on_gce_cache';
41
42    use CacheTrait;
43
44    /**
45     * @param array<mixed> $cacheConfig Configuration for the cache
46     * @param CacheItemPoolInterface $cache
47     */
48    public function __construct(
49        array $cacheConfig = null,
50        CacheItemPoolInterface $cache = null
51    ) {
52        $this->cache = $cache;
53        $this->cacheConfig = array_merge([
54            'lifetime' => 1500,
55            'prefix' => '',
56        ], (array) $cacheConfig);
57    }
58
59    /**
60     * Caches the result of onGce so the metadata server is not called multiple
61     * times.
62     *
63     * @param callable $httpHandler callback which delivers psr7 request
64     * @return bool True if this a GCEInstance, false otherwise
65     */
66    public function onGce(callable $httpHandler = null)
67    {
68        if (is_null($this->cache)) {
69            return GCECredentials::onGce($httpHandler);
70        }
71
72        $cacheKey = self::GCE_CACHE_KEY;
73        $onGce = $this->getCachedValue($cacheKey);
74
75        if (is_null($onGce)) {
76            $onGce = GCECredentials::onGce($httpHandler);
77            $this->setCachedValue($cacheKey, $onGce);
78        }
79
80        return $onGce;
81    }
82}
83