Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 45 additions & 45 deletions src/Builder/Concerns/ProxyMethods.php

Large diffs are not rendered by default.

125 changes: 125 additions & 0 deletions src/Commands/Generators/Model.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<?php

/**
* This file is part of Blitz PHP framework - Database Layer.
*
* (c) 2022 Dimitri Sitchet Tomkeu <devcode.dst@gmail.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace BlitzPHP\Database\Commands\Generators;

use BlitzPHP\Cli\Commands\Generators\GeneratorCommand;
use BlitzPHP\Utilities\Helpers;

/**
* Génère un squelette de fichier de modèle.
*/
class Model extends GeneratorCommand
{
/**
* {@inheritDoc}
*/
protected string $name = 'make:model';

/**
* {@inheritDoc}
*/
protected string $description = 'Génère un nouveau fichier de modèle.';

/**
* {@inheritDoc}
*/
protected array $arguments = [
'name' => 'Le nom de la classe de modèle',
];

/**
* {@inheritDoc}
*/
protected array $options = [
'--table' => ['Indiquez un nom de table. Par défaut : "le pluriel en minuscules du nom de la classe".'],
'--dbgroup' => ['Groupe de base de données à utiliser.'],
'--return' => ['Définit le type de retour des résultats, Options: [array, object, entity].', 'array'],
'--namespace' => ['Définit le namespace du modèle.', APP_NAMESPACE],
'--suffix' => 'Ajoute "Model" au nom de la classe (par exemple, User => UserModel).',
'--force' => 'Forcer l\'écrasement du fichier existant.',
];

/**
* {@inheritDoc}
*/
protected string $component = 'Model';

/**
* {@inheritDoc}
*/
protected string $directory = 'Models';

/**
* {@inheritDoc}
*/
protected string $templatePath = __DIR__ . '/Views';

/**
* {@inheritDoc}
*/
protected string $template = 'model.tpl.php';

/**
* {@inheritDoc}
*/
protected string $classNameLang = 'CLI.generator.className.model';

/**
* {@inheritDoc}
*/
protected function prepare(string $class): string
{
$table = $this->option('table');
$dbGroup = $this->option('dbgroup');
$return = $this->option('return', 'array');

$baseClass = Helpers::classBasename($class);

if (preg_match('/^(\S+)Model$/i', $baseClass, $match) === 1) {
$baseClass = $match[1];
}

helper('inflector');

$table = is_string($table) ? $table : plural(strtolower($baseClass));

if (! in_array($return, ['array', 'object', 'entity'], true)) {
$return = $this->choice(lang('CLI.generator.returnType'), ['array', 'object', 'entity'], 'array');
$this->newLine();
}

if ($return === 'entity') {
$return = str_replace('Models', 'Entities', $class);

if (preg_match('/^(\S+)Model$/i', $return, $match) === 1) {
$return = $match[1];

if ($this->option('suffix')) {
$return .= 'Entity';
}
}

$return = '\\' . trim($return, '\\') . '::class';

if ($this->commandExists('make:entity')) {
$this->call('make:entity', ['name' => $baseClass], [
'--namespace' => $this->option('namespace'),
'--suffix' => $this->option('suffix'),
]);
}
} else {
$return = "'{$return}'";
}

return $this->parseTemplate($class, ['{dbGroup}', '{table}', '{return}'], [$dbGroup, $table, $return], compact('dbGroup'));
}
}
49 changes: 49 additions & 0 deletions src/Commands/Generators/Views/model.tpl.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<@php

namespace {namespace};

use BlitzPHP\Database\Model;

class {class} extends Model
{
<?php if (is_string($dbGroup)): ?>
protected ?string $group = '{dbGroup}';
<?php endif; ?>
protected string $table = '{table}';
protected string $primaryKey = 'id';
protected bool $useAutoIncrement = true;
protected string $returnType = {return};
protected bool $useSoftDeletes = false;
protected array $fillable = [];

protected bool $allowEmptyInserts = false;
protected bool $updateOnlyChanged = true;

protected array $casts = [];
protected array $castHandlers = [];

// Dates
protected bool $useTimestamps = false;
protected string $dateFormat = 'datetime';
protected string $createdField = 'created_at';
protected string $updatedField = 'updated_at';
protected string $deletedField = 'deleted_at';

// Validation
protected array $rules = [];
protected array $messages = [];

protected $skipValidation = false;
protected $cleanValidationRules = true;

// Callbacks
protected bool $allowCallbacks = true;
protected array $beforeInsert = [];
protected array $afterInsert = [];
protected array $beforeUpdate = [];
protected array $afterUpdate = [];
protected array $beforeDelete = [];
protected array $afterDelete = [];
protected array $beforeFind = [];
protected array $afterFind = [];
}
23 changes: 23 additions & 0 deletions src/Config/Registrar.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

