-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.php
More file actions
109 lines (98 loc) · 2.08 KB
/
Database.php
File metadata and controls
109 lines (98 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
/**
* Created by PhpStorm.
* User: fris
* Date: 07/05/18
* Time: 08:41 AM
*/
class Database
{
/** @var string */
const FILE_HANDLE = 'db';
/** @var string */
private $filename;
/** @var array */
private $data = [];
public function __construct(string $filename)
{
$this->setFilename($filename);
if(!file_exists($filename)) {
echo "Creating the database's file:" . fopen($filename, "w") . PHP_EOL;
} else {
foreach (json_decode(file_get_contents($filename)) as $key => $value){
$this->addData($key, $value);
}
}
}
/**
* @return Database
*/
public function saveData(): self
{
file_put_contents($this->getFilename() , json_encode($this->getData(), JSON_PRETTY_PRINT | JSON_BIGINT_AS_STRING));
return $this;
}
/**
* @return string
*/
public function getFilename(): string
{
return $this->filename;
}
/**
* @param string $filename
* @return Database
*/
public function setFilename(string $filename): self
{
$this->filename = $filename;
return $this;
}
/**
* @return array
*/
public function getData(): array
{
return $this->data;
}
/**
* @param array $data
* @return Database
*/
public function setData(array $data): self
{
$this->data = $data;
return $this;
}
/**
* @param $key
* @param $value
* @return Database
*/
public function addData($key, $value): self
{
$this->data[strtolower($key)] = $value;
return $this;
}
/**
* @param $key
* @return Database
*/
public function removeData($key): self
{
if (key_exists($key, $this->data)){
unset($this->data[$key]);
}
return $this;
}
/**
* @return bool
*/
public function close(): bool
{
$this->saveData();
unset($this->data);
unset($this->filename);
return true;
}
}