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($this->getDatabasePath()); |
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($this->getDatabasePath(), 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($this->getDatabasePath(), 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) { |
65
|
|
|
throw new \Exception('Problem generation database'); |
66
|
|
|
} |
67
|
|
|
file_put_contents($this->getDatabasePath(), json_encode('{[]}')); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
private function getDatabasePath() |
72
|
|
|
{ |
73
|
|
|
return getenv("HOME").'/'.self::DIRECTORY.'/'.self::DB; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
} |