Completed
Push — master ( e32f5b...d93af6 )
by juan
02:37
created

DatabaseService::addProject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 9
c 1
b 0
f 1
nc 2
nop 2
dl 0
loc 14
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
        if (!file_exists(getenv("HOME").'/'.self::DIRECTORY)) {
14
            mkdir(getenv("HOME").'/'.self::DIRECTORY, 0777, true);
15
        }
16
17
        $db = file_get_contents(getenv("HOME").'/'.self::DIRECTORY.'/'.self::DB);
18
        $jsonDb = json_decode($db,true);
19
        if (!is_array($jsonDb)) {
20
            throw new \RuntimeException('$jsonDb must be an array.');
21
        }
22
23
        return $jsonDb;
24
    }
25
26
    public function removeProject($keyProject)
27
    {
28
        $this->generateDatabase();
29
        $jsonDb = $this->getProjects();
30
31
        if (isset($jsonDb[$keyProject])){
32
            unset($jsonDb[$keyProject]);
33
            try {
34
                file_put_contents(getenv("HOME").'/'.self::DIRECTORY.'/'.self::DB, json_encode($jsonDb));
35
            } catch (\Exception $e){
36
                return false;
37
            }
38
            return true;
39
        } else {
40
            return false;
41
        }
42
    }
43
44
    public function addProject($keyProject, $path)
45
    {
46
        $this->generateDatabase();
47
        $jsonDb = $this->getProjects();
48
        $jsonDb[$keyProject] = $path;
49
50
        try {
51
            file_put_contents(getenv("HOME").'/'.self::DIRECTORY.'/'.self::DB, json_encode($jsonDb));
52
        } catch (\Exception $e){
53
            return false;
54
        }
55
56
        return true;
57
    }
58
59
    private function generateDatabase()
60
    {
61
        if (!file_exists(getenv("HOME").'/'.self::DIRECTORY)) {
62
            try {
63
                mkdir(getenv("HOME").'/'.self::DIRECTORY, 0777, true);
64
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
65
            }
66
            file_put_contents(getenv("HOME").'/'.self::DIRECTORY.'/'.self::DB, json_encode('{[]}'));
67
        }
68
    }
69
70
}