/**
* This file is part of Blitz PHP framework - Database Layer.
*
* (c) 2022 Dimitri Sitchet Tomkeu <devcode.dst@gmail.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace BlitzPHP\Database\Config;

class Registrar
{
/**
* Enregistre les fichiers de configurations publiable
*/
public static function config(): array
{
return ['database', 'dump', 'migrations'];
}
}
4 changes: 4 additions & 0 deletions src/Connection/BaseConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -648,12 +648,16 @@ abstract public function _listTables(bool $constrainByPrefix = false): string;
/**
* Retourne la requête SQL pour lister les index
*
* @return list<object{name: string, columns: list<string>, type: string, unique: bool, primary: bool}>
*
* @internal
*/
abstract public function _listIndexes(string $table): array;

/**
* Retourne la requête SQL pour lister les colonnes
*
* @return list<object{name: string, type: string, type_name: string, nullable: bool, default: mixed, auto_increment: bool, comment: string|null, generation: array{type: string, expression: string|null}|null}>
*
* @internal
*/
Expand Down
74 changes: 54 additions & 20 deletions src/Connection/MySQL.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,39 +127,73 @@ public function _listIndexes(string $table): array
$indexes = [];

foreach ($rows as $row) {
$index = new stdClass();
$index->name = $row->Key_name;
$index->type = match (true) {
$row->Key_name === 'PRIMARY' => 'PRIMARY',
$row->Index_type === 'FULLTEXT' => 'FULLTEXT',
isset($row->Non_unique) => $row->Index_type === 'SPATIAL' ? 'SPATIAL' : 'INDEX',
default => 'UNIQUE',
};

$indexes[] = $index;
$indexName = $row->Key_name;

if (! isset($indexes[$indexName])) {
$type = match (true) {
$indexName === 'PRIMARY' => 'PRIMARY',
$row->Index_type === 'FULLTEXT' => 'FULLTEXT',
$row->Index_type === 'SPATIAL' => 'SPATIAL',
isset($row->Non_unique) && (int)$row->Non_unique === 0 => 'UNIQUE',
default => 'INDEX',
};

$indexes[$indexName] = (object) [
'name' => $indexName,
'columns' => [],
'type' => $type,
'unique' => $type === 'UNIQUE',
'primary' => $type === 'PRIMARY',
];
}

$indexes[$indexName]->columns[] = $row->Column_name;
}

return $indexes;
return array_values($indexes);
}

