1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
/* |
5
|
|
|
+-----------------------------------------------------------------------------+ |
6
|
|
|
| PHPPackage - PDO Wrapper |
7
|
|
|
+-----------------------------------------------------------------------------+ |
8
|
|
|
| Copyright (c)2018 (http://github.com/phppackage/pdo-wrapper) |
9
|
|
|
+-----------------------------------------------------------------------------+ |
10
|
|
|
| This source file is subject to MIT License |
11
|
|
|
| that is bundled with this package in the file LICENSE. |
12
|
|
|
| |
13
|
|
|
| If you did not receive a copy of the license and are unable to |
14
|
|
|
| obtain it through the world-wide-web, please send an email |
15
|
|
|
| to [email protected] so we can send you a copy immediately. |
16
|
|
|
+-----------------------------------------------------------------------------+ |
17
|
|
|
| Authors: |
18
|
|
|
| Lawrence Cherone <[email protected]> |
19
|
|
|
+-----------------------------------------------------------------------------+ |
20
|
|
|
*/ |
21
|
|
|
|
22
|
|
|
namespace PHPPackage\PDOWrapper; |
23
|
|
|
|
24
|
|
|
class Database |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @var PHPPackage\PDOWrapper\PDO |
|
|
|
|
28
|
|
|
*/ |
29
|
|
|
private $pdo; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* |
33
|
|
|
*/ |
34
|
3 |
|
public function __construct(PDO $pdo) |
35
|
|
|
{ |
36
|
3 |
|
$this->pdo = $pdo; |
|
|
|
|
37
|
3 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Get database name from dsn |
41
|
|
|
* |
42
|
|
|
* @throws RuntimeException |
43
|
|
|
* @return string |
44
|
|
|
*/ |
45
|
2 |
|
public function name(string $dsn): string |
46
|
|
|
{ |
47
|
|
|
// match database from dsn & set working vars |
48
|
2 |
|
if (!preg_match('/dbname=(\w+);/', $dsn, $results)) { |
49
|
1 |
|
throw new \RuntimeException('Could not match database name from dsn'); |
50
|
|
|
} |
51
|
|
|
|
52
|
1 |
|
return $results[1]; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Create database |
57
|
|
|
* |
58
|
|
|
* @return bool |
59
|
|
|
*/ |
60
|
1 |
|
public function create(string $name, $username, $password): bool |
61
|
|
|
{ |
62
|
1 |
|
if (!in_array($name, $this->all())) { |
63
|
1 |
|
return (bool) $this->pdo->exec(" |
64
|
1 |
|
CREATE DATABASE `$name`; |
65
|
1 |
|
CREATE USER '{$username}'@'%' IDENTIFIED BY '{$password}'; |
66
|
1 |
|
GRANT ALL ON `$name`.* TO '{$username}'@'%'; |
67
|
|
|
FLUSH PRIVILEGES; |
68
|
|
|
"); |
69
|
|
|
} |
70
|
1 |
|
return false; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Returns an array of databases |
75
|
|
|
* @return mixed |
76
|
|
|
*/ |
77
|
1 |
|
public function all(): array |
78
|
|
|
{ |
79
|
1 |
|
$stmt = $this->pdo->query("SHOW DATABASES"); |
80
|
|
|
|
81
|
1 |
|
$result = []; |
82
|
1 |
|
while ($row = $stmt->fetchColumn(0)) { |
83
|
1 |
|
$result[] = $row; |
84
|
|
|
} |
85
|
|
|
|
86
|
1 |
|
return $result; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
} |
90
|
|
|
|