Ubiquity  2.0.2
php rapid development framework
ApiTokens.php
Go to the documentation of this file.
1 <?php
2 
4 
7 
8 class ApiTokens {
9  private $tokens;
10  private $length;
11  private $duration;
12  private static $cache;
13 
14  public function __construct($length=10,$duration=3600,$tokens=[]){
15  $this->length=$length;
16  $this->duration=$duration;
17  $this->tokens=$tokens;
18  }
19 
20  protected function generateToken(){
21  do{
22  $token= \bin2hex(\random_bytes($this->length));
23  }while (\array_search($token, $this->tokens,true)===true);
24  return $token;
25  }
26 
27  public function getTokens() {
28  return $this->tokens;
29  }
30 
31  public function getDuration() {
32  return $this->duration;
33  }
34 
35  public function getToken($key){
36  if(isset($this->tokens[$key]))
37  return $this->tokens[$key];
38  return false;
39  }
40 
41  public function isExpired($key){
42  $token=$this->getToken($key);
43  if($token!==false)
44  return \time() - $token["creationTime"] > $this->duration;
45  return true;
46  }
47 
48  public function addToken(){
49  $key=$this->generateToken();
50  $this->tokens[$key]=["creationTime"=>\time()];
51  return $key;
52  }
53 
54  public function clearAll(){
55  $this->tokens=[];
56  }
57 
58  public function removeExpireds(){
60  foreach ($tokens as $key=>$value){
61  if($this->isExpired($key)){
62  unset($this->tokens[$key]);
63  }
64  }
65  }
66 
67  public function remove($key){
68  if(isset($this->tokens[$key])){
69  unset($this->tokens[$key]);
70  return true;
71  }
72  return false;
73  }
74 
75  public function storeToCache($key="_apiTokens"){
76  $fileContent=["duration"=>$this->duration,"length"=>$this->length,"tokens"=>$this->tokens];
77  self::$cache->store($key, "return " . UArray::asPhpArray($fileContent,"array").";");
78  }
79 
87  public static function getFromCache($folder,$key="_apiTokens",$length=10,$duration=3600){
88  if(!isset(self::$cache)){
89  self::$cache=new ArrayCache($folder."rest/tokens",".rest");
90  }
91  $tokens=[];
92  if(self::$cache->exists($key)){
93  $filecontent=self::$cache->fetch($key);
94  if(isset($filecontent["tokens"])){
95  $tokens=$filecontent["tokens"];
96  }
97  if(isset($filecontent["length"])){
98  $length=$filecontent["length"];
99  }
100  if(isset($filecontent["duration"])){
101  $duration=$filecontent["duration"];
102  }
103  }
104  $apiTokens=new ApiTokens($length,$duration,$tokens);
105  return $apiTokens;
106  }
107 }
static asPhpArray($array, $prefix="")
Definition: UArray.php:27
storeToCache($key="_apiTokens")
Definition: ApiTokens.php:75
static getFromCache($folder, $key="_apiTokens", $length=10, $duration=3600)
Definition: ApiTokens.php:87
This class is responsible for storing Arrays in PHP files.
Definition: ArrayCache.php:13
__construct($length=10, $duration=3600, $tokens=[])
Definition: ApiTokens.php:14