/**
* {@inheritDoc}
*/
public function _listColumns(string $table): array
{
$sql = "SHOW COLUMNS FROM {$this->escapeIdentifiers($table)}";
$sql = "SHOW FULL COLUMNS FROM {$this->escapeIdentifiers($table)}";

$rows = $this->query($sql)->resultObject();
$columns = [];

foreach ($rows as $row) {
$column = new stdClass();
$column->name = $row->Field;
$column->nullable = $row->Null === 'YES';
$column->default = $row->Default;
$column->primary_key = $row->Key === 'PRI';

sscanf($row->Type, '%[a-z](%d)', $column->type, $column->max_length);
$typeName = $row->Type;
$maxLength = null;

if (preg_match('/^([a-z]+)(?:\((\d+)\))?/', $row->Type, $matches)) {
$typeName = $matches[1];
$maxLength = isset($matches[2]) ? (int) $matches[2] : null;
}

$autoIncrement = stripos($row->Extra, 'auto_increment') !== false;

// Gérer la génération (virtuelle/stored)
$generation = null;
if (stripos($row->Extra, 'GENERATED') !== false) {
$generation = [
'type' => stripos($row->Extra, 'VIRTUAL') !== false ? 'VIRTUAL' : 'STORED',
'expression' => null, // MySQL ne fournit pas l'expression via SHOW COLUMNS
];
}

$column = new stdClass();
$column->name = $row->Field;
$column->type = $typeName;
$column->type_name = $typeName;
$column->nullable = $row->Null === 'YES';
$column->default = $row->Default;
$column->auto_increment = $autoIncrement;
$column->max_length = $maxLength;
$column->comment = $row->Comment ?: null;
$column->primary_key = $row->Key === 'PRI';
$column->generation = $generation;

$columns[] = $column;
}
Expand Down
65 changes: 46 additions & 19 deletions src/Connection/Postgre.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,21 @@ public function _listIndexes(string $table): array
$indexes = [];

foreach ($rows as $row) {
$index = new stdClass();
$index->name = $row->indexname;
$_columns = explode(',', preg_replace('/^.*\((.+?)\)$/', '$1', trim($row->indexdef)));
$index->columns = array_map(static fn ($v) => trim($v), $_columns);

if (str_starts_with($row->indexdef, 'CREATE UNIQUE INDEX pk')) {
$index->type = 'PRIMARY';
$type = 'PRIMARY';
} else {
$index->type = (str_starts_with($row->indexdef, 'CREATE UNIQUE')) ? 'UNIQUE' : 'INDEX';
$type = (str_starts_with($row->indexdef, 'CREATE UNIQUE')) ? 'UNIQUE' : 'INDEX';
}

$_columns = explode(',', preg_replace('/^.*\((.+?)\)$/', '$1', trim($row->indexdef)));

$index = new stdClass();
$index->name = $row->indexname;
$index->columns = array_map(static fn ($v) => trim($v), $_columns);
$index->type = $type;
$index->unique = $type === 'UNIQUE';
$index->primary = $type === 'PRIMARY';

$indexes[] = $index;
}

Expand All @@ -121,23 +125,46 @@ public function _listIndexes(string $table): array
*/
public function _listColumns(string $table): array
{
$sql = 'SELECT "column_name", "data_type", "character_maximum_length", "numeric_precision", "column_default", "is_nullable"
FROM "information_schema"."columns"
WHERE LOWER("table_name") = '
. $this->escape(strtolower($this->prefix . $table))
. ' ORDER BY "ordinal_position"';
$sql = 'SELECT
c.column_name,
c.data_type,
c.character_maximum_length,
c.numeric_precision,
c.column_default,
c.is_nullable,
pg_catalog.col_description(pgc.oid, c.ordinal_position) as column_comment,
c.is_identity,
c.generation_expression
FROM information_schema.columns c
LEFT JOIN pg_class pgc ON pgc.relname = ' . $this->escape(strtolower($this->prefix . $table)) . '
WHERE LOWER(c.table_name) = ' . $this->escape(strtolower($this->prefix . $table)) . '
AND c.table_schema = \'public\'
ORDER BY c.ordinal_position';

$rows = $this->query($sql)->resultObject();
$columns = [];

foreach ($rows as $row) {
$column = new stdClass();
$column->name = $row->column_name;
$column->type = $row->data_type;
$column->nullable = $row->is_nullable === 'YES';
$column->default = $row->column_default;
$column->max_length = $row->character_maximum_length > 0 ? $row->character_maximum_length : $row->numeric_precision;

// Gérer la génération (GENERATED ALWAYS AS ...)
$generation = null;
if (!empty($row->generation_expression)) {
$generation = [
'type' => $row->is_identity === 'YES' ? 'IDENTITY' : 'GENERATED',
'expression' => $row->generation_expression,
];
}

$column = new stdClass();
$column->name = $row->column_name;
$column->type = $row->data_type;
$column->type_name = $row->data_type;
$column->nullable = $row->is_nullable === 'YES';
$column->default = $row->column_default;
$column->auto_increment = $row->is_identity === 'YES';
$column->comment = $row->column_comment ?: null;
$column->max_length = $row->character_maximum_length > 0 ? $row->character_maximum_length : $row->numeric_precision;
$column->generation = $generation;

$columns[] = $column;
}

Expand Down
Loading