1 <?php
2
3 namespace PayPal\Cache;
4
5 use PayPal\Core\PayPalConfigManager;
6 use PayPal\Validation\JsonValidator;
7
8 abstract class AuthorizationCache
9 {
10 public static $CACHE_PATH = '/../../../var/auth.cache';
11
12 13 14 15 16 17 18 19
20 public static function pull($config = null, $clientId = null)
21 {
22
23 if (!self::isEnabled($config)) {
24 return null;
25 }
26
27 $tokens = null;
28 $cachePath = self::cachePath($config);
29 if (file_exists($cachePath)) {
30
31 $cachedToken = file_get_contents($cachePath);
32 if ($cachedToken && JsonValidator::validate($cachedToken, true)) {
33 $tokens = json_decode($cachedToken, true);
34 if ($clientId && is_array($tokens) && array_key_exists($clientId, $tokens)) {
35
36 return $tokens[$clientId];
37 } elseif ($clientId) {
38
39 return null;
40 }
41 }
42 }
43 return $tokens;
44 }
45
46 47 48 49 50 51 52 53 54 55
56 public static function push($config = null, $clientId, $accessToken, $tokenCreateTime, $tokenExpiresIn)
57 {
58
59 if (!self::isEnabled($config)) {
60 return;
61 }
62
63 $cachePath = self::cachePath($config);
64 if (!is_dir(dirname($cachePath))) {
65 if (mkdir(dirname($cachePath), 0755, true) == false) {
66 throw new \Exception("Failed to create directory at $cachePath");
67 }
68 }
69
70
71 $tokens = self::pull();
72 $tokens = $tokens ? $tokens : array();
73 if (is_array($tokens)) {
74 $tokens[$clientId] = array(
75 'clientId' => $clientId,
76 'accessTokenEncrypted' => $accessToken,
77 'tokenCreateTime' => $tokenCreateTime,
78 'tokenExpiresIn' => $tokenExpiresIn
79 );
80 }
81 if (!file_put_contents($cachePath, json_encode($tokens))) {
82 throw new \Exception("Failed to write cache");
83 };
84 }
85
86 87 88 89 90 91
92 public static function isEnabled($config)
93 {
94 $value = self::getConfigValue('cache.enabled', $config);
95 return empty($value) ? false : ((trim($value) == true || trim($value) == 'true'));
96 }
97
98 99 100 101 102 103
104 public static function cachePath($config)
105 {
106 $cachePath = self::getConfigValue('cache.FileName', $config);
107 return empty($cachePath) ? __DIR__ . self::$CACHE_PATH : $cachePath;
108 }
109
110 111 112 113 114 115 116 117
118 private static function getConfigValue($key, $config)
119 {
120 $config = ($config && is_array($config)) ? $config : PayPalConfigManager::getInstance()->getConfigHashmap();
121 return (array_key_exists($key, $config)) ? trim($config[$key]) : null;
122 }
123 }
124