mirror of
https://codeberg.org/vlw/scaffold.git
synced 2026-02-26 03:21:57 +01:00
This is a follow-up PR from #22. Instead of returning a new instance after setting the environment variables we simply do nothing. Most of the extending classes will not take advantage of the new instance anyways, and will just call `new Database()` as before. Of course, as mentioned in #22 this setup is not ideal, and another solution should be implemented to instance this class. Reviewed-on: https://codeberg.org/vlw/scaffold/pulls/24
70 lines
1.8 KiB
PHP
70 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace vlw\Scaffold;
|
|
|
|
use vlw\MySQL\MySQL;
|
|
|
|
use vlw\Scaffold\Database\Paginate;
|
|
|
|
require_once dirname(__DIR__, 1) . "/Helpers/Paginate.php";
|
|
|
|
/**
|
|
* Wrapper for vlw\MySQL which reads credentials from .env.ini in the project root.
|
|
*/
|
|
class Database extends MySQL {
|
|
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 void
|
|
*/
|
|
public static function set_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;
|
|
}
|
|
|
|
/**
|
|
* Wrap a new vlw/MySQL instance with credentials from project .env.ini
|
|
*/
|
|
public function __construct() {
|
|
parent::__construct(
|
|
$_ENV["mariadb"]["host"],
|
|
$_ENV["mariadb"]["user"],
|
|
$_ENV["mariadb"]["pass"],
|
|
$_ENV["mariadb"]["db"],
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Paginate request by chaining this after vlw/MySQL->from() and before vlw/MySQL->select()
|
|
*
|
|
* @param ?Paginate $paginate a vlw\Scaffold\Helper\Paginate instance
|
|
* @return self Instance chainable with vlw\MySQL
|
|
*/
|
|
public function paginate(?Paginate &$paginate = null): self {
|
|
return $paginate ? $this->limit($paginate->size, $paginate->offset) : $this;
|
|
}
|
|
}
|