Test Failed
Pull Request — develop (#27)
by Michiel
06:05
created

FileTrait::_loadUser()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 18
rs 9.8666
cc 4
nc 6
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
     *
21
     * @param string $userId
22
     * @param boolean $failIfNotFound
23
     *
24
     * @return false if the data is not present, or an array containing the data.
25
     *
26
     * @throws Exception when the data can not be found and failIfNotFound is set to true
27
     */
28
    protected function _loadUser($userId, $failIfNotFound = TRUE)
29
    {
30
        $fileName = $this->getPath().$userId.".json";
31
32
        $data = NULL;
33
        if (file_exists($fileName)) {
34
            $data = json_decode(file_get_contents($this->getPath().$userId.".json"), true);
35
        }
36
37
        if ($data === NULL) {
38
            if ($failIfNotFound) {
39
                throw new Exception('Error loading data for user: ' . var_export($userId, TRUE));
40
            } else {
41
                $this->logger->error('Error loading data for user from user storage (file storage)');
42
                return false;
43
            }
44
        } else {
45
            return $data;
46
        }
47
    }
48
49
    /**
50
     * Retrieve the path where the json files are stored.
51
     * @return String
52
     */
53
    public function getPath()
54
    {
55
        if (substr($this->path, -1)!="/") return $this->path."/";
56
        return $this->path;
57
    }
58
}
59