ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
TokenHandler.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22
25use ILIAS\MetaData\OERExposer\OAIPMH\DateHelper;
26
28{
29 use DateHelper;
30
31 public function generateToken(
32 int $offset,
33 ?\DateTimeImmutable $from_date,
34 ?\DateTimeImmutable $until_date
35 ): string {
36 /*
37 * (Re-)setting the until date helps with
38 * returning consistent results over multiple request if changes
39 * have been made in the meantime.
40 */
41 $current_date = $this->getCurrentDate();
42 if (is_null($until_date) || $until_date > $current_date) {
43 $until_date = $current_date;
44 }
45
46 $token_parts = [$offset, $until_date->format('Y-m-d')];
47 if (!is_null($from_date)) {
48 $token_parts[] = $from_date->format('Y-m-d');
49 }
50
51 return $this->encodeFromArray($token_parts);
52 }
53
54 public function isTokenValid(string $token): bool
55 {
56 $token_parts = $this->decodeToArray($token);
57
58 if (count($token_parts) < 2 || count($token_parts) > 3) {
59 return false;
60 }
61
62 if (
63 !isset($token_parts[0]) ||
64 !is_int($token_parts[0]) ||
65 $token_parts[0] < 0
66 ) {
67 return false;
68 }
69
70 if (
71 !isset($token_parts[1]) ||
72 !is_string($token_parts[1]) ||
73 !$this->isStringValidAsDate($token_parts[1])
74 ) {
75 return false;
76 }
77
78 // last parameter is optional
79 if (
80 isset($token_parts[2]) &&
81 (!is_string($token_parts[2]) || !$this->isStringValidAsDate($token_parts[2]))
82 ) {
83 return false;
84 }
85
86 return true;
87 }
88
90 RequestInterface $request,
91 string $token
93 $token_parts = $this->decodeToArray($token);
94
95 if (isset($token_parts[1])) {
96 $request = $request->withArgument(
97 Argument::UNTIL_DATE,
98 $token_parts[1]
99 );
100 }
101
102 if (isset($token_parts[2])) {
103 $request = $request->withArgument(
104 Argument::FROM_DATE,
105 $token_parts[2]
106 );
107 }
108
109 return $request;
110 }
111
112 public function getOffsetFromToken(string $token): int
113 {
114 return (int) ($this->decodeToArray($token)[0] ?? 0);
115 }
116
117 protected function decodeToArray(string $string): array
118 {
119 $decoded = json_decode(base64_decode($string));
120 if (is_array($decoded)) {
121 return $decoded;
122 }
123 return [];
124 }
125
126 protected function encodeFromArray(array $array): string
127 {
128 return base64_encode(json_encode($array));
129 }
130}
generateToken(int $offset, ?\DateTimeImmutable $from_date, ?\DateTimeImmutable $until_date)
appendArgumentsFromTokenToRequest(RequestInterface $request, string $token)
$token
Definition: xapitoken.php:70