Generator.php
[Pman.Core] / Generator.php
1 <?php
2  
3  
4 /**
5  * 
6  * Generate DataObjects...
7  * 
8  * This does not generate ini files any more - as that is done on the fly by the framework.
9  * 
10  * note - we write to a temporary directory first...
11  * 
12  * 
13  */
14  
15 require_once 'DB/DataObject/Generator.php';
16
17
18 /** basic thing now works... 
19
20 * it needs a bit more intelligence to work out what to do...
21
22
23 * Basically we need to build up all the formats for each db column
24 * then 
25 *   - overlay any mapping stuff.
26 *   
27 *   - overlay user defined settings
28 *   = write it out to file..
29 *   
30 *  Strucutres:
31 $this->def['order'][$table][] = $t->name;
32 $this->def['readers'][$table][$t->name] = $reader;
33 $this->def['colmodels'][$table][$t->name] = $colmodel;
34 $this->def['forms'][$table][$t->name] = $form;
35
36 *   Readers
37 *       readersDef[table.col]
38
39
40
41 * **/
42
43
44
45 class Pman_Core_Generator extends DB_DataObject_Generator
46 {
47     
48
49    
50     // inherrited..
51     // $tablekeys
52     // $tables
53     // $_definitions
54     /**
55      * def[order]  
56      *      [tablename] => array( list of columns ones with '-' indicate lookup
57      *    [readers]
58      *       [tablename][colname] -> reader foramt
59      *    [forms]
60      *        [tablename][colname] => xtype / name etc...
61      *    [readerArgs]
62      *        [tablename] => data for reader args (eg. id / total prop etc.)
63      *  readers =>
64      *         [tablename] => array of cols with types
65      *  forms =>
66      *        [tablename] -> array of cols
67      * 
68      */ 
69     var $def;
70     
71       
72     var $page = false; // page container when run from cli.
73     
74     // dont do usual stuff!!!
75     var $rootDir = '';
76     var $tablekeys = array();
77     
78     var $overwrite = array(); // default dont overwrite any of the files..
79     //  array('master', 'corejs', 'corephp', 'index', 'Roo')
80     // and ('js-?????' where ??? is the table name) <- for all the generated js classes.
81     // we always overwrite the definition!!!
82     // set to array('all') to overwrite everything!!!
83     
84     function start($cli=false, $mods='', $overwrite='')
85     {
86         
87         $ff = HTML_Flexyframework::get();
88         $this->scanModules();
89         //echo '<PRE>'; print_r($this->modtables); exit;
90         
91         $options = &PEAR::getStaticProperty('DB_DataObject','options');
92         
93         
94         $proj = 'pman'; //ucfirst(basename($options['database']));
95         // we are going to generate all of the code into a temporay foldler..
96         $user = posix_getpwuid(posix_getuid());
97         
98         $options['rootDir'] = ini_get('session.save_path').'/temp_'. $proj.'_'. $user['name'];
99         $options['cli'] = $cli;
100         $options['mods'] = empty($mods) ? array() : explode('/',$mods);
101        
102         if (!file_exists($options['rootDir'])) {
103             mkdir($options['rootDir'], 0775, true);
104         }
105         
106         $this->rootDir = $options['rootDir'];
107         $options['schema_location'] =  $this->rootDir .'/'.$proj.'/DataObjects';
108         $options['class_location'] = $this->rootDir .'/'.$proj.'/DataObjects';
109         $options['require_prefix'] =    $proj . '/DataObjects/';
110         $options['class_prefix'] =    $proj . '_DataObjects_';
111        //  print_r($this);exit;
112        
113        
114         $this->importSQL();
115        
116         $standard_database = $options['database'];
117        
118        
119        
120        
121        
122        
123        
124        
125        
126         parent::start();
127         
128         $this->scanModules();
129         require_once 'System.php';
130         $diff = System::which('diff');
131         // now for each of the directories copy/show diffs..
132         echo $cli ? '' : '<PRE>';
133         $flist = explode(',', $overwrite);
134         foreach($this->modtables as $m=>$ar) {
135             if ($options['database'] !=  $standard_database) {
136                 $options['database'] =  $standard_database ;
137                 
138                 parent::start();
139             }
140             
141             $options['database'] =  $standard_database ;
142             if (isset($options['database_'. $m])) {
143                 $options['database'] =  $options['database_'. $m];
144                 //var_dump($url);exit;
145                 
146                 // start again?
147                 parent::start();
148             }
149             
150             
151             if (!empty($options['mods'] ) && !in_array($m,  $options['mods'] )) {
152                 continue;
153             }
154             foreach(scandir($options['rootDir'].'/'.$m) as $f) {
155                 if (!strlen($f) || $f[0] == '.') {
156                     continue;
157                 }
158                 // does it exist!!!
159                 $src = $options['rootDir']."/$m/$f";
160                 $tg = $ff->page->rootDir."/Pman/$m/DataObjects/$f";
161                 if (preg_match('/\.js$/', $f)) {
162                     $tg = $ff->page->rootDir."/Pman/$m/$f";
163                 }
164                 
165                 if (!file_exists($tg) || !filesize($tg) ) {
166                   
167                     if ($cli && !filesize($tg) || in_array($f, $flist)) {
168                         echo "COPY $src $tg" . ($cli ? "\n" : "<BR>");
169                         copy($src, $tg);
170                         continue;
171                     }
172                     echo "!!!!MISSING!!! $tg" . ($cli ? "\n" : "<BR>");
173                     
174                     continue;
175                 }
176                 // always copy readers and ini file.=  nope - not on live..
177                 if ($cli && in_array($f, $flist)) {
178                     
179                    //|| $f=='pman.ini' || preg_match('/\.js$/', $f))) {
180                     echo "COPY $src $tg". ($cli ? "\n" : "<BR>");
181                     copy($src, $tg);
182                     continue;
183                 }
184                 
185                 // diff the two..
186                 $cmd = "$diff -u -w ". escapeshellarg($tg) . ' ' . escapeshellarg($src);
187                  
188                 $out = array(); $ret = 0;
189                 exec($cmd, $out, $ret);
190                 if ($ret ==0) { // files match..
191                     continue;
192                 }
193                 // var_dump($ret);
194                 echo "\n" .implode( "\n" , $out) . "\n";
195                
196                 
197             }
198             
199             
200         }
201         
202         
203         
204         
205     }
206     /**
207      * imports SQL files from all DataObjects directories....
208      * 
209      * except any matching /migrate/
210      */
211     function importSQL()
212     {
213         $options = &PEAR::getStaticProperty('DB_DataObject','options');
214         
215         $ff = HTML_Flexyframework::get();
216         
217         $url = parse_url($options['database']);
218         // hide stuff for web..
219         $cli = $options['cli'];
220         if (!$cli) {
221             $url['pass'] = '*****';
222             $url['user'] = '*****';
223             $url['host'] = '*****';
224         }
225         
226         require_once 'System.php';
227         $cat = System::which('cat');
228         $mysql = System::which('mysql');
229         print_r($options['mods'] );
230         foreach($this->modsql as $m => $fl)
231         {
232             if ($cli && isset($options['database_'. $m])) {
233                 $url = parse_url($options['database_'.$m]);
234             }
235             
236             $mysql_cmd = $mysql .
237                 ' -h ' . $url['host'] .
238                 ' -u' . escapeshellarg($url['user']) .
239                 (!empty($url['pass']) ? ' -p' . escapeshellarg($url['pass'])  :  '') .
240                 ' ' . basename($url['path']);
241            
242             echo $mysql_cmd . "\n" ;
243             
244             if (!empty($options['mods'] ) && !in_array($m,  $options['mods'] )) {
245                 continue;
246             }
247             
248             foreach($fl as $f) {
249                 $fn = $ff->page->rootDir. "/Pman/$m/DataObjects/$f";
250                 if (preg_match('/migrate/i', $f)) { // skip migration scripts at present..
251                     continue;
252                 }
253                 
254                 $cmd = $cat . ' ' . escapeshellarg($fn) . " | $mysql_cmd -f ";
255                 echo $cmd. ($cli ? "\n" : "<BR>\n");
256                 if ($cli) {
257                     passthru($cmd);
258                 }
259                 
260             }
261         }
262         
263         
264         
265     }
266     /**
267      * Scan the folders for DataObjects
268      * - Use the list of php files in DataObjects folders 
269      *   to determine which module owns which database table.
270      * 
271      */
272     
273     
274     function scanModules()
275     {
276         
277         $options = &PEAR::getStaticProperty('DB_DataObject','options');
278         if (isset($options['modtables'])) {
279             $this->modtables = $options['modtables'];
280             $this->modmap = $options['modmap'];
281             $this->modsql = $options['modsql'];
282             return;
283         }
284         
285         $ff = HTML_Flexyframework::get();
286         
287         $top = $ff->page->rootDir .'/Pman';
288         $this->modtables = array();
289         $this->modmap = array();
290         $this->modmapsql = array();
291         
292         foreach(scandir($top) as $m) {
293             
294             if (!strlen($m) || 
295                     $m[0] == '.' || 
296                     !is_dir($top .'/'.$m) || 
297                     !file_exists($top .'/'.$m.'/DataObjects')
298                 ) {
299                 continue;
300             }
301             $this->modtables[$m] = array();
302             $this->modsql[$m] = array();
303             foreach(scandir($top .'/'.$m.'/DataObjects') as $f) {
304                 if (!strlen($f) ||   $m[0] == '.') {
305                     continue;
306                 }
307                 if (preg_match('/\.sql$/', $f))  {
308                     $this->modsql[$m][] = $f;
309                 }
310                                 
311                 if (preg_match('/\.php$/', $f))  {
312                     $tn = strtolower(preg_replace('/\.php$/', '', $f));
313                     $this->modtables[$m][] = $tn;
314                     $this->modmap[$tn] = $m;
315                     continue;
316                 }
317             }
318         }
319         $options['modtables'] = $this->modtables;
320         $options['modmap'] = $this->modmap;
321         $options['modsql'] = $this->modsql;
322        // print_r($options);
323         
324     }
325     /**
326      * 
327      * this is run first, so picks up any missing dataobject files..
328      */
329     
330     function generateDefinitions()
331     {
332         if (!$this->tables) {
333             $this->debug("-- NO TABLES -- \n");
334             return;
335         }
336         if (!isset($this->modmap)) {
337             $this->scanModules();
338         }
339          $options = &PEAR::getStaticProperty('DB_DataObject','options');
340         $builder_options = PEAR::getStaticProperty('Pman_Builder','options');
341         $ignore = empty($builder_options['skip_tables']) ? array() : $builder_options['skip_tables'];
342         
343          $mods = $options['mods'];
344         $inis = array();
345         $this->_newConfig = '';
346         foreach($this->tables as $this->table) {
347             
348             $tn  = strtolower($this->table);
349             //print_r($this->modmap);//[$tn]);//
350             
351             
352             
353             if (!isset($this->modmap[$tn])) {
354                 
355                 if (in_array($this->table, $ignore)) {
356                     continue;
357                 }
358                 if (empty($mods)) {
359                 
360                 
361                    die("No existing DataObject file found for table {$this->table} 
362             
363 - either add it to Pman_Builder[skip_tables] or\n
364 - create an empty file in the related Module/DataObjects directory
365 eg. 
366 touch Pman/????/DataObjects/".ucfirst($this->table).".php
367    
368    ");
369                 }
370                 // use mods to determine where it should output to..
371                 $this->modmap[$tn] = $mods;
372                 
373                 
374             }
375             $mod = $this->modmap[$tn];
376             $inis[$mod] = isset($inis[$mod]) ? $inis[$mod] : '';
377             
378             
379             $this->_newConfig = '';
380             $this->_generateDefinitionsTable();
381             
382             
383             $inis[$mod] .= $this->_newConfig;
384         }
385         return; // we do not generate in ifiles any more..
386          
387     }
388     
389     function generateClasses() 
390     {
391       // print_R($this->modmap);
392        // die("generateClasses");
393         $options = &PEAR::getStaticProperty('DB_DataObject','options');
394         
395         $ff = HTML_Flexyframework::get();
396         
397         $rd = $options['rootDir'];
398         $mods = $options['mods'];
399         $this->_extends = 'DB_DataObject';
400         $this->_extendsFile = 'DB/DataObject.php';
401         $cli = $options['cli'];
402
403         foreach($this->tables as $this->table) {
404             $this->table        = trim($this->table);
405             $tn  = strtolower($this->table);
406             $mod = $this->modmap[$tn];
407             
408              if (!empty($mods) && !in_array($mod, $mods)) {
409                 continue;
410             }
411             
412             
413             $this->classname    = 'Pman_'.$mod . '_DataObjects_'. ucfirst($this->table); // replace odd chars?
414            
415            
416             $outfilename    = $rd.'/'.$mod.'/'. ucfirst($this->table).'.php';
417             $orig           = $ff->page->rootDir .'/Pman/'.$mod.'/DataObjects/'. ucfirst($this->table).'.php';
418             
419            
420                 // file_get_contents???
421             $oldcontents = file_get_contents($orig);
422             
423              
424             echo "GENERATE: " .   $this->classname  . ($cli ? "\n" : "<BR>");
425             
426             $out = $this->_generateClassTable($oldcontents);
427             
428             // get rid of static GET!!!
429             $out = preg_replace('/(\n|\r\n)\s*function staticGet[^\n]+(\n|\r\n)/s', '', $out);
430             $out = preg_replace('#/\* Static get \*/#s', '', $out);
431               
432             if (!file_exists(dirname($outfilename))) {
433                 mkdir(dirname($outfilename), 0755, true);
434             }
435            // $this->debug( "writing $this->classname\n");
436             //$tmpname = tempnam(session_save_path(),'DataObject_');
437             file_put_contents($outfilename, $out);
438             
439         }
440     }
441     
442     
443         
444    // function generateDefinitions() { }
445     ////function generateForeignKeys() { }
446    // function generateClasses() { }
447    
448       
449      
450      
451    
452     function parseConfig()
453     {
454          $options = &PEAR::getStaticProperty('DB_DataObject','options');
455         
456         if (isset($options['modtables'])) {
457             $this->modtables = $options['modtables'];
458             $this->modmap = $options['modmap'];
459             $this->modsql = $options['modsql'];
460         }
461         
462         $ff = HTML_Flexyframework::get();
463         $dirs = array($ff->page->rootDir.'/Pman/DataObjects'); // not used anymore!
464         foreach($this->modtables as $m=>$ts) {
465             $dirs[] = $ff->page->rootDir.'/Pman/'.$m.'/DataObjects';
466         }
467         
468          //echo '<PRE>';print_R($ini);//exit;
469         
470         
471          
472     }
473      
474         //var_dump($table);
475         //print_r( $this->def['readers'][$table]);
476        // print_r( $this->def['colmodels'][$table]);
477         //print_r($this->def['readers'][$table]); exit;
478         
479       
480        
481     function writeFileEx($n, $f, $str) 
482     {
483         if (file_exists($f)) {
484             // all - will not overwrite stuff.. (only being specific willl)
485             if (!in_array($n, $this->overwrite)) {
486                 $this->writeFile($f.'.generated',$str);
487                 return;
488             }
489         }
490         $this->writeFile($f,$str);
491         
492         
493     }
494     function writeFile($f, $str)
495     {
496         require_once 'System.php';
497         System::mkdir(array('-p', dirname($f)));
498         // overwrite???
499         echo "write: $f\n";
500         file_put_contents($f, $str);
501     } 
502    
503 }
504