DatabaseService   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getProjects() 0 12 2
A removeProject() 0 17 3
A addProject() 0 14 2
A generateDatabase() 0 11 3
A getDatabasePath() 0 4 1
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
}