Files
php_assessment_1/mysql-database-service.php
T

659 lines
14 KiB
PHP
Raw Normal View History

2025-02-04 23:06:08 +01:00
<?php
require 'mysql-adapter.php';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* MySqlDatabaseService
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*
*/
class MySqlDatabaseService
{
protected $_db = NULL;
protected $_instance = NULL;
protected $_table = '';
protected $_primary_key = 'id';
protected $_return_type = 'array';
protected $_allowed_fields = [];
protected $_label_fields = [];
protected $_use_timestamps = TRUE;
protected $_created_field = 'created_at';
protected $_updated_field = 'updated_at';
protected $_validation_rules = [];
protected $_validation_edit_rules = [];
protected $_validation_messages = [];
public function __construct()
{
$this->_instance = MySqlAdapter::get_instance();
$this->_db = $this->_instance->get_connection();
}
/**
* If you need to modify payload before create, overload this function
*
* @param mixed $data
* @return mixed
*/
protected function _pre_create_processing($data)
{
return $data;
}
/**
* If you need to modify payload before edit, overload this function
*
* @param mixed $data
* @return mixed
*/
protected function _post_edit_processing($data)
{
return $data;
}
/**
* Allow user to add extra counting condition so user don't have to change main function
*
* @param mixed $parameters
* @return $db
*/
protected function _custom_counting_conditions(&$db)
{
return $db;
}
/**
* Raw Mysql query
*
* @param string $sql
* @return mixed
*/
public function raw_query($sql)
{
}
/**
* Raw no error query for writes
*
* @param string $sql
* @return mixed
*/
public function raw_no_error_query($sql)
{
}
/**
* Raw Mysql query
*
* @param string $sql
* @return mixed
*/
public function raw_prepare_query($sql, $parameters)
{
}
/**
* Get Model
*
* @param integer $id
* @return mixed
*/
public function get($id)
{
return R::load($this->_table, $id);
}
public function get_like($field, $value)
{
// Match strings that start with $value
return R::find($this->_table, ' ' . $field . ' LIKE ? ORDER BY id DESC LIMIT 1', [$value . '%']);
}
// public function get_like($field, $value)
// {
// // Use a custom SQL query with REGEXP for more precise pattern matching
// $sql = 'SELECT * FROM ' . $this->_table . ' WHERE ' . $field . ' LIKE ? ORDER BY id DESC';
// return R::getAll($sql, [$value . '%']);
// }
/**
* Get Model by field
*
* @param string $field
* @param mixed $value
* @return mixed
*/
public function get_by_field($field, $value)
{
return R::findOne($this->_table, " $field = ? ", ["$value"]);
}
/**
* Get One Model by fields
*
* @param string $field
* @param mixed $value
* @return mixed
*/
public function get_one_by_fields($where)
{
$sql = [];
foreach ($where as $key => $value) {
if (is_string($value) && strlen($value) > 0) {
$sql[] = " `$key` = '$value' ";
} else {
$sql[] = " `$key` = '$value' ";
}
}
return R::findOne($this->_table, implode(' AND ', $sql));
}
/**
* Get Model by fields
*
* @param string $field
* @param mixed $value
* @return mixed
*/
public function get_by_fields($where)
{
$sql = [];
foreach ($where as $key => $value) {
if (is_string($value) && strlen($value) > 0) {
// $sql[] = "$key";
// echo "1";
$sql[] = " `$key` = '$value' ";
} else {
$sql[] = " `$key` = '$value' ";
}
}
return R::find($this->_table, implode(' AND ', $sql));
// R::fancyDebug( TRUE );
// $logs = R::getDatabaseAdapter()
// ->getDatabase()
// ->getLogger();
// echo "<pre>";
// print_r( $where );
// print_r( $sql );
// print_r( $logs->grep( 'SELECT' ) );
// die;
}
/**
* Get all Model
* @param array $where
* @return array
*/
public function get_all($where = array())
{
$sql = [];
foreach ($where as $key => $value) {
if (is_string($value) && strlen($value) > 0) {
$sql[] = "$key";
} else {
$sql[] = "$key = $value";
}
}
return R::findAll($this->_table, implode(' AND ', $sql));
}
/**
* Get all Model
* @param string $status
* @return array
*/
public function get_all_by_status($status)
{
return R::findAll($this->_table, "status = ", [$status]);
}
/**
* Get all Model key value
* @param string $field
* @param string $status
* @return array
*/
public function get_all_by_key_value($field, $status)
{
$results = R::findAll($this->_table, "status = ", [$status]);
$key_value = [];
foreach ($results as $key => $value) {
$key_value[$value['id']] = $value[$field];
}
return $key_value;
}
/**
* Create
*
* @param array $data
* @return mixed
*/
public function create($data)
{
try {
if ($this->_use_timestamps) {
if (!isset($data[$this->_created_field])) {
$data[$this->_created_field] = date('Y-m-j');
}
if (!isset($data[$this->_updated_field])) {
$data[$this->_updated_field] = date('Y-m-j H:i:s');
}
}
$data = $this->_pre_create_processing($data);
$row = R::dispense($this->_table);
foreach ($data as $key => $value) {
$row[$key] = $value;
}
$id = R::store($row);
if ($id) {
return $id;
}
return FALSE;
} catch (Exception $e) {
echo $e;
}
}
/**
* Bulk Create
*
* @param [type] $params
* @return void
*/
public function batch_insert($params)
{
if ($this->_use_timestamps) {
$rows = [];
foreach ($params as $key => $value) {
$params[$key][$this->_created_field] = date('Y-m-j');
$params[$key][$this->_updated_field] = date('Y-m-j H:i:s');
$row = R::dispense($this->_table);
foreach ($value as $field => $val) {
$row[$field] = $val;
}
$rows[] = $row;
}
}
return R::storeAll($rows);
}
/**
* Edit Model
* @param array $data
* @param integer $id
* @return bool
*/
public function edit($data, $id)
{
if ($this->_use_timestamps) {
if (!isset($data[$this->_updated_field])) {
$data[$this->_updated_field] = date('Y-m-j H:i:s');
}
}
$data = $this->_post_edit_processing($data);
$row = R::load($this->_table, $id);
foreach ($data as $key => $value) {
$row[$key] = $value;
}
return R::store($row);
}
/**
* Edit Model
* @param array $data
* @param integer $id
* @return bool
*/
public function edit_raw($data, $id)
{
if ($this->_use_timestamps) {
$data[$this->_updated_field] = date('Y-m-j H:i:s');
}
$row = R::load($this->_table, $id);
foreach ($data as $key => $value) {
$row[$key] = $value;
}
return R::store($row);
}
/**
* Soft Delete Model
* @param array $data
* @param integer $id
* @return bool
*/
public function delete($id)
{
$row = R::load($this->_table, $id);
$row['status'] = 0;
return R::store($row);
}
/**
* Real Delete Model
* @param integer $id
* @return bool
*/
public function real_delete($id)
{
$row = R::load($this->_table, $id);
R::trash($row);
}
/**
* Real Delete Model
* @param Array
* @return bool
*/
public function real_delete_by_fields($where = [])
{
$sql = [];
foreach ($where as $key => $value) {
if (is_string($value) && strlen($value) > 0 && is_int($key)) {
$sql[] = "$value";
} else {
$sql[] = "$key = $value";
}
}
$rows = R::find($this->_table, implode(' AND ', $sql));
foreach ($rows as $row) {
R::trash($row);
}
}
/**
* Real Delete Model
* @return bool
*/
public function real_delete_all()
{
return R::wipe($this->_table);
}
/**
* Get All Validation Rules
*
* @param string $key
* @return array
*/
public function get_all_validation_rule()
{
return $this->_validation_rules;
}
/**
* Get All Allowed Rules
*
* @param string $key
* @return array
*/
public function get_all_allowed_fields()
{
return $this->_allowed_fields;
}
/**
* Get All Edit Validation Rules
*
* @param string $key
* @return array
*/
public function get_all_edit_validation_rule()
{
return $this->_validation_edit_rules;
}
/**
* Fill validation rules
*
* @param mixed $form_validation
* @param mixed $validation_rules
* @return void
*/
public function set_form_validation($form_validation, $validation_rules)
{
}
/**
* Count number of model
*
* @access public
* @param mixed $parameters
* @return integer $result
*/
public function count($parameters)
{
$sql = [];
foreach ($parameters as $key => $value) {
if (is_string($value) && strlen($value) > 0) {
$sql[] = "$key";
} else {
$sql[] = "$key = $value";
}
}
return R::count($this->_table, implode(' AND ', $sql));
}
/**
* Paginated
*
* @param integer $page
* @param integer $limit
* @param array $where
* @param string $order_by
* @param string $direction
* @return mixed
*/
public function get_paginated($page = 0, $limit = 25, $parameters = [], $order_by = '', $direction = 'ASC')
{
$sql = [];
$last_id = 0;
foreach ($parameters as $key => $value) {
if (is_string($value) && strlen($value) > 0 && is_numeric($key)) {
$sql[] = " $value ";
} else {
$sql[] = " `$key` = $value ";
}
}
// echo "<pre>";
// print_r( $sql);
// print_r( $parameters);
// die;
$total = R::count($this->_table, implode(' AND ', $sql));
$offset = ($page - 1) * $limit;
$limit_query = " ORDER BY $order_by $direction LIMIT $offset, $limit ";
$final_list = R::find($this->_table, implode(' AND ', $sql) . $limit_query);
//select MODE 2 to see parameters filled in
// R::fancyDebug(); //since 4.2
// $logs = R::getDatabaseAdapter()
// ->getDatabase()
// ->getLogger();
// echo "<pre>";
// print_r( $logs);
// die;
// echo "<pre>";
// print_r( $sql);
// print_r( implode(' AND ', $sql));
// $logs = R::getDatabaseAdapter()->getDatabase()->getLogger();
// print_r( $final_list);
// print_r( $logs);
// die;
if ($final_list) {
$last_id = $final_list[array_key_last($final_list)]['id'];
}
return [
'total' => $total,
'last_page' => ceil($total / $limit),
'page' => $page,
'id' => $last_id,
'data' => $final_list
];
}
/**
* Cursor Pagination
*
* @param integer $page
* @param integer $limit
* @param array $where
* @param string $order_by
* @param string $direction
* @return mixed
*/
public function get_cursor_paginated($page = 1, $limit = 25, $parameters = [], $order_by = '', $direction = 'ASC', $id)
{
$sql = [];
$last_id = 0;
foreach ($parameters as $key => $value) {
if (is_string($value) && strlen($value) > 0) {
$sql[] = "$key";
} else {
$sql[] = "$key = $value";
}
}
if (count($sql) < 1) {
$total = R::count($this->_table);
} else {
$total = R::count($this->_table, implode(' AND ', $sql));
}
$limit_query = " ORDER BY $order_by $direction LIMIT $limit";
$sql[] = 'id > ' . $id;
$final_list = R::find($this->_table, implode(' AND ', $sql) . $limit_query);
if ($final_list) {
$last_id = $final_list[array_key_last($final_list)]['id'];
}
$last_page = ceil($total / $limit);
return [
'total' => $total,
'size' => $limit,
'page' => $page,
'last_page' => $last_page,
'data' => $final_list,
'id' => $last_id
];
}
/**
* Join All
*
* @param string $table
* @param string $field
* @param array $where
* @param array $custom_duplicate_names
* @return void
*/
public function _join($table, $field, $where, $custom_duplicate_names = [])
{
}
/**
* Join Paginate
*
* @param string $table
* @param string $field
* @param array $where
* @param integer $page
* @param integer $limit
* @param string $order_by
* @param string $direction
* @param array $custom_duplicate_names
* @return mixed
*/
public function _join_paginate($table, $field, $where, $page = 0, $limit = 10, $order_by = '', $direction = 'ASC', $custom_duplicate_names = [])
{
}
/**
* Filter all keys before inserting to make sure they are allowed
*
* @param mixed $data
* @return mixed
*/
protected function _filter_allow_keys($data)
{
$clean_data = [];
$allowed_fields = $this->_allowed_fields;
$allowed_fields[] = $this->_primary_key;
if ($this->_use_timestamps) {
$allowed_fields[] = $this->_created_field;
$allowed_fields[] = $this->_updated_field;
}
foreach ($data as $key => $val) {
if (!in_array($key, $allowed_fields)) {
continue;
}
$clean_data[$key] = $val;
}
return $clean_data;
}
/**
* escapeLikeString data
*
* @param mixed $data
* @return mixed
*/
public function escapeLikeString($data)
{
}
/**
* Get Last ID in table
*
* @return integer
*/
public function get_last_id()
{
return FALSE;
}
/**
* Get Database Table Schema
*
* @return mixed
*/
public function get_schema()
{
return R::inspect($this->_table);
}
}