From 1536079fe384c0cdc8b3814b67318140dbc339ff Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Wed, 11 Feb 2026 17:25:22 +0100 Subject: [PATCH] feat: add static method to create new `Database` instance from credentials (#22) In this PR we add a new static method for creating a `vlw\Scaffold\Database\Database` instance from a set of provided credentials. This is of course not ideal and a better way to instance this class should be added in the future. Reviewed-on: https://codeberg.org/vlw/scaffold/pulls/22 --- src/Database/Database.php | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/Database/Database.php b/src/Database/Database.php index f050ee9..ec95a26 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -15,6 +15,39 @@ public const DATE_FORMAT = "Y-m-d"; public const DATETIME_FORMAT = "Y-m-d H:i:s"; + private const DEFAULT_HOSTNAME = "localhost"; + private const DEFAULT_USERNAME = "www-data"; + private const DEFAULT_PASSWORD = ""; + + /** + * Create a new Database instance from credentials + * + * @param string $host + * @param string $username + * @param string $password + * @param string $database + * @return static + */ + public static function from_credentials( + ?string $host = self::DEFAULT_HOSTNAME, + ?string $username = self::DEFAULT_USERNAME, + ?string $password = self::DEFAULT_PASSWORD, + string $database + ) { + // Create key if it does not exist + if (!$_ENV["mariadb"]) { + $_ENV["mariadb"] = []; + } + + // Set environment variables from credentials + $_ENV["mariadb"]["host"] = $host; + $_ENV["mariadb"]["user"] = $username; + $_ENV["mariadb"]["pass"] = $password; + $_ENV["mariadb"]["db"] = $database; + + return new static(); + } + /** * Wrap a new vlw/MySQL instance with credentials from project .env.ini */