This repository has been archived by the owner on Nov 4, 2020. It is now read-only.
/
xpdogenerator.class.php
655 lines (626 loc) · 24.3 KB
/
xpdogenerator.class.php
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
<?php
/*
* Copyright 2006, 2007, 2008, 2009 by Jason Coward <xpdo@opengeek.com>
*
* This file is part of xPDO.
*
* xPDO is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* xPDO is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* xPDO; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*/
/**
* Class for reverse and forward engineering xPDO domain models.
*
* @package xpdo
* @subpackage om
*/
/**
* A service for reverse and forward engineering xPDO domain models.
*
* This service utilizes an xPDOManager instance to generate class stub and
* meta-data map files from a provided vanilla XML schema of a database
* structure. It can also reverse-engineer XML schemas from an existing
* database.
*
* @package xpdo
* @subpackage om
*/
class xPDOGenerator {
/**
* @var xPDOManager $manager A reference to the xPDOManager using this
* generator.
*/
public $manager= null;
/**
* @var xPDOSchemaManager $schemaManager
*/
public $schemaManager= null;
/**
* @var xmlParser $xmlParser
*/
public $xmlParser= null;
/**
* @var string $outputDir The absolute path to output the class and map
* files to.
*/
public $outputDir= '';
/**
* @var string $schemaFile An absolute path to the schema file.
*/
public $schemaFile= '';
/**
* @var string $schemaContent The stored content of the newly-created schema
* file.
*/
public $schemaContent= '';
/**
* @var string $classTemplate The class template string to build the class
* files from.
*/
public $classTemplate= '';
/**
* @var string $platformTemplate The class platform template string to build
* the class platform files from.
*/
public $platformTemplate= '';
/**
* @var string $mapHeader The map header string to build the map files from.
*/
public $mapHeader= '';
/**
* @var string $mapFooter The map footer string to build the map files from.
*/
public $mapFooter= '';
/**
* @var array $model The stored model array.
*/
public $model= array ();
/**
* @var array $classes The stored classes array.
*/
public $classes= array ();
/**
* @var array $map The stored map array.
*/
public $map= array ();
/**
* @var string $className A placeholder for the current class name.
*/
public $className= '';
/**
* @var string $fieldKey A placeholder for the current field key.
*/
public $fieldKey= '';
/**
* Constructor
*
* @access protected
* @param xPDOManager &$manager A reference to a valid xPDOManager instance.
* @return xPDOGenerator
*/
public function __construct(& $manager) {
$this->manager= & $manager;
}
/**
* Formats a class name to a specific value, stripping the prefix if
* specified.
*
* @access public
* @param string $string The name to format.
* @param string $prefix If specified, will strip the prefix out of the
* first argument.
* @param boolean $prefixRequired If true, will return a blank string if the
* prefix specified is not found.
* @return string The formatting string.
*/
public function getTableName($string, $prefix= '', $prefixRequired= false) {
if (!empty($prefix) && strpos($string, $prefix) === 0) {
$string= substr($string, strlen($prefix));
}
elseif ($prefixRequired) {
$string= '';
}
return $string;
}
/**
* Gets a class name from a table name by splitting the string by _ and
* capitalizing each token.
*
* @access public
* @param string $string The table name to format.
* @return string The formatted string.
*/
public function getClassName($string) {
if (is_string($string) && $strArray= explode('_', $string)) {
$return= '';
while (list($k, $v)= each($strArray)) {
$return.= strtoupper(substr($v, 0, 1)) . substr($v, 1) . '';
}
$string= $return;
}
return trim($string);
}
/**
* Gets the PHP field type based upon the specified database type.
*
* @access public
* @param string $dbtype The database field type to convert.
* @return string The associated PHP type
*/
public function getPhpType($dbtype) {
$dbtype= strtoupper($dbtype);
$phptype = '';
foreach ($this->manager->dbtypes as $key => $type) {
if (in_array($dbtype, $type)) {
$phptype= $key;
break;
}
}
return $phptype;
}
/**
* Format the passed default value as an XML attribute.
*
* @access public
* @param string $value The value to encapsulate in the default tag.
* @return string The parsed XML string
*/
public function getDefault($value) {
$return= '';
if ($value !== null) {
$return= ' default="'.$value.'"';
}
return $return;
}
/**
* Format the passed database index value as an XML attribute.
*
* @access public
* @param string $index The DB representation string of the index
* @return string The formatted XML attribute string
*/
public function getIndex($index) {
switch ($index) {
case 'PRI':
$index= 'pk';
break;
case 'UNI':
$index= 'unique';
break;
case 'MUL':
$index= 'index';
break;
default:
break;
}
if (!empty ($index)) {
$index= ' index="' . $index . '"';
}
return $index;
}
/**
* Parses an XPDO XML schema and generates classes and map files from it.
*
* @param string $schemaFile The name of the XML file representing the
* schema.
* @param string $outputDir The directory in which to generate the class and
* map files into.
* @param boolean $compile Create compiled copies of the classes and maps from the schema.
* @return boolean True on success, false on failure.
*/
public function parseSchema($schemaFile, $outputDir= '', $compile= false) {
$this->schemaFile= $schemaFile;
$this->classTemplate= $this->getClassTemplate();
if (!is_file($schemaFile)) {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not find specified XML schema file {$schemaFile}");
return false;
} else {
$fileContent= @ file($schemaFile);
$this->schemaContent= implode('', $fileContent);
}
/* Create the parser and set handlers. */
$this->xmlParser= xml_parser_create('UTF-8');
xml_set_object($this->xmlParser, $this);
xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($this->xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
xml_set_element_handler($this->xmlParser, '_handleOpenElement', '_handleCloseElement');
xml_set_character_data_handler($this->xmlParser, "_handleCData");
/* Parse it. */
if (!xml_parse($this->xmlParser, $this->schemaContent)) {
$ln= xml_get_current_line_number($this->xmlParser);
$msg= xml_error_string(xml_get_error_code($this->xmlParser));
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error parsing XML schema on line $ln: $msg");
return false;
}
/* Free up the parser and clear memory */
xml_parser_free($this->xmlParser);
unset ($this->xmlParser);
$om_path= XPDO_CORE_PATH . 'om/';
$path= !empty ($outputDir) ? $outputDir : $om_path;
if (isset ($this->model['package']) && strlen($this->model['package']) > 0) {
$path .= strtr($this->model['package'], '.', '/');
$path .= '/';
}
$this->outputClasses($path);
$this->outputMaps($path);
if ($compile) $this->compile($path, $this->model, $this->classes, $this->maps);
unset($this->model, $this->classes, $this->map);
return true;
}
/**
* Handles formatting of the open XML element.
*
* @access private
* @param xmlParser &$parser
* @param string &$element
* @param array &$attributes
*/
protected function _handleOpenElement(& $parser, & $element, & $attributes) {
$element= strtolower($element);
switch ($element) {
case 'model' :
while (list ($attrName, $attrValue)= each($attributes)) {
$this->model[$attrName]= $attrValue;
}
break;
case 'object' :
while (list ($attrName, $attrValue)= each($attributes)) {
switch ($attrName) {
case 'class' :
$this->className= "{$attrValue}";
if (!isset ($this->classes[$this->className])) {
$this->classes[$this->className]= array ();
$this->map[$this->className]= array ();
$this->classes[$this->className]['extends']= $this->model['baseClass'];
}
if (isset ($this->model['package'])) {
$this->map[$this->className]['package']= $this->model['package'];
}
break;
case 'table' :
$this->map[$this->className]['table']= $attrValue;
break;
case 'extends' :
$this->classes[$this->className]['extends']= $attrValue;
break;
}
}
break;
case 'field' :
while (list ($attrName, $attrValue)= each($attributes)) {
switch ($attrName) {
case 'key' :
$this->fieldKey= "{$attrValue}";
$this->map[$this->className]['fields'][$this->fieldKey]= null;
$this->map[$this->className]['fieldMeta'][$this->fieldKey]= array ();
break;
case 'default' :
$attrValue = ($attrValue === 'NULL' ? null : $attrValue);
$attrValue = in_array(strtoupper($attributes['dbtype']), $this->manager->dbtypes['integer']) ? intval($attrValue) : $attrValue;
$attrValue = in_array(strtoupper($attributes['dbtype']), $this->manager->dbtypes['boolean']) ? intval($attrValue) : $attrValue;
$attrValue = in_array(strtoupper($attributes['dbtype']), $this->manager->dbtypes['bit']) ? intval($attrValue) : $attrValue;
$attrValue = in_array(strtoupper($attributes['dbtype']), $this->manager->dbtypes['float']) ? floatval($attrValue) : $attrValue;
$this->map[$this->className]['fields'][$this->fieldKey]= $attrValue;
$this->map[$this->className]['fieldMeta'][$this->fieldKey]['default']= $attrValue;
break;
case 'null' :
$attrValue = ($attrValue && $attrValue !== 'false' ? true : false);
default :
$this->map[$this->className]['fieldMeta'][$this->fieldKey][$attrName]= $attrValue;
break;
}
}
break;
case 'aggregate' :
$alias= '';
$node= array ();
while (list ($attrName, $attrValue)= each($attributes)) {
switch ($attrName) {
case 'alias' :
$alias= "{$attrValue}";
break;
default :
$node[$attrName]= $attrValue;
break;
}
}
if ($alias && $node) {
$this->map[$this->className]['aggregates'][$alias]= $node;
}
break;
case 'composite' :
$alias= '';
$node= array ();
while (list ($attrName, $attrValue)= each($attributes)) {
switch ($attrName) {
case 'alias' :
$alias= "{$attrValue}";
break;
default :
$node[$attrName]= $attrValue;
break;
}
}
if ($alias && $node) {
$this->map[$this->className]['composites'][$alias]= $node;
}
break;
case 'validation' :
$node= array ();
while (list ($attrName, $attrValue)= each($attributes)) {
$node[$attrName]= $attrValue;
}
if ($node) {
$node['rules']= array();
$this->map[$this->className]['validation']= $node;
}
break;
case 'rule' :
$field= '';
$name= '';
$node= array ();
while (list ($attrName, $attrValue)= each($attributes)) {
switch ($attrName) {
case 'field' :
$field= "{$attrValue}";
break;
case 'name' :
$name= "{$attrValue}";
break;
default :
$node[$attrName]= $attrValue;
break;
}
}
if ($field && $name && $node) {
$this->map[$this->className]['validation']['rules'][$field][$name]= $node;
}
break;
}
}
/**
* Handles the closing of XML tags.
*
* @access private
*/
protected function _handleCloseElement(& $parser, & $element) {}
/**
* Handles the XML CDATA tags
*
* @access private
*/
protected function _handleCData(& $parser, & $data) {}
/**
* Write the generated class files to the specified path.
*
* @access public
* @param string $path An absolute path to write the generated class files
* to.
*/
public function outputClasses($path) {
$newClassGeneration= false;
$newPlatformGeneration= false;
$platform= $this->model['platform'];
if (!is_dir($path)) {
$newClassGeneration= true;
mkdir($path, 0777);
}
$ppath= $path;
$ppath .= $platform;
if (!is_dir($ppath)) {
$newPlatformGeneration= true;
mkdir($ppath, 0777);
}
$model= $this->model;
if (isset($this->model['phpdoc-package'])) {
$model['phpdoc-package']= '@package ' . $this->model['phpdoc-package'];
if (isset($this->model['phpdoc-subpackage']) && !empty($this->model['phpdoc-subpackage'])) {
$model['phpdoc-subpackage']= '@subpackage ' . $this->model['phpdoc-subpackage'] . '.' . $this->model['platform'];
} else {
$model['phpdoc-subpackage']= '@subpackage ' . $this->model['platform'];
}
} else {
$basePos= strpos($this->model['package'], '.');
$package= $basePos
? substr($this->model['package'], 0, $basePos)
: $this->model['package'];
$subpackage= $basePos
? substr($this->model['package'], $basePos + 1)
: '';
$model['phpdoc-package']= '@package ' . $package;
if ($subpackage) $model['phpdoc-subpackage']= '@subpackage ' . $subpackage;
}
foreach ($this->classes as $className => $classDef) {
$newClass= false;
$classDef['class']= $className;
$classDef['class-lowercase']= strtolower($className);
$classDef= array_merge($model, $classDef);
$replaceVars= array ();
foreach ($classDef as $varKey => $varValue) {
if (is_scalar($varValue)) $replaceVars["[+{$varKey}+]"]= $varValue;
}
$fileContent= str_replace(array_keys($replaceVars), array_values($replaceVars), $this->classTemplate);
if (is_dir($path)) {
$fileName= $path . '/' . strtolower($className) . '.class.php';
if (!file_exists($fileName)) {
if ($file= @ fopen($fileName, 'wb')) {
if (!fwrite($file, $fileContent)) {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not write to file: {$fileName}");
}
$newClass= true;
@fclose($file);
} else {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not open or create file: {$fileName}");
}
} else {
$newClass= false;
$this->manager->xpdo->log(xPDO::LOG_LEVEL_INFO, "Skipping {$fileName}; file already exists.\nMove existing class files to regenerate them.");
}
} else {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not open or create dir: {$path}");
}
$fileContent= str_replace(array_keys($replaceVars), array_values($replaceVars), $this->getClassPlatformTemplate($platform));
if (is_dir($ppath)) {
$fileName= $ppath . '/' . strtolower($className) . '.class.php';
if (!file_exists($fileName)) {
if ($file= @ fopen($fileName, 'wb')) {
if (!fwrite($file, $fileContent)) {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not write to file: {$fileName}");
}
@fclose($file);
} else {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not open or create file: {$fileName}");
}
} else {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_INFO, "Skipping {$fileName}; file already exists.\nMove existing class files to regenerate them.");
if ($newClassGeneration || $newClass) $this->manager->xpdo->log(xPDO::LOG_LEVEL_WARN, "IMPORTANT: {$fileName} already exists but you appear to have generated classes with an older xPDO version. You need to edit your class definition in this file to extend {$className} rather than {$classDef['extends']}.");
}
} else {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not open or create dir: {$path}");
}
}
}
/**
* Write the generated class maps to the specified path.
*
* @access public
* @param string $path An absolute path to write the generated maps to.
*/
public function outputMaps($path) {
if (!is_dir($path)) {
mkdir($path, 0777);
}
$path .= $this->model['platform'];
if (!is_dir($path)) {
mkdir($path, 0777);
}
$model= $this->model;
if (isset($this->model['phpdoc-package'])) {
$model['phpdoc-package']= '@package ' . $this->model['phpdoc-package'];
if (isset($this->model['phpdoc-subpackage']) && !empty($this->model['phpdoc-subpackage'])) {
$model['phpdoc-subpackage']= '@subpackage ' . $this->model['phpdoc-subpackage'] . '.' . $this->model['platform'];
} else {
$model['phpdoc-subpackage']= '@subpackage ' . $this->model['platform'];
}
} else {
$basePos= strpos($this->model['package'], '.');
$package= $basePos
? substr($this->model['package'], 0, $basePos)
: $this->model['package'];
$subpackage= $basePos
? substr($this->model['package'], $basePos + 1) . '.' . $this->model['platform']
: $this->model['platform'];
$model['phpdoc-package']= '@package ' . $package;
$model['phpdoc-subpackage']= '@subpackage ' . $subpackage;
}
foreach ($this->map as $className => $map) {
$lcClassName= strtolower($className);
$fileName= $path . '/' . strtolower($className) . '.map.inc.php';
$vars= array_merge($model, $map);
$replaceVars= array ();
foreach ($vars as $varKey => $varValue) {
if (is_scalar($varValue)) $replaceVars["[+{$varKey}+]"]= $varValue;
}
$fileContent= str_replace(array_keys($replaceVars), array_values($replaceVars), $this->getMapHeader());
$fileContent.= "\n\$xpdo_meta_map['$className']= " . var_export($map, true) . ";\n";
$fileContent.= str_replace(array_keys($replaceVars), array_values($replaceVars), $this->getMapFooter());
if (is_dir($path)) {
if ($file= @ fopen($fileName, 'wb')) {
if (!fwrite($file, $fileContent)) {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not write to file: {$fileName}");
}
fclose($file);
} else {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not open or create file: {$fileName}");
}
} else {
$this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not open or create dir: {$path}");
}
}
}
/**
* Compile the packages into a single file for quicker loading.
*
* @todo Implement this to compile packages into a single file for quicker
* loading
*
* @access public
* @param string $path The absolute path to compile into.
* @return boolean True if the compiling went successfully.
*/
public function compile($path= '') {
$compiled= false;
return $compiled;
}
/**
* Return the class template for the class files.
*
* @access public
* @return string The class template.
*/
public function getClassTemplate() {
if ($this->classTemplate) return $this->classTemplate;
$template= <<<EOD
<?php
class [+class+] extends [+extends+] {
public function __construct(& \$xpdo) {
parent :: __construct(\$xpdo);
}
}
?>
EOD;
return $template;
}
/**
* Return the class platform template for the class files.
*
* @access public
* @return string The class platform template.
*/
public function getClassPlatformTemplate($platform) {
if ($this->platformTemplate) return $this->platformTemplate;
$template= <<<EOD
<?php
require_once (strtr(realpath(dirname(dirname(__FILE__))), '\\\\', '/') . '/[+class-lowercase+].class.php');
class [+class+]_$platform extends [+class+] {
public function __construct(& \$xpdo) {
parent :: __construct(\$xpdo);
}
}
?>
EOD;
return $template;
}
/**
* Gets the map header template.
*
* @access public
* @return string The map header template.
*/
public function getMapHeader() {
if ($this->mapHeader) return $this->mapHeader;
$header= <<<EOD
<?php
EOD;
return $header;
}
/**
* Gets the map footer template.
*
* @access public
* @return string The map footer template.
*/
public function getMapFooter() {
if ($this->mapFooter) return $this->mapFooter;
return '';
}
}