MiniMVC /module/Dev/controller/Generate.php

Language PHP Lines 569
MD5 Hash bc2202fce178ee30bac18e202595cfcb
Repository https://github.com/tquensen/MiniMVC.git View Raw File View Project SPDX
  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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
<?php

class Dev_Generate_Controller extends MiniMVC_Controller
{

    public function i18nAction($params)
    {
        if (!$params['module']) {
            return 'Kein Modul angegeben!' . "\n";
        }

        if (!file_exists(MODULEPATH . $params['module'])) {
            return 'Modul existiert nicht!' . "\n";
        }

        $return = '';

        $languages = array();
        $activeLanguages = $this->registry->settings->get('config/enabledLanguages', array());
        foreach ($activeLanguages as $language) {
            $MiniMVC_i18n = array();
            $languages[$language] = array('found' => array(), 'new' => array());

            if (file_exists(MODULEPATH . $params['module'].'/i18n/'.$language.'.php')) {
                include MODULEPATH . $params['module'].'/i18n/'.$language.'.php';
                if (isset($MiniMVC_i18n[$params['module']])) {
                    $languages[$language]['found'] = $MiniMVC_i18n[$params['module']];
                }
            }
        }

        $i18nFound = $this->searchI18n(MODULEPATH . $params['module']);
        asort($i18nFound);

        foreach ($languages as $currentLanguage => $currentLanguageData) {
            foreach ($i18nFound as $newI18n) {
                if (!isset($currentLanguageData['found'][$newI18n])) {
                    $languages[$currentLanguage]['new'][$newI18n] = '$MiniMVC_i18n[\''.$params['module'].'\'][\''.$newI18n.'\'] = \''.$newI18n.'\';';
                }
            }
        }

        foreach ($languages as $currentLanguage => $currentLanguageData) {
            if (file_exists(MODULEPATH . $params['module'].'/i18n/'.$currentLanguage.'.php')) {
                file_put_contents(MODULEPATH . $params['module'].'/i18n/'.$currentLanguage.'.php', "\n".implode("\n", $languages[$currentLanguage]['new']), FILE_APPEND);
                $return .= 'Datei '.MODULEPATH . $params['module'].'/i18n/'.$currentLanguage.'.php'.' aktualisiert!'."\n";
            } else {
                file_put_contents(MODULEPATH . $params['module'].'/i18n/'.$currentLanguage.'.php', '<?php'."\n".implode("\n", $languages[$currentLanguage]['new']));
                $return .= 'Datei '.MODULEPATH . $params['module'].'/i18n/'.$currentLanguage.'.php'.' angelegt!'."\n";
            }
        }
        
        return $return .= 'I18n-Dateien erfolgreich generiert!';

    }

    protected function searchI18n($folder, $found = array())
    {
        if (!is_dir($folder)) {
            return $found;
        }

        $regex = '#(\$|->)(t|i18n)->([\w]+)#i';

        foreach (scandir($folder) as $file) {
            if (is_dir($folder.'/'.$file) && $file !== '.' && $file !== '..') {
                $found = $this->searchI18n($folder.'/'.$file, $found);
            } elseif (is_file($folder.'/'.$file) && substr($file, -4) == '.php') {
                $content = file_get_contents($folder.'/'.$file);
                $matches = array();
                if (preg_match_all($regex, $content, $matches)) {
                    foreach ($matches[3] as $match) {
                        if ($match == 'get') {
                            continue;
                        }
                        $found[$match] = $match;
                    }
                }
            }
        }
        return $found;
    }

    public function appAction($params)
    {
        if (!$params['app']) {
            return 'Keinen Appnamen angegeben!' . "\n";
        }

        if (file_exists(APPPATH . $params['app'])) {
            return 'App existiert bereits!' . "\n";
        }

        if (!is_writable(APPPATH)) {
            return 'Keine Schreibrechte im App-Ordner!' . "\n";
        }

        $path = APPPATH . $params['app'];
        $dummy = MODULEPATH . 'Dev/dummies';

        mkdir($path);
        mkdir($path . '/i18n');
        mkdir($path . '/settings');
        mkdir($path . '/view');
        mkdir($path . '/web');
        mkdir($path . '/web/js');
        mkdir($path . '/web/css');
        mkdir($path . '/web/images');
        mkdir($path . '/lib');

        file_put_contents($path . '/view/default.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/app_view.php')));
