Test Failed
Pull Request — develop (#30)
by Michiel
07:02
created

FileTrait::_saveUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 2
1
<?php
2
trait FileTrait
3
{
4
    /**
5
     * This function takes care of actually saving the user data to a JSON file.
6
     * @param String $userId
7
     * @param array $data
8
     */
9
    protected function _saveUser($userId, $data)
10
    {
11
        if (file_put_contents($this->getPath().$userId.".json", json_encode($data)) === false) {
12
            $this->logger->error('Unable to save the user to user storage (file storage)');
13
            return false;
14
        }
15
        return true;
16
    }
17
18
    /**
19
     * This function takes care of loading the user data from a JSON file.
20
     * @param String $userId
21
     * @return false if the data is not present, or an array containing the data.
22
     */
23
    protected function _loadUser($userId, $failIfNotFound = TRUE)
24
    {
25
        $fileName = $this->getPath().$userId.".json";
26
27
        $data = NULL;
28
        if (file_exists($fileName)) {
29
            $data = json_decode(file_get_contents($this->getPath().$userId.".json"), true);
30
        }
31
32
        if ($data === NULL) {
33
            if ($failIfNotFound) {
34
                throw new Exception('Error loading data for user: ' . var_export($userId, TRUE));
35
            } else {
36
                $this->logger->error('Error loading data for user from user storage (file storage)');
37
                return false;
38
            }
39
        } else {
40
            return $data;
41
        }
42
    }
43
44
    /**
45
     * Retrieve the path where the json files are stored.
46
     * @return String
47
     */
48
    public function getPath()
49
    {
50
        if (substr($this->path, -1)!="/") return $this->path."/";
51
        return $this->path;
52
    }
53
}
54