| 1 |
<?php |
| 2 |
|
| 3 |
namespace WPStaging\Framework\Database; |
| 4 |
|
| 5 |
use WPStaging\Framework\Adapter\Database\DatabaseException; |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
final class ExternalDatabaseConfiguration |
| 11 |
{ |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
public function isEnabled($options): bool |
| 17 |
{ |
| 18 |
$options = $this->normalizeOptions($options); |
| 19 |
|
| 20 |
if (array_key_exists('useCustomDatabase', $options)) { |
| 21 |
return filter_var($options['useCustomDatabase'], FILTER_VALIDATE_BOOLEAN); |
| 22 |
} |
| 23 |
|
| 24 |
return $this->hasConnectionTarget($options); |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
public function hasConnectionTarget($options): bool |
| 32 |
{ |
| 33 |
$options = $this->normalizeOptions($options); |
| 34 |
|
| 35 |
return $this->getValue($options, 'databaseServer') !== '' |
| 36 |
&& $this->getValue($options, 'databaseUser') !== '' |
| 37 |
&& $this->getValue($options, 'databaseDatabase') !== ''; |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
public function validateConnectionTarget($options) |
| 46 |
{ |
| 47 |
$options = $this->normalizeOptions($options); |
| 48 |
|
| 49 |
if (!$this->hasConnectionTarget($options)) { |
| 50 |
throw new DatabaseException(__('External database credentials are incomplete. Enter the database host, database name, and database user.', 'wp-staging')); |
| 51 |
} |
| 52 |
|
| 53 |
if (strpos($this->getValue($options, 'databaseServer'), '://') !== false) { |
| 54 |
throw new DatabaseException(__('The external database server must be a hostname, IP address, socket, or host:port value without a URL scheme such as http:// or https://.', 'wp-staging')); |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
private function normalizeOptions($options): array |
| 63 |
{ |
| 64 |
if (is_array($options)) { |
| 65 |
return $options; |
| 66 |
} |
| 67 |
|
| 68 |
if (is_object($options)) { |
| 69 |
return get_object_vars($options); |
| 70 |
} |
| 71 |
|
| 72 |
return []; |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
private function getValue(array $options, string $key): string |
| 81 |
{ |
| 82 |
return isset($options[$key]) ? trim((string)$options[$key]) : ''; |
| 83 |
} |
| 84 |
} |
| 85 |
|