Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
66.67% |
24 / 36 |
|
50.00% |
2 / 4 |
CRAP | |
0.00% |
0 / 1 |
Database | |
66.67% |
24 / 36 |
|
50.00% |
2 / 4 |
17.33 | |
0.00% |
0 / 1 |
__construct | |
23.08% |
3 / 13 |
|
0.00% |
0 / 1 |
11.28 | |||
setDefaultCredentials | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
5 | |||
setCredentials | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 | |||
connect | |
86.67% |
13 / 15 |
|
0.00% |
0 / 1 |
2.01 |
1 | <?php |
2 | |
3 | namespace Config; |
4 | |
5 | use Exceptions\DatabaseException; |
6 | |
7 | class Database { |
8 | private $host; |
9 | private $user; |
10 | private $password; |
11 | private $database; |
12 | |
13 | public function __construct(bool $useEnv = true) { |
14 | if (!$useEnv) { |
15 | $this->setDefaultCredentials(); |
16 | return; |
17 | } |
18 | |
19 | $envPath = __DIR__ . '/../../.env'; |
20 | |
21 | if (file_exists($envPath)) { |
22 | $env = parse_ini_file($envPath); |
23 | if ($env !== false) { |
24 | $this->host = $env['DB_HOST']; |
25 | $this->user = $env['DB_USER']; |
26 | $this->password = $env['DB_PASSWORD']; |
27 | $this->database = $env['DB_NAME']; |
28 | return; |
29 | } |
30 | } |
31 | |
32 | $this->setDefaultCredentials(); |
33 | } |
34 | |
35 | private function setDefaultCredentials(): void |
36 | { |
37 | $this->host = getenv('DB_HOST') ?: 'db'; |
38 | $this->user = getenv('DB_USER') ?: 'root'; |
39 | $this->password = getenv('DB_PASSWORD') ?: '123456'; |
40 | $this->database = getenv('DB_NAME') ?: 'tienda_bd'; |
41 | } |
42 | |
43 | public function setCredentials(string $host, string $user, string $password, string $database): void |
44 | { |
45 | $this->host = $host; |
46 | $this->user = $user; |
47 | $this->password = $password; |
48 | $this->database = $database; |
49 | } |
50 | |
51 | public function connect() { |
52 | try { |
53 | $conn = new \PDO( |
54 | "mysql:host={$this->host};dbname={$this->database}", |
55 | $this->user, |
56 | $this->password, |
57 | array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") |
58 | ); |
59 | $conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); |
60 | return $conn; |
61 | } catch(\PDOException $e) { |
62 | error_log("Error de conexión: " . $e->getMessage()); |
63 | throw new DatabaseException( |
64 | "Error de conexión a la base de datos: " . $e->getMessage(), |
65 | $e->getCode(), |
66 | $e |
67 | ); |
68 | } |
69 | } |
70 | } |