Repository navigation
Expand file tree
/
Copy pathModelModel.php
More file actions
294 lines (226 loc) · 8.88 KB
/
Copy pathModelModel.php
File metadata and controls
294 lines (226 loc) · 8.88 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
<?php namespace RainLab\Builder\Classes;
use DirectoryIterator;
use SystemException;
use Validator;
use Lang;
use File;
use Schema;
use Str;
use Db;
/**
* Manages plugin models.
*
* @package rainlab\builder
* @author Alexey Bobkov, Samuel Georges
*/
class ModelModel extends BaseModel
{
const UNQUALIFIED_CLASS_NAME_PATTERN = '/^[A-Z]+[a-zA-Z0-9_]+$/';
public $className;
public $databaseTable;
protected static $fillable = [
'className',
'databaseTable',
'addTimestamps',
'addSoftDeleting'
];
protected $validationRules = [
'className' => ['required', 'regex:' . self::UNQUALIFIED_CLASS_NAME_PATTERN, 'uniqModelName'],
'databaseTable' => ['required'],
'addTimestamps' => ['timestampColumnsMustExist'],
'addSoftDeleting' => ['deletedAtColumnMustExist']
];
public static function listPluginModels($pluginCodeObj)
{
$modelsDirectoryPath = $pluginCodeObj->toPluginDirectoryPath().'/models';
$pluginNamespace = $pluginCodeObj->toPluginNamespace();
$modelsDirectoryPath = File::symbolizePath($modelsDirectoryPath);
if (!File::isDirectory($modelsDirectoryPath)) {
return [];
}
$parser = new ModelFileParser();
$result = [];
foreach (new DirectoryIterator($modelsDirectoryPath) as $fileInfo) {
if (!$fileInfo->isFile()) {
continue;
}
if ($fileInfo->getExtension() != 'php') {
continue;
}
$filePath = $fileInfo->getPathname();
$contents = File::get($filePath);
$modelInfo = $parser->extractModelInfoFromSource($contents);
if (!$modelInfo) {
continue;
}
if (!Str::startsWith($modelInfo['namespace'], $pluginNamespace.'\\')) {
continue;
}
$model = new ModelModel();
$model->className = $modelInfo['class'];
$model->databaseTable = isset($modelInfo['table']) ? $modelInfo['table'] : null;
$result[] = $model;
}
return $result;
}
public function save()
{
$this->validate();
$modelFilePath = $this->getFilePath();
$namespace = $this->getPluginCodeObj()->toPluginNamespace().'\\Models';
$structure = [
$modelFilePath => 'model.php.tpl'
];
$variables = [
'namespace' => $namespace,
'classname' => $this->className,
'table' => $this->databaseTable
];
$dynamicContents = [];
$generator = new FilesystemGenerator('$', $structure, '$/rainlab/builder/classes/modelmodel/templates');
$generator->setVariables($variables);
if ($this->addSoftDeleting) {
$dynamicContents[] = $generator->getTemplateContents('soft-delete.php.tpl');
}
if (!$this->addTimestamps) {
$dynamicContents[] = $generator->getTemplateContents('no-timestamps.php.tpl');
}
$generator->setVariable('dynamicContents', implode('', $dynamicContents));
$generator->generate();
}
public function validate()
{
$path = File::symbolizePath('$/'.$this->getFilePath());
$this->validationMessages = [
'className.uniq_model_name' => Lang::get('rainlab.builder::lang.model.error_class_name_exists', ['path'=>$path]),
'addTimestamps.timestamp_columns_must_exist' => Lang::get('rainlab.builder::lang.model.error_timestamp_columns_must_exist'),
'addSoftDeleting.deleted_at_column_must_exist' => Lang::get('rainlab.builder::lang.model.error_deleted_at_column_must_exist')
];
Validator::extend('uniqModelName', function ($attribute, $value, $parameters) use ($path) {
$value = trim($value);
if (!$this->isNewModel()) {
// Editing models is not supported at the moment,
// so no validation is required.
return true;
}
return !File::isFile($path);
});
$columns = $this->isNewModel() ? Schema::getColumnListing($this->databaseTable) : [];
Validator::extend('timestampColumnsMustExist', function ($attribute, $value, $parameters) use ($columns) {
return $this->validateColumnsExist($value, $columns, ['created_at', 'updated_at']);
});
Validator::extend('deletedAtColumnMustExist', function ($attribute, $value, $parameters) use ($columns) {
return $this->validateColumnsExist($value, $columns, ['deleted_at']);
});
parent::validate();
}
public function getDatabaseTableOptions()
{
$pluginCode = $this->getPluginCodeObj()->toCode();
$tables = DatabaseTableModel::listPluginTables($pluginCode);
return array_combine($tables, $tables);
}
private static function getTableNameFromModelClass($pluginCodeObj, $modelClassName)
{
if (!self::validateModelClassName($modelClassName)) {
throw new SystemException('Invalid model class name: '.$modelClassName);
}
$modelsDirectoryPath = File::symbolizePath($pluginCodeObj->toPluginDirectoryPath().'/models');
if (!File::isDirectory($modelsDirectoryPath)) {
return '';
}
$modelFilePath = $modelsDirectoryPath.'/'.$modelClassName.'.php';
if (!File::isFile($modelFilePath)) {
return '';
}
$parser = new ModelFileParser();
$modelInfo = $parser->extractModelInfoFromSource(File::get($modelFilePath));
if (!$modelInfo || !isset($modelInfo['table'])) {
return '';
}
return $modelInfo['table'];
}
public static function getModelFields($pluginCodeObj, $modelClassName)
{
$tableName = self::getTableNameFromModelClass($pluginCodeObj, $modelClassName);
// Currently we return only table columns,
// but eventually we might want to return relations as well.
return Schema::getColumnListing($tableName);
}
public static function getModelColumnsAndTypes($pluginCodeObj, $modelClassName)
{
$tableName = self::getTableNameFromModelClass($pluginCodeObj, $modelClassName);
if (!DatabaseTableModel::tableExists($tableName)) {
throw new ApplicationException('Database table not found: '.$tableName);
}
$schema = DatabaseTableModel::getSchema();
$tableInfo = $schema->getTable($tableName);
$columns = $tableInfo->getColumns();
$result = [];
foreach ($columns as $column) {
$columnName = $column->getName();
$typeName = $column->getType()->getName();
if ($typeName == EnumDbType::TYPENAME) {
continue;
}
$item = [
'name' => $columnName,
'type' => MigrationColumnType::toMigrationMethodName($typeName, $columnName)
];
$result[] = $item;
}
return $result;
}
public static function getPluginRegistryData($pluginCode, $subtype)
{
$pluginCodeObj = new PluginCode($pluginCode);
$models = self::listPluginModels($pluginCodeObj);
$result = [];
foreach ($models as $model) {
$fullClassName = $pluginCodeObj->toPluginNamespace().'\\Models\\'.$model->className;
$result[$fullClassName] = $model->className;
}
return $result;
}
public static function getPluginRegistryDataColumns($pluginCode, $modelClassName)
{
$classParts = explode('\\', $modelClassName);
if (!$classParts) {
return [];
}
$modelClassName = array_pop($classParts);
if (!self::validateModelClassName($modelClassName)) {
return [];
}
$pluginCodeObj = new PluginCode($pluginCode);
$columnNames = self::getModelFields($pluginCodeObj, $modelClassName);
$result = [];
foreach ($columnNames as $columnName) {
$result[$columnName] = $columnName;
}
return $result;
}
public static function validateModelClassName($modelClassName)
{
return class_exists($modelClassName) || !!preg_match(self::UNQUALIFIED_CLASS_NAME_PATTERN, $modelClassName);
}
protected function getFilePath()
{
return $this->getPluginCodeObj()->toFilesystemPath().'/models/'.$this->className.'.php';
}
protected function validateColumnsExist($value, $columns, $columnsToCheck)
{
if (!strlen(trim($this->databaseTable))) {
return true;
}
if (!$this->isNewModel()) {
// Editing models is not supported at the moment,
// so no validation is required.
return true;
}
if (!$value) {
return true;
}
return count(array_intersect($columnsToCheck, $columns)) == count($columnsToCheck);
}
}