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

DatabaseService   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 66
rs 10
wmc 11
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getProjects() 0 15 3
A removeProject() 0 17 3
A addProject() 0 14 2
A generateDatabase() 0 10 3
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
}