1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Copyright 2022 SURF B.V. |
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
|
|
|
trait FileTrait |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* This function takes care of actually saving the user data to a JSON file. |
22
|
|
|
* @param string $userId |
23
|
|
|
* @param array $data |
24
|
|
|
* @throws ReadWriteException |
25
|
|
|
*/ |
26
|
|
|
protected function _saveUser($userId, $data) |
27
|
|
|
{ |
28
|
|
|
if (file_put_contents($this->getPath().$userId.".json", json_encode($data)) === false) { |
29
|
|
|
throw new ReadWriteException('Unable to save the user to user storage (file storage)'); |
30
|
|
|
} |
31
|
|
|
return true; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* This function takes care of loading the user data from a JSON file. |
36
|
|
|
* |
37
|
|
|
* @param string $userId |
38
|
|
|
* @param boolean $failIfNotFound |
39
|
|
|
* |
40
|
|
|
* @return false if the data is not present, or an array containing the data. |
41
|
|
|
* |
42
|
|
|
* @throws Exception when the data can not be found and failIfNotFound is set to true |
43
|
|
|
*/ |
44
|
|
|
protected function _loadUser($userId, $failIfNotFound = TRUE) |
45
|
|
|
{ |
46
|
|
|
$fileName = $this->getPath().$userId.".json"; |
47
|
|
|
|
48
|
|
|
$data = NULL; |
49
|
|
|
if (file_exists($fileName)) { |
50
|
|
|
$data = json_decode(file_get_contents($this->getPath().$userId.".json"), true); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
if ($data === NULL) { |
54
|
|
|
if ($failIfNotFound) { |
55
|
|
|
throw new Exception('Error loading data for user: ' . var_export($userId, TRUE)); |
56
|
|
|
} else { |
57
|
|
|
$this->logger->error('Error loading data for user from user storage (file storage)'); |
58
|
|
|
return false; |
59
|
|
|
} |
60
|
|
|
} else { |
61
|
|
|
return $data; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Retrieve the path where the json files are stored. |
67
|
|
|
* @return String |
68
|
|
|
*/ |
69
|
|
|
public function getPath() |
70
|
|
|
{ |
71
|
|
|
if (substr($this->path, -1)!="/") return $this->path."/"; |
72
|
|
|
return $this->path; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|