//        file_put_contents($path . '/view/default.html.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/app_view_html.php')));
//        file_put_contents($path . '/view/default.json.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/app_view.json.php')));
//        file_put_contents($path . '/view/default.xml.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/app_view.xml.php')));
        file_put_contents($path . '/i18n/de_DE.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/de_DE_app.php')));
        file_put_contents($path . '/i18n/en_US.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/en_US_app.php')));
        //file_put_contents($path . '/settings/slots.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/slots_app.php')));
        file_put_contents($path . '/settings/view.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/view.php')));
        file_put_contents($path . '/settings/config.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/config_app.php')));
        file_put_contents($path . '/settings/routes.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/routes_app.php')));
        file_put_contents($path . '/settings/widgets.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/widgets_app.php')));
        file_put_contents($path . '/settings/theme.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/theme.php')));

        if ($params['w']) {
            file_put_contents(WEBPATH . $params['app'] . '.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/app_web.php')));
            file_put_contents(WEBPATH . $params['app'] . '_dev.php', str_replace('APP', $params['app'], file_get_contents($dummy . '/app_web_dev.php')));
        }

        return 'App was generated successfully!'."\n"
              .'Make sure to define the $MiniMVC_apps[\''.$params['app'].'\'][\'baseurl\'] in your settings/apps.php and settings/apps_dev.php files!'."\n"
              .'Optionally, you can modify the web/.htaccess file to enable pretty URLs.';
    }

    public function moduleAction($params)
    {
        if (!$params['module']) {
            return 'Kein Modul angegeben!' . "\n";
        }

        if (file_exists(MODULEPATH . $params['module'])) {
            return 'Modul existiert bereits!' . "\n";
        }

        if (!is_writable(MODULEPATH)) {
            return 'Keine Schreibrechte im Module-Ordner!' . "\n";
        }

        $controller = !empty($params['controller']) ? $params['controller'] : $params['module'];

        $path = MODULEPATH . $params['module'];
        $dummy = MODULEPATH . 'Dev/dummies';

        mkdir($path);
        mkdir($path . '/controller');
        mkdir($path . '/model');
        //mkdir($path . '/Model/Schema');
        mkdir($path . '/settings');
        mkdir($path . '/i18n');
        mkdir($path . '/view');
        mkdir($path . '/view/'.strtolower($controller));
        mkdir($path . '/web');
        mkdir($path . '/web/js');
        mkdir($path . '/web/css');
        mkdir($path . '/web/images');
        mkdir($path . '/lib');
        //mkdir($path . '/Lib/Migrations');

        $search = array(
            'MODULELCFIRST',
            'CONTROLLERLCFIRST',
            'CONTROLLERTABLE',
            'MODLC',
            'MODULE',
            'CONTROLLERLC',
            'CONTROLLER',
        );
        $replace = array(
            strtolower(substr($params['module'], 0, 1)) . substr($params['module'], 1),
            strtolower(substr($controller, 0, 1)) . substr($controller, 1),
            strtolower(preg_replace('/(?!^)[[:upper:]]+/', '_$0', $controller)),
            strtolower($params['module']),
            $params['module'],
            strtolower($controller),
            $controller
        );
        file_put_contents($path . '/controller/'.$controller.'.php', str_replace($search, $replace, file_get_contents($dummy . '/Controller.php')));
        file_put_contents($path . '/Installer.php', str_replace($search, $replace, file_get_contents($dummy . '/Installer.php')));
        file_put_contents($path . '/i18n/de_DE.php', str_replace($search, $replace, file_get_contents($dummy . '/de_DE.php')));
        file_put_contents($path . '/i18n/en_US.php', str_replace($search, $replace, file_get_contents($dummy . '/en_US.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/index.html.php', str_replace($search, $replace, file_get_contents($dummy . '/index.html.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/index.json.php', str_replace($search, $replace, file_get_contents($dummy . '/index.json.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/widget.html.php', str_replace($search, $replace, file_get_contents($dummy . '/widget.html.php')));
//        file_put_contents($path . '/view/'.strtolower($controller).'/new.html.php', str_replace($search, $replace, file_get_contents($dummy . '/new.html.php')));
//        file_put_contents($path . '/view/'.strtolower($controller).'/new.json.php', str_replace($search, $replace, file_get_contents($dummy . '/new.json.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/create.html.php', str_replace($search, $replace, file_get_contents($dummy . '/create.html.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/create.json.php', str_replace($search, $replace, file_get_contents($dummy . '/create.json.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/show.html.php', str_replace($search, $replace, file_get_contents($dummy . '/show.html.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/show.json.php', str_replace($search, $replace, file_get_contents($dummy . '/show.json.php')));
//        file_put_contents($path . '/view/'.strtolower($controller).'/edit.html.php', str_replace($search, $replace, file_get_contents($dummy . '/edit.html.php')));
//        file_put_contents($path . '/view/'.strtolower($controller).'/edit.json.php', str_replace($search, $replace, file_get_contents($dummy . '/edit.json.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/update.html.php', str_replace($search, $replace, file_get_contents($dummy . '/update.html.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/update.json.php', str_replace($search, $replace, file_get_contents($dummy . '/update.json.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/delete.html.php', str_replace($search, $replace, file_get_contents($dummy . '/delete.html.php')));
        file_put_contents($path . '/view/'.strtolower($controller).'/delete.json.php', str_replace($search, $replace, file_get_contents($dummy . '/delete.json.php')));
        file_put_contents($path . '/settings/config.php', str_replace($search, $replace, file_get_contents($dummy . '/config.php')));
        file_put_contents($path . '/settings/routes.php', str_replace($search, $replace, file_get_contents($dummy . '/routes.php')));
        file_put_contents($path . '/settings/widgets.php', str_replace($search, $replace, file_get_contents($dummy . '/widgets.php')));
        file_put_contents($path . '/model/definition.php', str_replace($search, $replace, file_get_contents($dummy . '/definition.php')));
        //file_put_contents($path . '/settings/slots.php', str_replace(array('MODLC', 'MODULE'), array(strtolower($params['module']), $params['module']), file_get_contents($dummy . '/slots.php')));
        //file_put_contents($path . '/Model/Schema/schema.yml', str_replace(array('MODLC', 'MODULE'), array(strtolower($params['module']), $params['module']), file_get_contents($dummy . '/schema.yml')));

        $routesContent = file_get_contents($path . '/settings/routes.php');
        file_put_contents($path . '/settings/routes.php', str_replace($search, $replace, file_get_contents($dummy . '/routes_controller.php')) . $routesContent);

        return 'Modul wurde erfolgreich generiert!';
    }

    public function modelAction($params)
    {
        if (!$params['module']) {
            return 'Kein Modul angegeben!' . "\n";
        }
        if (!$params['model']) {
            return 'Kein Modelnamen angegeben!' . "\n";
        }

        $definition = $this->getModelDefinition($params['module'], $params['model']);

        if (!$definition) {
            return 'No model definition found for '.$params['model'].' in module '.$params['module'].'...' . "\n";
        }

        if (empty($definition['identifier'])) {
            $definition['identifier'] = 'id';
        }
        if (!isset($definition['autoIncrement'])) {
            $definition['autoIncrement'] = false;
        }
        if (!isset($definition['columns'][$definition['identifier']])) {
            $definition['columns'][$definition['identifier']] = 'int';
        }
        if (!isset($definition['relations'])) {
            $definition['relations'] = array();
        }

        $model = ucfirst($params['model']);

        $search = array(
            '{name}',
            '{table}',
            '{module}',
            '{modlc}',
            '{namelcfirst}',
            '{columns_list}',
            '{columns_sql}',
            '{columns_phpdoc}',
            '{columns_form}',
            '{auto_increment}',
            '{identifier}',
            '{relations_list}',
            '{relations_methods}',
            '{modelClass}',
            '{tableClass}',
            '{collectionClass}'
        );
        $replace = array(
            $model,
            strtolower(preg_replace('/(?!^)[[:upper:]]+/', '_$0', $model)),
            $params['module'],
            strtolower($params['module']),
            strtolower(substr($model, 0, 1)) . substr($model, 1),
            '\''.implode('\', \'', array_keys($definition['columns'])).'\'',
            $this->getSqlCode($definition, $model),
            $this->getPhpDocCode($definition, $model),
            $this->getFormCode($definition, $model),
            $definition['autoIncrement'] ? 'true' : 'false',
            $definition['identifier'],
            $this->getRelationsListCode($definition, $model),
            $this->getRelationsMethodsCode($definition, $model),
            $this->registry->settings->get('config/classes/model', 'MiniMVC_Model'),
            $this->registry->settings->get('config/classes/table', 'MiniMVC_Table'),
            $this->registry->settings->get('config/classes/collection', 'MiniMVC_Collection')
        );

        $path = MODULEPATH . $params['module'].'/model';
        $dummy = MODULEPATH . 'Dev/dummies';

        $message = 'Erstelle Models...'."\n";
        if (!file_exists($path . '/'.$model.'.php')) {
            file_put_contents($path . '/'.$model.'.php', str_replace($search, $replace, file_get_contents($dummy . '/Model.php')));
            $message .= '-> Datei '.$model.'.php erstellt'."\n";
        } else {
            $message .= '-> Datei '.$model.'.php existiert bereits'."\n";
        }
        if (!file_exists($path . '/'.$model.'Table.php')) {
            file_put_contents($path . '/'.$model.'Table.php', str_replace($search, $replace, file_get_contents($dummy . '/Table.php')));
            $message .= '-> Datei '.$model.'Table.php erstellt'."\n";
        } else {
            $message .= '-> Datei '.$model.'Table.php existiert bereits'."\n";
        }
        if (!file_exists($path . '/'.$model.'Form.php')) {
            file_put_contents($path . '/'.$model.'Form.php', str_replace($search, $replace, file_get_contents($dummy . '/Form.php')));
            $message .= '-> Datei '.$model.'Form.php erstellt'."\n";
        } else {
            $message .= '-> Datei '.$model.'Form.php existiert bereits'."\n";
        }
        if (!file_exists($path . '/'.$model.'Collection.php')) {
            file_put_contents($path . '/'.$model.'Collection.php', str_replace($search, $replace, file_get_contents($dummy . '/Collection.php')));
            $message .= '-> Datei '.$model.'Collection.php erstellt'."\n";
        } else {
            $message .= '-> Datei '.$model.'Collection.php existiert bereits'."\n";
        }

        file_put_contents($path . '/'.$model.'Base.php', str_replace($search, $replace, file_get_contents($dummy . '/ModelBase.php')));
        $message .= '-> Datei '.$model.'Base.php erstellt'."\n";
        file_put_contents($path . '/'.$model.'TableBase.php', str_replace($search, $replace, file_get_contents($dummy . '/TableBase.php')));
        $message .= '-> Datei '.$model.'TableBase.php erstellt'."\n";


        return $message;
    }

    public function controllerAction($params)
    {
        if (!$params['module']) {
            return 'Kein Modul angegeben!' . "\n";
        }
        if (!$params['controller']) {
            return 'Kein Controllername angegeben!' . "\n";
        }

        $params['module'] = ucfirst($params['module']);
        $controller = ucfirst($params['controller']);

        $search = array(
            'MODULELCFIRST',
            'CONTROLLERLCFIRST',
            'MODLC',
            'MODULE',
            'MODULELCFIRST',
            'CONTROLLERLC',
            'CONTROLLER'
        );
        $replace = array(
            strtolower(substr($params['module'], 0, 1)) . substr($params['module'], 1),
            strtolower(substr($controller, 0, 1)) . substr($controller, 1),
            strtolower($params['module']),
            $params['module'],
            strtolower(substr($params['module'], 0, 1)) . substr($params['module'], 1),
            strtolower($controller),
            $controller
        );

        $path = MODULEPATH . $params['module'].'/controller';
        $dummy = MODULEPATH . 'Dev/dummies';

        $message = 'Erstelle Controller...'."\n";
        if (!file_exists($path . '/'.$controller.'.php')) {
            mkdir($path . '/../view/'.strtolower($controller));
            file_put_contents($path . '/'.$controller.'.php', str_replace($search, $replace, file_get_contents($dummy . '/Controller.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/index.html.php', str_replace($search, $replace, file_get_contents($dummy . '/index.html.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/index.json.php', str_replace($search, $replace, file_get_contents($dummy . '/index.json.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/widget.html.php', str_replace($search, $replace, file_get_contents($dummy . '/widget.html.php')));
//            file_put_contents($path . '/../view/'.strtolower($controller).'/new.html.php', str_replace($search, $replace, file_get_contents($dummy . '/new.html.php')));
//            file_put_contents($path . '/../view/'.strtolower($controller).'/new.json.php', str_replace($search, $replace, file_get_contents($dummy . '/new.json.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/create.html.php', str_replace($search, $replace, file_get_contents($dummy . '/create.html.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/create.json.php', str_replace($search, $replace, file_get_contents($dummy . '/create.json.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/show.html.php', str_replace($search, $replace, file_get_contents($dummy . '/show.html.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/show.json.php', str_replace($search, $replace, file_get_contents($dummy . '/show.json.php')));
//            file_put_contents($path . '/../view/'.strtolower($controller).'/edit.html.php', str_replace($search, $replace, file_get_contents($dummy . '/edit.html.php')));
//            file_put_contents($path . '/../view/'.strtolower($controller).'/edit.json.php', str_replace($search, $replace, file_get_contents($dummy . '/edit.json.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/update.html.php', str_replace($search, $replace, file_get_contents($dummy . '/update.html.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/update.json.php', str_replace($search, $replace, file_get_contents($dummy . '/update.json.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/delete.html.php', str_replace($search, $replace, file_get_contents($dummy . '/delete.html.php')));
            file_put_contents($path . '/../view/'.strtolower($controller).'/delete.json.php', str_replace($search, $replace, file_get_contents($dummy . '/delete.json.php')));


            $routesContent = file_exists($path . '/../settings/routes.php') ? file_get_contents($path . '/../settings/routes.php') : '';
            file_put_contents($path . '/../settings/routes.php', str_replace($search, $replace, file_get_contents($dummy . '/routes_controller.php')) . $routesContent);

            $message .= '-> Controller controller/'.$controller.'.php wurde erstellt'."\n";
            $message .= '-> Views in view/'.strtolower($controller).'/ wurden erstellt'."\n";
            $message .= '-> Routing in settings/routes.php wurde erweitert'."\n";
        } else {
            $message .= '-> Datei '.$controller.'.php existiert bereits'."\n";
        }
        return $message;
    }

    protected function getSqlCode($definition, $model)
    {
        $types = array(
            'int' => 'INT(11)',
            'integer' => 'INT(11)',
            'bool' => 'TINYINT(1) NOT NULL',
            'boolean' => 'TINYINT(1) NOT NULL',
            'float' => 'FLOAT',
            'double' => 'DOUBLE',
            'string' => 'VARCHAR(255)',
            'array' => 'TEXT'
        );

        $return = array();
        foreach ($definition['columns'] as $column => $type) {
            $sqlType = isset($types[strtolower($type)]) ? $types[strtolower($type)] : 'VARCHAR(255)';
            if ($column == $definition['identifier']) {
                array_unshift($return, $column . ' ' .$sqlType . ($definition['autoIncrement'] ? ' AUTO_INCREMENT' : ''));
            } else {
                $return[] = '                      ' . $column . ' ' .$sqlType;
            }
        }
        return implode(",\n", $return);

    }

    protected function getPhpDocCode($definition, $model)
    {
        $return = '';
        foreach ($definition['columns'] as $column => $type) {
            $return .= '@property ' . strtolower($type) . ' $' . $column . "\n * ";
        }
        return $return;
    }

    protected function getFormCode($definition, $model)
    {
        $types = array(
            'int' => 'Text',
            'integer' => 'Text',
            'bool' => 'Checkbox',
            'boolean' => 'Checkbox',
            'float' => 'Text',
            'double' => 'Text',
            'string' => 'Text',
            'array' => 'Text'
        );

        $code = '$this->setElement(new MiniMVC_Form_Element_{type}(\'{column}\',
                        array(\'label\' => $this->i18n->{namelcfirst}Form{columncc}Label),
                        array(
                            //new MiniMVC_Form_Validator_Required(array(\'errorMessage\' => $this->i18n->{namelcfirst}Form{columncc}Error))
                )));
        ';

        $output = '';
        $search = array('{namelcfirst}', '{column}', '{columnucfirst}', '{columncc}', '{type}');

        foreach ($definition['columns'] as $column => $type) {
            if ($column == $definition['identifier']) {
                continue;
            }
            $replace = array(strtolower(substr($model, 0, 1)) . substr($model, 1), $column, ucfirst($column), ucfirst(preg_replace('/_(.)/e', 'ucfirst("$1")', $column)), isset($types[strtolower($type)]) ? $types[strtolower($type)] : 'Text');
            $output .= str_replace($search, $replace, $code);
        }
        return $output;
    }

    protected function getRelationsListCode($definition, $model)
    {
        $return = array();
        foreach ($definition['relations'] as $relation => $data) {
            if (empty($data[0]) || empty($data[1]) || empty($data[2])) {
                continue;
            }
            $return[] = '\''.$relation.'\' => array(\''.$data[0].'\', \''.$data[1].'\', \''.$data[2].'\''.(!empty($data[3]) ? ($data[3] === true ? ', true' : ', \''.$data[3].'\'') : '').')';
        }
        return implode(', ', $return);
    }

    protected function getRelationsMethodsCode($definition, $model)
    {
        $code = '
    /**
     *
     * @param mixed $identifier the identifier of the related model or true to return all stored models of this relation
     * @return {related_model_or_array}
     */
    public function get{relation}($identifier = true)
    {
        return $this->getRelated(\'{relation}\', $identifier = true);
    }

    /**
     *
     * @param MiniMVC_Model $identifier the related model
     * @param bool $update whether to update the model if it is already stored or not
     */
    public function set{relation}($identifier = null, $update = true)
    {
        return $this->setRelated(\'{relation}\', $identifier = null, $update = true);
    }

    /**
     *
     * @param mixed $identifier either a model object, an identifier of a related model or true
     * @param bool $realDelete whether to delete the model from the database (true) or just from this object(false) defaults to true
     * @param bool $realDeleteLoad if the identifier is true only the related models currently assigned to this object will be deleted. with relaDeleteLoad=true, all related models will be deleted
     * @param bool $realDeleteCleanRef if relaDeleteLoad is true, set realDeleteCleanRef=true to clean up the ref table (for m:n relations)
     */
    public function delete{relation}($identifier = true, $realDelete = true, $realDeleteLoad = false, $realDeleteCleanRef = false)
    {
        return $this->deleteRelated(\'{relation}\', $identifier = true, $realDelete = true, $realDeleteLoad = false, $realDeleteCleanRef = false);
    }

    /**
     *
     * @param string $condition the where-condition
     * @param array $values values for the placeholders in the condition
     * @param string $order the order
     * @param int $limit the limit
     * @param int $offset the offset
     * @return {related_model_or_array}
     */
    public function load{relation}($condition = null, $values = array(), $order = null, $limit = null, $offset = null)
    {
        return $this->loadRelated(\'{relation}\', $condition = null, $values = array(), $order = null, $limit = null, $offset = null);
    }

    /**
     *
     * @param mixed $identifier a related model object, the identifier of a related model currently asigned to this model or true to save all related models
     * @param bool $saveThisOnDemand whether to allow this model to be saved in the database if its new (to generate an auto-increment identifier)
     */
    public function save{relation}($identifier = true, $saveThisOnDemand = true)
    {
        return $this->saveRelated(\'{relation}\', $identifier = true, $saveThisOnDemand = true);
    }

    /**
     *
     * @param mixed $identifier a related model object, the identifier of a related model
     * @param bool $loadRelated whether to load the related object (if identifier is not already loaded and assigned to this model)
     */
    public function link{relation}($identifier = null, $loadRelated = false)
    {
        return $this->linkRelated(\'{relation}\', $identifier = null, $loadRelated = false);
    }

    /**
     *
     * @param mixed $identifier a related model object, the identifier of a related model or unlink to save all related models
     */
    public function unlink{relation}($identifier = true)
    {
        return $this->unlinkRelated(\'{relation}\', $identifier = true);
    }

    ';


        $return = array();
        $search = array('{relation}', '{related_model_or_array}');
        foreach ($definition['relations'] as $relation => $data) {
            $replace = array($relation, isset($data[3]) && $data[3] === true ? $data[0] : $data[0].'Collection');
            $return[] = str_replace($search, $replace, $code);
        }
        return implode("\n", $return);
    }

    protected function getModelDefinition($module, $model)
    {
        $modelDefinition = array();
        $file = MODULEPATH . $module.'/model/definition.php';
        if (file_exists($file)) {
            include $file;
        }
        return isset($modelDefinition[$model]) ? $modelDefinition[$model] : false;
    }
}
Back to Top