From 175ef582895a1674636c5c7d15be4a9f7981dc17 Mon Sep 17 00:00:00 2001 From: Jagepard Date: Fri, 27 Jun 2025 17:47:16 +0300 Subject: [PATCH] add docs --- docs.md | 159 +++++++++++++++++---------------- src/Driver/MySQL.php | 37 ++++++++ src/Driver/PgSQL.php | 37 ++++++++ src/Driver/SQLite.php | 37 ++++++++ src/Entity.php | 25 ++++++ src/Model.php | 21 +++++ src/QB.php | 101 +++++++++++++++++++++ src/Repository.php | 201 +++++++++++++++++++++++++++++++++++++++--- src/Schema.php | 20 +++++ 9 files changed, 553 insertions(+), 85 deletions(-) diff --git a/docs.md b/docs.md index f0af7b3..0934fb2 100644 --- a/docs.md +++ b/docs.md @@ -7,6 +7,7 @@ - [Rudra\Model\QB](#rudra_model_qb) - [Rudra\Model\QBFacade](#rudra_model_qbfacade) - [Rudra\Model\Repository](#rudra_model_repository) +- [Rudra\Model\Schema](#rudra_model_schema)
@@ -14,14 +15,14 @@ ### Class: Rudra\Model\Driver\MySQL | Visibility | Function | |:-----------|:---------| -|public|concat( string $fieldName string $alias string $orderBy ): string
| -|public|close(): string
| -|public|integer( string $field string $default bool $autoincrement string $null ): string
| -|public|string( string $field string $default string $null ): string
| -|public|text( string $field string $null ): string
| -|public|created_at(): string
| -|public|updated_at(): string
| -|public|pk( $field ): string
| +| public | `concat(string $fieldName, string $alias, string $orderBy): string`
| +| public | `close(): string`
| +| public | `integer(string $field, string $default, bool $autoincrement, string $null): string`
| +| public | `string(string $field, string $default, string $null): string`
| +| public | `text(string $field, string $null): string`
| +| public | `created_at(): string`
| +| public | `updated_at(): string`
| +| public | `pk( $field): string`
| @@ -29,14 +30,14 @@ ### Class: Rudra\Model\Driver\PgSQL | Visibility | Function | |:-----------|:---------| -|public|concat( string $fieldName string $alias string $orderBy ): string
| -|public|close(): string
| -|public|integer( string $field string $default bool $pk string $null ): string
| -|public|string( string $field string $default string $null ): string
| -|public|text( string $field string $null ): string
| -|public|created_at(): string
| -|public|updated_at(): string
| -|public|pk( string $field ): string
| +| public | `concat(string $fieldName, string $alias, string $orderBy): string`
| +| public | `close(): string`
| +| public | `integer(string $field, string $default, bool $pk, string $null): string`
| +| public | `string(string $field, string $default, string $null): string`
| +| public | `text(string $field, string $null): string`
| +| public | `created_at(): string`
| +| public | `updated_at(): string`
| +| public | `pk(string $field): string`
| @@ -44,14 +45,14 @@ ### Class: Rudra\Model\Driver\SQLite | Visibility | Function | |:-----------|:---------| -|public|concat( string $fieldName string $alias string $orderBy ): string
| -|public|close(): string
| -|public|integer( string $field string $default bool $pk string $null ): string
| -|public|string( string $field string $default string $null ): string
| -|public|text( string $field string $null ): string
| -|public|created_at(): string
| -|public|updated_at(): string
| -|public|pk( string $field ): string
| +| public | `concat(string $fieldName, string $alias, string $orderBy): string`
| +| public | `close(): string`
| +| public | `integer(string $field, string $default, bool $pk, string $null): string`
| +| public | `string(string $field, string $default, string $null): string`
| +| public | `text(string $field, string $null): string`
| +| public | `created_at(): string`
| +| public | `updated_at(): string`
| +| public | `pk(string $field): string`
| @@ -59,9 +60,9 @@ ### Class: Rudra\Model\Entity | Visibility | Function | |:-----------|:---------| -|public static|__callStatic( $method array $parameters )
| -|public|__call( $method array $parameters )
| -|protected static|callMethod( $method array $parameters )
| +| public static | `__callStatic( $method, array $parameters)`
| +| public | `__call( $method, array $parameters)`
| +| protected static | `callMethod( $method, array $parameters)`
Dynamically calls a method on the corresponding Model, Repository, or parent Repository class.
The method first attempts to call the method on the Model class associated with the Entity.
If the Model does not exist, it falls back to the Repository class.
If the Repository does not exist, it defaults to the parent Repository class.
-------------------------
Динамически вызывает метод в соответствующем классе Model, Repository или родительском Repository.
Метод сначала пытается вызвать метод в классе Model, связанном с Entity.
Если Model не существует, используется класс Repository.
Если Repository не существует, используется родительский класс Repository. | @@ -69,8 +70,8 @@ ### Class: Rudra\Model\Model | Visibility | Function | |:-----------|:---------| -|public|__construct( string $table )
| -|public|__call( $method array $parameters )
| +| public | `__construct(?string $table)`
| +| public | `__call( $method, array $parameters)`
Handles calls to undefined methods by delegating them to the corresponding Repository class.
The method dynamically resolves the Repository class associated with the Model.
If the Repository does not exist, it falls back to the parent Repository class.
If the method exists in the resolved Repository, it is invoked with the provided parameters.
Otherwise, an exception is thrown.
-------------------------
Обрабатывает вызовы неопределённых методов, делегируя их соответствующему классу Repository.
Метод динамически определяет класс Repository, связанный с Model.
Если Repository не существует, используется родительский класс Repository.
Если метод существует в разрешённом Repository, он вызывается с предоставленными параметрами.
В противном случае выбрасывается исключение. | @@ -78,28 +79,28 @@ ### Class: Rudra\Model\QB | Visibility | Function | |:-----------|:---------| -|public|__construct( PDO $dsn )
| -|public|select( string $fields ): self
| -|public|concat( string $fieldName string $alias ?string $orderBy ): self
| -|public|from( string $table ): self
| -|public|where( string $param ): self
| -|public|and( string $param ): self
| -|public|or( string $param ): self
| -|public|limit( $param ): self
| -|public|offset( $param ): self
| -|public|orderBy( string $param ): self
| -|public|groupBy( string $param ): self
| -|public|join( string $param string $type ): self
| -|public|on( string $param ): self
| -|public|get(): string
| -|public|create( string $table ): self
| -|public|close(): self
| -|public|integer( string $field string $default bool $autoincrement string $null ): self
| -|public|string( string $field string $default string $null ): self
| -|public|text( string $field string $null ): self
| -|public|created_at(): self
| -|public|updated_at(): self
| -|public|pk( ?string $field ): self
| +| public | `__construct( $dsn)`
Initializes the database driver based on the provided DSN or a default DSN from the container.
If no DSN is provided and none is available in the container, a LogicException is thrown.
The driver is selected based on the database type specified in the DSN's driver attribute.
-------------------------
Инициализирует драйвер базы данных на основе предоставленного DSN или DSN по умолчанию из контейнера.
Если DSN не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException.
Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера DSN. | +| public | `select(string $fields): self`
| +| public | `concat(string $fieldName, string $alias, ?string $orderBy): self`
| +| public | `from(string $table): self`
| +| public | `where(string $param): self`
| +| public | `and(string $param): self`
| +| public | `or(string $param): self`
| +| public | `limit( $param): self`
| +| public | `offset( $param): self`
| +| public | `orderBy(string $param): self`
| +| public | `groupBy(string $param): self`
| +| public | `join(string $param, string $type): self`
| +| public | `on(string $param): self`
| +| public | `get(): string`
| +| public | `create(string $table): self`
| +| public | `close(): self`
| +| public | `integer(string $field, string $default, bool $autoincrement, string $null): self`
| +| public | `string(string $field, string $default, string $null): self`
| +| public | `text(string $field, string $null): self`
| +| public | `created_at(): self`
| +| public | `updated_at(): self`
| +| public | `pk(?string $field): self`
| @@ -107,7 +108,7 @@ ### Class: Rudra\Model\QBFacade | Visibility | Function | |:-----------|:---------| -|public static|__callStatic( string $method array $parameters ): mixed
| +| public static | `__callStatic(string $method, array $parameters): ?mixed`
Handles static method calls for the Facade class.
It dynamically resolves the underlying class name by removing "Facade" from the class name.
If the resolved class does not exist, it attempts to clean up the class name by removing spaces.
If the resolved class is not already registered in the container, it registers it.
Finally, it delegates the static method call to the resolved class instance.
-------------------------
Обрабатывает статические вызовы методов для класса Facade.
Динамически разрешает имя базового класса, удаляя "Facade" из имени класса.
Если разрешённый класс не существует, пытается очистить имя класса, удаляя пробелы.
Если разрешённый класс ещё не зарегистрирован в контейнере, он регистрируется.
В конце делегирует статический вызов метода экземпляру разрешённого класса. | @@ -115,28 +116,38 @@ ### Class: Rudra\Model\Repository | Visibility | Function | |:-----------|:---------| -|public|__construct( string $table ?PDO $dsn )
| -|public|__call( $method array $parameters )
| -|private|getQB(): Rudra\Model\QB
| -|public|onDsn( PDO $dsn ): self
| -|public|withDsn( PDO $dsn ): self
| -|public|qBuilder( $queryString array $queryParams ): array
Represents a prepared database query and, when the query is executed, the corresponding result set.
Представляет подготовленный запрос к базе данных, а после выполнения запроса соответствующий результирующий набор. | -|public|getAllPerPage( Rudra\Pagination $pagination ?string $fields )
| -|public|find( $id ): array|false
| -|public|getAll( string $sort ?string $fields )
| -|public|numRows()
| -|public|findBy( $field $value )
| -|public|lastInsertId()
| -|public|update( array $fields )
| -|public|create( array $fields )
| -|public|delete( $id )
| -|protected static|updateStmtString( array $fields )
Prepares a row to update the database| -|protected static|createStmtString( array $fields )
Prepares a row to be added to the database| -|public|getColumns()
| -|public|getFields( ?string $fields )
| -|public|search( string $search string $column ?string $fields )
| -|public|toggle()
Helper method for writing a toggle| -|public|qCache( array $params $cacheTime )
| +| public | `__construct(?string $table, ?PDO $dsn)`
Initializes the class with a table name, DSN (Data Source Name), and sets up dependencies.
The DSN is either provided directly or retrieved from the Rudra container.
If the DSN is not an instance of PDO, a LogicException is thrown.
-------------------------
Инициализирует класс с именем таблицы, DSN (Data Source Name) и настраивает зависимости.
DSN может быть предоставлен напрямую или извлечен из контейнера Rudra.
Если DSN не является экземпляром PDO, выбрасывается исключение LogicException. | +| public | `__call( $method, array $parameters)`
Handles calls to undefined methods by throwing a LogicException.
This method is invoked when an attempt is made to call a non-existent method on the object.
-------------------------
Обрабатывает вызовы неопределённых методов, выбрасывая исключение LogicException.
Этот метод вызывается, когда происходит попытка вызвать несуществующий метод у объекта. | +| public | `qb(): Rudra\Model\QB`
Returns an instance of the Query Builder (QB).
If the QB instance is not yet initialized, it creates a new instance using the DSN.
This method implements lazy initialization to ensure the QB instance is created only when needed.
-------------------------
Возвращает экземпляр Query Builder (QB).
Если экземпляр QB ещё не инициализирован, создаётся новый экземпляр с использованием DSN.
Этот метод реализует ленивую инициализацию, чтобы гарантировать создание экземпляра QB только при необходимости. | +| public | `onDsn(PDO $dsn): self`
Sets the DSN (Data Source Name) for the database connection and resets the Query Builder instance.
This method allows changing the DSN dynamically and ensures that the Query Builder is re-initialized.
-------------------------
Устанавливает DSN (Data Source Name) для подключения к базе данных и сбрасывает экземпляр Query Builder.
Этот метод позволяет динамически изменять DSN и гарантирует повторную инициализацию Query Builder. | +| public | `withDsn(PDO $dsn): self`
Creates and returns a new instance of the class with the specified DSN.
This method allows changing the DSN while preserving the current table name.
It is useful for creating new instances with different database connections without modifying the original object.
-------------------------
Создает и возвращает новый экземпляр класса с указанным DSN.
Этот метод позволяет изменить DSN, сохраняя текущее имя таблицы.
Он полезен для создания новых экземпляров с разными подключениями к базе данных без изменения исходного объекта. | +| public | `qBuilder( $queryString, array $queryParams): array`
Executes a custom SQL query and returns the result as an associative array.
The method prepares the query, executes it with optional parameters, and fetches all results.
-------------------------
Выполняет пользовательский SQL-запрос и возвращает результат в виде ассоциативного массива.
Метод подготавливает запрос, выполняет его с необязательными параметрами и извлекает все результаты. | +| public | `getAllPerPage(Rudra\Pagination $pagination, ?string $fields)`
| +| public | `find( $id): array\|false`
| +| public | `getAll(string $sort, ?string $fields)`
| +| public | `numRows()`
| +| public | `findBy( $field, $value)`
| +| public | `lastInsertId()`
| +| public | `update(array $fields)`
| +| public | `create(array $fields)`
| +| public | `delete( $id)`
| +| protected static | `updateStmtString(array $fields)`
Generates a string of fields and placeholders for an SQL UPDATE statement.
The method takes an array of fields and constructs a comma-separated list of "key=:key" pairs.
This string can be directly used in the SET clause of an SQL UPDATE query.
-------------------------
Генерирует строку полей и плейсхолдеров для SQL-запроса UPDATE.
Метод принимает массив полей и формирует список пар "ключ=:ключ", разделённый запятыми.
Эта строка может быть напрямую использована в SET-части SQL-запроса UPDATE. | +| protected static | `createStmtString(array $fields)`
Generates two strings for an SQL INSERT statement: one for column names and one for placeholders.
The method takes an array of fields and constructs two comma-separated lists:
- A list of column names.
- A list of placeholders (prefixed with colons) for parameter binding.
These strings can be directly used in the SQL INSERT query.
-------------------------
Генерирует две строки для SQL-запроса INSERT:
- Список имен столбцов.
- Список плейсхолдеров (с префиксом двоеточия) для связывания параметров.
Эти строки могут быть напрямую использованы в SQL-запросе INSERT. | +| public | `getColumns()`
Retrieves the column information for the current table based on the database driver.
The method executes a query specific to the database type (MySQL, PostgreSQL, or SQLite)
to fetch the column details of the table.
-------------------------
Получает информацию о столбцах текущей таблицы в зависимости от типа базы данных.
Метод выполняет запрос, специфичный для используемой СУБД (MySQL, PostgreSQL или SQLite),
чтобы получить сведения о столбцах таблицы. | +| public | `getFields(?string $fields)`
Retrieves the list of fields (columns) for the current table.
If no specific fields are provided, the method fetches all column names based on the database driver.
Otherwise, it splits the provided comma-separated string of fields into an array.
-------------------------
Получает список полей (столбцов) для текущей таблицы.
Если конкретные поля не указаны, метод извлекает все имена столбцов в зависимости от типа базы данных.
В противном случае он разделяет предоставленную строку полей, разделённых запятыми, на массив. | +| public | `search(string $search, string $column, ?string $fields)`
Searches for records in the database based on a search term and column.
The method prepares and executes a query to retrieve records where the specified column matches the search term.
Results are ordered by ID in descending order and limited to 10 records.
-------------------------
Выполняет поиск записей в базе данных на основе поискового запроса и указанного столбца.
Метод подготавливает и выполняет запрос для получения записей, где указанный столбец соответствует поисковому запросу.
Результаты сортируются по ID в порядке убывания и ограничиваются 10 записями. | +| public | `toggle()`
| +| public | `cache(array $params, $cacheTime)`
Caches the result of a method call to a JSON file for a specified duration.
If the cached file exists and is still valid (based on cache time), the cached data is returned.
Otherwise, the method executes the specified method, caches its result, and returns the data.
-------------------------
Кэширует результат вызова метода в JSON-файл на определённый период времени.
Если кэшированный файл существует и всё ещё действителен (на основе времени кэширования), возвращаются кэшированные данные.
В противном случае метод выполняет указанный метод, кэширует его результат и возвращает данные. | +| public | `clearCache(string $type)`
Clears cached files of a specified type or all types.
The method removes JSON cache files from the 'database' or 'view' directories,
or clears both directories if 'all' is specified.
-------------------------
Очищает кэшированные файлы указанного типа или всех типов.
Метод удаляет JSON-файлы кэша из директорий 'database' или 'view',
или очищает обе директории, если указано значение 'all'. | + + + + +### Class: Rudra\Model\Schema +| Visibility | Function | +|:-----------|:---------| +| public static | `create(string $table, callable $callback): self`
Creates a new Schema instance and defines the table structure using a callback function.
The callback function is used to configure the table schema via the Query Builder.
-------------------------
Создает новый экземпляр Schema и определяет структуру таблицы с помощью callback-функции.
Callback-функция используется для настройки схемы таблицы через Query Builder. | +| public | `execute(): bool`
Executes the schema creation by preparing and running the SQL query.
The SQL query is generated using the Query Builder and executed on the database connection.
-------------------------
Выполняет создание схемы путем подготовки и выполнения SQL-запроса.
SQL-запрос генерируется с использованием Query Builder и выполняется на подключении к базе данных. |
###### created with [Rudra-Documentation-Collector](#https://github.com/Jagepard/Rudra-Documentation-Collector) diff --git a/src/Driver/MySQL.php b/src/Driver/MySQL.php index 8c76d89..714a873 100755 --- a/src/Driver/MySQL.php +++ b/src/Driver/MySQL.php @@ -11,16 +11,32 @@ class MySQL { + /** + * @param string $fieldName + * @param string $alias + * @param string $orderBy + * @return string + */ public function concat(string $fieldName, string $alias, string $orderBy): string { return ", GROUP_CONCAT($fieldName ORDER BY $orderBy SEPARATOR ';') as $alias "; } + /** + * @return string + */ public function close(): string { return ") ENGINE = InnoDB"; } + /** + * @param string $field + * @param string $default + * @param boolean $autoincrement + * @param string $null + * @return string + */ public function integer(string $field, string $default = "", bool $autoincrement = false, string $null = "NOT NULL"): string { if ($autoincrement) { @@ -30,26 +46,47 @@ public function integer(string $field, string $default = "", bool $autoincrement return ", `$field` INT $null $default"; } + /** + * @param string $field + * @param string $default + * @param string $null + * @return string + */ public function string(string $field, string $default = "", string $null = "NOT NULL"): string { return ", `$field` VARCHAR(255) $null $default"; } + /** + * @param string $field + * @param string $null + * @return string + */ public function text(string $field, string $null = "NOT NULL"): string { return ", `$field` text $null"; } + /** + * @return string + */ public function created_at(): string { return ", `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"; } + /** + * @return string + */ public function updated_at(): string { return ", `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"; } + /** + * @param $field + * @return string + */ public function pk($field): string { return ", PRIMARY KEY (`$field`)"; diff --git a/src/Driver/PgSQL.php b/src/Driver/PgSQL.php index ade8f1e..f0068eb 100755 --- a/src/Driver/PgSQL.php +++ b/src/Driver/PgSQL.php @@ -11,16 +11,32 @@ class PgSQL { + /** + * @param string $fieldName + * @param string $alias + * @param string $orderBy + * @return string + */ public function concat(string $fieldName, string $alias, string $orderBy): string { return ", array_to_string(array_agg($fieldName ORDER BY $orderBy), ';') $alias "; } + /** + * @return string + */ public function close(): string { return ");"; } + /** + * @param string $field + * @param string $default + * @param boolean $pk + * @param string $null + * @return string + */ public function integer(string $field, string $default = "", bool $pk = false, string $null = "NOT NULL"): string { if ($pk) { @@ -30,26 +46,47 @@ public function integer(string $field, string $default = "", bool $pk = false, s return ", $field INTEGER $null $default"; } + /** + * @param string $field + * @param string $default + * @param string $null + * @return string + */ public function string(string $field, string $default = "", string $null = "NOT NULL"): string { return ", $field VARCHAR(255) $null $default"; } + /** + * @param string $field + * @param string $null + * @return string + */ public function text(string $field, string $null = "NOT NULL"): string { return ", $field TEXT $null"; } + /** + * @return string + */ public function created_at(): string { return ", created_at TIMESTAMP without time zone"; } + /** + * @return string + */ public function updated_at(): string { return ", updated_at TIMESTAMP without time zone"; } + /** + * @param string $field + * @return string + */ public function pk(string $field): string { return ""; diff --git a/src/Driver/SQLite.php b/src/Driver/SQLite.php index 25a8d98..b5f6a24 100755 --- a/src/Driver/SQLite.php +++ b/src/Driver/SQLite.php @@ -11,16 +11,32 @@ class SQLite { + /** + * @param string $fieldName + * @param string $alias + * @param string $orderBy + * @return string + */ public function concat(string $fieldName, string $alias, string $orderBy): string { return ", GROUP_CONCAT($fieldName,';') $alias "; } + /** + * @return string + */ public function close(): string { return ")"; } + /** + * @param string $field + * @param string $default + * @param boolean $pk + * @param string $null + * @return string + */ public function integer(string $field, string $default = "", bool $pk = false, string $null = "NOT NULL"): string { if ($pk) { @@ -30,26 +46,47 @@ public function integer(string $field, string $default = "", bool $pk = false, s return ", $field INTEGER $null $default"; } + /** + * @param string $field + * @param string $default + * @param string $null + * @return string + */ public function string(string $field, string $default = "", string $null = "NOT NULL"): string { return ", $field TEXT $null $default"; } + /** + * @param string $field + * @param string $null + * @return string + */ public function text(string $field, string $null = "NOT NULL"): string { return ", $field TEXT $null"; } + /** + * @return string + */ public function created_at(): string { return ", created_at TEXT DEFAULT CURRENT_TIMESTAMP"; } + /** + * @return string + */ public function updated_at(): string { return ", updated_at TEXT DEFAULT CURRENT_TIMESTAMP"; } + /** + * @param string $field + * @return string + */ public function pk(string $field): string { return ""; diff --git a/src/Entity.php b/src/Entity.php index 0b0db2f..6a7bebe 100755 --- a/src/Entity.php +++ b/src/Entity.php @@ -13,16 +13,41 @@ class Entity { public static ?string $table = null; + /** + * @param $method + * @param array $parameters + * @return void + */ public static function __callStatic($method, array $parameters = []) { return self::callMethod($method, $parameters); } + /** + * @param $method + * @param array $parameters + * @return void + */ public function __call($method, array $parameters = []) { return self::callMethod($method, $parameters); } + /** + * Dynamically calls a method on the corresponding Model, Repository, or parent Repository class. + * The method first attempts to call the method on the Model class associated with the Entity. + * If the Model does not exist, it falls back to the Repository class. + * If the Repository does not exist, it defaults to the parent Repository class. + * ------------------------- + * Динамически вызывает метод в соответствующем классе Model, Repository или родительском Repository. + * Метод сначала пытается вызвать метод в классе Model, связанном с Entity. + * Если Model не существует, используется класс Repository. + * Если Repository не существует, используется родительский класс Repository. + * + * @param $method + * @param array $parameters + * @return void + */ protected static function callMethod($method, array $parameters) { $className = str_replace("Entity", "Model", get_called_class()); diff --git a/src/Model.php b/src/Model.php index 1204313..d95eee5 100755 --- a/src/Model.php +++ b/src/Model.php @@ -15,11 +15,32 @@ class Model { public ?string $table; + /** + * @param string|null $table + */ public function __construct(?string $table = null) { $this->table = $table; } + /** + * Handles calls to undefined methods by delegating them to the corresponding Repository class. + * The method dynamically resolves the Repository class associated with the Model. + * If the Repository does not exist, it falls back to the parent Repository class. + * If the method exists in the resolved Repository, it is invoked with the provided parameters. + * Otherwise, an exception is thrown. + * ------------------------- + * Обрабатывает вызовы неопределённых методов, делегируя их соответствующему классу Repository. + * Метод динамически определяет класс Repository, связанный с Model. + * Если Repository не существует, используется родительский класс Repository. + * Если метод существует в разрешённом Repository, он вызывается с предоставленными параметрами. + * В противном случае выбрасывается исключение. + * + * @param $method + * @param array $parameters + * @return void + * @throws RudraException + */ public function __call($method, array $parameters = []) { $className = str_replace("Model", "Repository", get_called_class()) . "Repository"; diff --git a/src/QB.php b/src/QB.php index 146bc6a..715dbae 100755 --- a/src/QB.php +++ b/src/QB.php @@ -20,6 +20,18 @@ class QB private $driver; private string $query = ''; + /** + * Initializes the database driver based on the provided DSN or a default DSN from the container. + * If no DSN is provided and none is available in the container, a LogicException is thrown. + * The driver is selected based on the database type specified in the DSN's driver attribute. + * ------------------------- + * Инициализирует драйвер базы данных на основе предоставленного DSN или DSN по умолчанию из контейнера. + * Если DSN не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException. + * Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера DSN. + * + * @param $dsn + * @throws LogicException + */ public function __construct($dsn = null) { $dsn = $dsn ?? Rudra::get('DSN') ?? throw new LogicException("DSN is mot installed"); @@ -33,78 +45,132 @@ public function __construct($dsn = null) } } + /** + * @param string $fields + * @return self + */ public function select(string $fields = '*'): self { $this->query .= "SELECT {$fields} "; return $this; } + /** + * @param string $fieldName + * @param string $alias + * @param string|null $orderBy + * @return self + */ public function concat(string $fieldName, string $alias, ?string $orderBy = null): self { $this->query .= $this->driver->concat($fieldName, $alias, $orderBy); return $this; } + /** + * @param string $table + * @return self + */ public function from(string $table): self { $this->query .= "FROM {$table} "; return $this; } + /** + * @param string $param + * @return self + */ public function where(string $param): self { $this->query .= "WHERE $param "; return $this; } + /** + * @param string $param + * @return self + */ public function and(string $param): self { $this->query .= "AND $param "; return $this; } + /** + * @param string $param + * @return self + */ public function or(string $param): self { $this->query .= "OR $param "; return $this; } + /** + * @param $param + * @return self + */ public function limit($param): self { $this->query .= "LIMIT $param "; return $this; } + /** + * @param $param + * @return self + */ public function offset($param): self { $this->query .= "OFFSET $param "; return $this; } + /** + * @param string $param + * @return self + */ public function orderBy(string $param): self { $this->query .= "ORDER BY $param "; return $this; } + /** + * @param string $param + * @return self + */ public function groupBy(string $param): self { $this->query .= "GROUP BY $param "; return $this; } + /** + * @param string $param + * @param string $type + * @return self + */ public function join(string $param, string $type = "LEFT"): self { $this->query .= "$type JOIN $param "; return $this; } + /** + * @param string $param + * @return self + */ public function on(string $param): self { $this->query .= "ON $param "; return $this; } + /** + * @return string + */ public function get(): string { $result = $this->query . ';'; @@ -113,48 +179,83 @@ public function get(): string return $result; } + /** + * @param string $table + * @return self + */ public function create(string $table): self { $this->query .= "CREATE TABLE {$table} ("; return $this; } + /** + * @return self + */ public function close(): self { $this->query .= $this->driver->close(); return $this; } + /** + * @param string $field + * @param string $default + * @param boolean $autoincrement + * @param string $null + * @return self + */ public function integer(string $field, string $default = "", bool $autoincrement = false, string $null = "NOT NULL"): self { $this->query .= $this->driver->integer($field, $default, $autoincrement, $null); return $this; } + /** + * @param string $field + * @param string $default + * @param string $null + * @return self + */ public function string(string $field, string $default = "", string $null = "NOT NULL"): self { $this->query .= $this->driver->string($field, $default, $null); return $this; } + /** + * @param string $field + * @param string $null + * @return self + */ public function text(string $field, string $null = "NOT NULL"): self { $this->query .= $this->driver->text($field, $null); return $this; } + /** + * @return self + */ public function created_at(): self { $this->query .= $this->driver->created_at(); return $this; } + /** + * @return self + */ public function updated_at(): self { $this->query .= $this->driver->updated_at(); return $this; } + /** + * @param string|null $field + * @return self + */ public function pk(?string $field = null): self { $this->query .= $this->driver->pk($field); diff --git a/src/Repository.php b/src/Repository.php index cf9d00d..7d3a776 100755 --- a/src/Repository.php +++ b/src/Repository.php @@ -22,6 +22,20 @@ class Repository private \PDO $dsn; private QB $qb; + /** + * Initializes the class with a table name, DSN (Data Source Name), and sets up dependencies. + * The DSN is either provided directly or retrieved from the Rudra container. + * If the DSN is not an instance of PDO, a LogicException is thrown. + * ------------------------- + * Инициализирует класс с именем таблицы, DSN (Data Source Name) и настраивает зависимости. + * DSN может быть предоставлен напрямую или извлечен из контейнера Rudra. + * Если DSN не является экземпляром PDO, выбрасывается исключение LogicException. + * + * @param string|null $table + * @param \PDO|null $dsn + * @return void + * @throws LogicException + */ public function __construct(?string $table, ?\PDO $dsn = null) { $this->table = $table; @@ -34,11 +48,34 @@ public function __construct(?string $table, ?\PDO $dsn = null) } } + /** + * Handles calls to undefined methods by throwing a LogicException. + * This method is invoked when an attempt is made to call a non-existent method on the object. + * ------------------------- + * Обрабатывает вызовы неопределённых методов, выбрасывая исключение LogicException. + * Этот метод вызывается, когда происходит попытка вызвать несуществующий метод у объекта. + * + * @param string $method + * @param array $parameters + * @return void + * @throws LogicException + */ public function __call($method, array $parameters = []) { throw new LogicException(sprintf('Method %s does not exists', $method)); } + /** + * Returns an instance of the Query Builder (QB). + * If the QB instance is not yet initialized, it creates a new instance using the DSN. + * This method implements lazy initialization to ensure the QB instance is created only when needed. + * ------------------------- + * Возвращает экземпляр Query Builder (QB). + * Если экземпляр QB ещё не инициализирован, создаётся новый экземпляр с использованием DSN. + * Этот метод реализует ленивую инициализацию, чтобы гарантировать создание экземпляра QB только при необходимости. + * + * @return QB + */ public function qb(): QB { if ($this->qb === null) { @@ -48,6 +85,16 @@ public function qb(): QB return $this->qb; } + /** + * Sets the DSN (Data Source Name) for the database connection and resets the Query Builder instance. + * This method allows changing the DSN dynamically and ensures that the Query Builder is re-initialized. + * ------------------------- + * Устанавливает DSN (Data Source Name) для подключения к базе данных и сбрасывает экземпляр Query Builder. + * Этот метод позволяет динамически изменять DSN и гарантирует повторную инициализацию Query Builder. + * + * @param \PDO $dsn + * @return self + */ public function onDsn(\PDO $dsn): self { $this->dsn = $dsn; @@ -56,19 +103,33 @@ public function onDsn(\PDO $dsn): self return $this; } + /** + * Creates and returns a new instance of the class with the specified DSN. + * This method allows changing the DSN while preserving the current table name. + * It is useful for creating new instances with different database connections without modifying the original object. + * ------------------------- + * Создает и возвращает новый экземпляр класса с указанным DSN. + * Этот метод позволяет изменить DSN, сохраняя текущее имя таблицы. + * Он полезен для создания новых экземпляров с разными подключениями к базе данных без изменения исходного объекта. + * + * @param \PDO $dsn + * @return self + */ public function withDsn(\PDO $dsn): self { return new static($this->table, $dsn); } /** - * Represents a prepared database query and, when the query is executed, the corresponding result set. - * --------------------------------------------------------------------------------------------------- - * Представляет подготовленный запрос к базе данных, а после выполнения запроса соответствующий результирующий набор. + * Executes a custom SQL query and returns the result as an associative array. + * The method prepares the query, executes it with optional parameters, and fetches all results. + * ------------------------- + * Выполняет пользовательский SQL-запрос и возвращает результат в виде ассоциативного массива. + * Метод подготавливает запрос, выполняет его с необязательными параметрами и извлекает все результаты. * - * @param $queryString - * @param array $queryParams - * @return void + * @param string $queryString + * @param array $queryParams + * @return array */ public function qBuilder($queryString, array $queryParams = []): array { @@ -78,6 +139,11 @@ public function qBuilder($queryString, array $queryParams = []): array return $stmt->fetchAll(\PDO::FETCH_ASSOC); } + /** + * @param Pagination $pagination + * @param string|null $fields + * @return array + */ public function getAllPerPage(Pagination $pagination, string $fields = null) { $fields = !isset($fields) ? implode(',', $this->getFields($fields)) : $fields; @@ -90,6 +156,10 @@ public function getAllPerPage(Pagination $pagination, string $fields = null) return $this->qBuilder($qString); } + /** + * @param int|string $id + * @return array|false + */ public function find($id): array|false { $stmt = $this->dsn->prepare(" @@ -104,6 +174,11 @@ public function find($id): array|false return $stmt->fetch(\PDO::FETCH_ASSOC); } + /** + * @param string $sort + * @param string|null $fields + * @return void + */ public function getAll(string $sort = 'id ASC', string $fields = null) { $fields = !isset($fields) ? implode(',', $this->getFields($fields)) : $fields; @@ -116,6 +191,7 @@ public function getAll(string $sort = 'id ASC', string $fields = null) return self::qBuilder($qString); } + public function numRows() { $table = $this->table; @@ -124,6 +200,11 @@ public function numRows() return $count->fetchColumn(); } + /** + * @param $field + * @param $value + * @return void + */ public function findBy($field, $value) { $table = $this->table; @@ -144,6 +225,10 @@ public function lastInsertId() return $this->dsn->lastInsertId(); } + /** + * @param array $fields + * @return void + */ public function update(array $fields) { $id = $fields['id']; @@ -159,6 +244,10 @@ public function update(array $fields) $this->clearCache(); } + /** + * @param array $fields + * @return void + */ public function create(array $fields) { $table = $this->table; @@ -172,6 +261,10 @@ public function create(array $fields) $this->clearCache(); } + /** + * @param $id + * @return void + */ public function delete($id) { $table = $this->table; @@ -181,10 +274,16 @@ public function delete($id) } /** - * Prepares a row to update the database + * Generates a string of fields and placeholders for an SQL UPDATE statement. + * The method takes an array of fields and constructs a comma-separated list of "key=:key" pairs. + * This string can be directly used in the SET clause of an SQL UPDATE query. + * ------------------------- + * Генерирует строку полей и плейсхолдеров для SQL-запроса UPDATE. + * Метод принимает массив полей и формирует список пар "ключ=:ключ", разделённый запятыми. + * Эта строка может быть напрямую использована в SET-части SQL-запроса UPDATE. * * @param array $fields - * @return void + * @return string */ protected static function updateStmtString(array $fields) { @@ -198,10 +297,19 @@ protected static function updateStmtString(array $fields) } /** - * Prepares a row to be added to the database + * Generates two strings for an SQL INSERT statement: one for column names and one for placeholders. + * The method takes an array of fields and constructs two comma-separated lists: + * - A list of column names. + * - A list of placeholders (prefixed with colons) for parameter binding. + * These strings can be directly used in the SQL INSERT query. + * ------------------------- + * Генерирует две строки для SQL-запроса INSERT: + * - Список имен столбцов. + * - Список плейсхолдеров (с префиксом двоеточия) для связывания параметров. + * Эти строки могут быть напрямую использованы в SQL-запросе INSERT. * * @param array $fields - * @return void + * @return array */ protected static function createStmtString(array $fields) { @@ -216,6 +324,18 @@ protected static function createStmtString(array $fields) return [implode(",", $insert), implode(",", $execute)]; } + /** + * Retrieves the column information for the current table based on the database driver. + * The method executes a query specific to the database type (MySQL, PostgreSQL, or SQLite) + * to fetch the column details of the table. + * ------------------------- + * Получает информацию о столбцах текущей таблицы в зависимости от типа базы данных. + * Метод выполняет запрос, специфичный для используемой СУБД (MySQL, PostgreSQL или SQLite), + * чтобы получить сведения о столбцах таблицы. + * + * @return array + * @throws \PDOException + */ public function getColumns() { $table = $this->table; @@ -235,6 +355,18 @@ public function getColumns() return $query->fetchAll(\PDO::FETCH_ASSOC); } + /** + * Retrieves the list of fields (columns) for the current table. + * If no specific fields are provided, the method fetches all column names based on the database driver. + * Otherwise, it splits the provided comma-separated string of fields into an array. + * ------------------------- + * Получает список полей (столбцов) для текущей таблицы. + * Если конкретные поля не указаны, метод извлекает все имена столбцов в зависимости от типа базы данных. + * В противном случае он разделяет предоставленную строку полей, разделённых запятыми, на массив. + * + * @param string|null $fields + * @return array + */ public function getFields(string $fields = null) { if (!isset($fields)) { @@ -258,6 +390,20 @@ public function getFields(string $fields = null) return $fields; } + /** + * Searches for records in the database based on a search term and column. + * The method prepares and executes a query to retrieve records where the specified column matches the search term. + * Results are ordered by ID in descending order and limited to 10 records. + * ------------------------- + * Выполняет поиск записей в базе данных на основе поискового запроса и указанного столбца. + * Метод подготавливает и выполняет запрос для получения записей, где указанный столбец соответствует поисковому запросу. + * Результаты сортируются по ID в порядке убывания и ограничиваются 10 записями. + * + * @param string $search + * @param string $column + * @param string|null $fields + * @return array + */ public function search(string $search, string $column, string $fields = null) { $table = $this->table; @@ -278,7 +424,15 @@ public function search(string $search, string $column, string $fields = null) /** * @deprecated - * Helper method for writing a toggle + * Helper method for writing a toggle. + * This method processes a toggle request, validates input data, updates the status of a record, + * and redirects to the specified URL. + * ------------------------- + * Вспомогательный метод для обработки переключения (toggle). + * Этот метод обрабатывает запрос на переключение, проверяет входные данные, обновляет статус записи + * и выполняет перенаправление на указанный URL. + * + * @return void */ public function toggle() { @@ -311,6 +465,19 @@ public function toggle() } } + /** + * Caches the result of a method call to a JSON file for a specified duration. + * If the cached file exists and is still valid (based on cache time), the cached data is returned. + * Otherwise, the method executes the specified method, caches its result, and returns the data. + * ------------------------- + * Кэширует результат вызова метода в JSON-файл на определённый период времени. + * Если кэшированный файл существует и всё ещё действителен (на основе времени кэширования), возвращаются кэшированные данные. + * В противном случае метод выполняет указанный метод, кэширует его результат и возвращает данные. + * + * @param array $params + * @param string|null $cacheTime + * @return mixed + */ public function cache(array $params, $cacheTime = null) { $directory = dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'database'; @@ -332,6 +499,18 @@ public function cache(array $params, $cacheTime = null) return $data; } + /** + * Clears cached files of a specified type or all types. + * The method removes JSON cache files from the 'database' or 'view' directories, + * or clears both directories if 'all' is specified. + * ------------------------- + * Очищает кэшированные файлы указанного типа или всех типов. + * Метод удаляет JSON-файлы кэша из директорий 'database' или 'view', + * или очищает обе директории, если указано значение 'all'. + * + * @param string $type + * @return void + */ public function clearCache(string $type = 'database') { $baseDir = dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR; diff --git a/src/Schema.php b/src/Schema.php index 01e4659..f23dbd8 100644 --- a/src/Schema.php +++ b/src/Schema.php @@ -15,6 +15,17 @@ class Schema { private QB $qb; + /** + * Creates a new Schema instance and defines the table structure using a callback function. + * The callback function is used to configure the table schema via the Query Builder. + * ------------------------- + * Создает новый экземпляр Schema и определяет структуру таблицы с помощью callback-функции. + * Callback-функция используется для настройки схемы таблицы через Query Builder. + * + * @param string $table + * @param callable $callback + * @return self + */ public static function create(string $table, callable $callback): self { $qb = Entity::qb()->create($table); @@ -24,6 +35,15 @@ public static function create(string $table, callable $callback): self return $self; } + /** + * Executes the schema creation by preparing and running the SQL query. + * The SQL query is generated using the Query Builder and executed on the database connection. + * ------------------------- + * Выполняет создание схемы путем подготовки и выполнения SQL-запроса. + * SQL-запрос генерируется с использованием Query Builder и выполняется на подключении к базе данных. + * + * @return bool + */ public function execute(): bool { $sql = $this->qb->close()->get();