-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMakeModel.php
More file actions
93 lines (81 loc) · 2.65 KB
/
Copy pathMakeModel.php
File metadata and controls
93 lines (81 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
namespace Pet\Model;
use Pet\View\BladeCompiler;
/**
* MakeModel
*
* Генерирует класс модели на основе Blade-шаблона stub/Model.blade.php.
* Использует BladeCompiler для компиляции шаблона в PHP-код.
*
* Использование:
* ```php
* new MakeModel('User');
* // Создаёт app/Model/User.php из stub/Model.blade.php
* ```
*/
class MakeModel
{
/**
* Директория, куда сохранять модель (app/Model).
*/
protected static string $DIR = '';
/**
* Имя папки для моделей.
*/
protected static string $nameFolder = 'Model';
/**
* Путь к Blade-шаблону модели.
*/
protected static string $stubPath = '';
/**
* @param string $name Имя модели (например, User)
*/
public function __construct(string $name)
{
// Инициализация путей
static::$DIR = ROOT . DS . PUBLIC_DIR . DS . APP;
static::$stubPath = __DIR__ . '/../blade/Model.blade.php';
if (!is_dir(static::$DIR . DS . static::$nameFolder)) {
mkdir(static::$DIR . DS . static::$nameFolder, 0777, true);
}
$name = ucfirst($name);
$this->createModel($name);
}
/**
* Создать файл модели из Blade-шаблона.
*
* @param string $name Имя класса модели
* @return void
*/
private function createModel(string $name): void
{
// Данные для шаблона
$data = [
'namespace' => 'App\\' . static::$nameFolder,
'className' => $name,
'table' => $this->tableName($name),
'fillable' => [],
'hidden' => ['password'],
'casts' => [],
'timestamps' => true,
'connection' => null,
];
// Компилируем Blade-шаблон в PHP
$compiled = BladeCompiler::renderFile(static::$stubPath, $data);
// Сохраняем в файл
$folder = static::$DIR . DS . static::$nameFolder . DS . "$name.php";
file_put_contents($folder, $compiled);
}
/**
* Преобразовать имя класса в имя таблицы (CamelCase -> snake_case + s).
*
* @param string $name
* @return string
*/
private function tableName(string $name): string
{
// User -> users, Post -> posts, UserRole -> user_roles
$snake = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $name));
return $snake . 's';
}
}