DatabaseService::getProjects()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
cc 2
eloc 7
c 4
b 0
f 1
nc 2
nop 0
dl 0
loc 12
rs 9.4285
1
<?php
2
3
namespace Juanber84\Services;
4
5
class DatabaseService
6
{
7
    const DIRECTORY = '.dep';
8
    const DB = 'db.json';
9
10
    public function getProjects()
11
    {
12
        $this->generateDatabase();
13
        $db = file_get_contents($this->getDatabasePath());
14
15
        $jsonDb = json_decode($db,true);
16
        if (!is_array($jsonDb)) {
17
            throw new \RuntimeException('$jsonDb must be an array.');
18
        }
19
20
        return $jsonDb;
21
    }
22
23
    public function removeProject($keyProject)
24
    {
25
        $this->generateDatabase();
26
        $jsonDb = $this->getProjects();
27
28
        if (isset($jsonDb[$keyProject])){
29
            unset($jsonDb[$keyProject]);
30
            try {
31
                file_put_contents($this->getDatabasePath(), json_encode($jsonDb));
32
            } catch (\Exception $e){
33
                return false;
34
            }
35
        } else {
36
            return false;
37
        }
38
        return true;
39
    }
40
41
    public function addProject($keyProject, $path)
42
    {
43
        $this->generateDatabase();
44
        $jsonDb = $this->getProjects();
45
        $jsonDb[$keyProject] = $path;
46
47
        try {
48
            file_put_contents($this->getDatabasePath(), json_encode($jsonDb));
49
        } catch (\Exception $e){
50
            return false;
51
        }
52
53
        return true;
54
    }
55
56
    private function generateDatabase()
57
    {
58
        if (!file_exists(getenv("HOME").'/'.self::DIRECTORY)) {
59
            try {
60
                mkdir(getenv("HOME").'/'.self::DIRECTORY, 0777, true);
61
            } catch (\Exception $e) {
62
                throw new \Exception('Problem generation database');
63
            }
64
            file_put_contents($this->getDatabasePath(), json_encode(array()));
65
        }
66
    }
67
68
    private function getDatabasePath()
69
    {
70
        return getenv("HOME").'/'.self::DIRECTORY.'/'.self::DB;
71
    }
72
}