ano-mr-site/lib/php/DataBaseManager/Entitie.php

58 lines
2.8 KiB
PHP

<?php
namespace DataBaseManager\Entitie;
class Entitie
{
private array $column_array;
private string $table_name;
private string $create_table;
private string $delete_table;
private string $type_id;
private string $create;
private string $select;
private string $select_all;
private string $remove;
private string $clear;
private \Closure $create_all;
private \Closure $update;
private \Closure $update_by_condition;
public function __construct(array $column_array, string $table_name, string $type_id = "serial")
{
$this->column_array = $column_array;
$this->table_name = $table_name;
$this->type_id = $type_id;
$columns_sql = implode(", ", $this->column_array);
$column_names = implode(", ", array_map(fn($col) => explode(" ", $col)[0], $this->column_array));
$placeholders = implode(", ", array_fill(0, count($this->column_array), "?"));
$set_clause = implode(", ", array_map(fn($col) => explode(" ", $col)[0] . "=?", $this->column_array));
$this->create_table = "CREATE TABLE IF NOT EXISTS {$this->table_name} (id {$this->type_id}, {$columns_sql})";
$this->delete_table = "DROP TABLE IF EXISTS {$this->table_name}";
$this->create = "INSERT INTO {$this->table_name} ({$column_names}) VALUES ({$placeholders})";
$this->select = "SELECT * FROM {$this->table_name} WHERE id=?";
$this->select_all = "SELECT * FROM {$this->table_name}";
$this->remove = "DELETE FROM {$this->table_name} WHERE id=?";
$this->clear = "TRUNCATE TABLE {$this->table_name}";
$this->create_all = function($length) use ($placeholders, $column_names, $table_name) {
$placeholders_array = implode(", ", array_fill(0, $length, "({$placeholders})"));
return "INSERT INTO {$table_name} ({$column_names}) VALUES {$placeholders_array}";
};
$this->update = fn($id) => "UPDATE {$this->table_name} SET {$set_clause} WHERE id = ?";
$this->update_by_condition = fn($condition) => "UPDATE {$this->table_name} SET {$set_clause} WHERE {$condition}";
}
public function get_create_table(): string { return $this->create_table; }
public function get_delete_table(): string { return $this->delete_table; }
public function get_create(): string { return $this->create; }
public function get_select(): string { return $this->select; }
public function get_select_all(): string { return $this->select_all; }
public function get_remove(): string { return $this->remove; }
public function get_clear(): string { return $this->clear; }
public function get_create_all(): \Closure { return $this->create_all; }
public function get_update(): \Closure { return $this->update; }
public function get_update_by_condition(): \Closure { return $this->update_by_condition; }
}