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         $standard_database = $options['database'];
115        
116        
117          
118        
119        
120        
121        
122        
123        
124         parent::start();
125         
126         $this->scanModules();
127         require_once 'System.php';
128         $diff = System::which('diff');
129         // now for each of the directories copy/show diffs..
130         echo $cli ? '' : '<PRE>';
131         $flist = explode(',', $overwrite);
132         foreach($this->modtables as $m=>$ar) {
133             if ($options['database'] !=  $standard_database) {
134                 $options['database'] =  $standard_database ;
135                 
136                 parent::start();
137             }
138             
139             $options['database'] =  $standard_database ;
140             if (isset($options['database_'. $m])) {
141                 $options['database'] =  $options['database_'. $m];
142                 //var_dump($url);exit;
143                 
144                 // start again?
145                 parent::start();
146             }
147             
148             
149             if (!empty($options['mods'] ) && !in_array($m,  $options['mods'] )) {
150                 continue;
151             }
152             // this happens when we have no database tables from a module,
153             // but module code has been defined.
154             if (!file_exists($options['rootDir'].'/'.$m)) {
155                 continue;
156             }
157             foreach(scandir($options['rootDir'].'/'.$m) as $f) {
158                 if (!strlen($f) || $f[0] == '.') {
159                     continue;
160                 }
161                 // does it exist!!!
162                 $src = $options['rootDir']."/$m/$f";
163                 $tg = $ff->page->rootDir."/Pman/$m/DataObjects/$f";
164                 if (preg_match('/\.js$/', $f)) {
165                     $tg = $ff->page->rootDir."/Pman/$m/$f";
166                 }
167                 
168                 if (!file_exists($tg) || !filesize($tg) ) {
169                   
170                     if ($cli && !filesize($tg) || in_array($f, $flist)) {
171                         echo "COPY $src $tg" . ($cli ? "\n" : "<BR>");
172                         copy($src, $tg);
173                         continue;
174                     }
175                     echo "!!!!MISSING!!! $tg" . ($cli ? "\n" : "<BR>");
176                     
177                     continue;
178                 }
179                 // always copy readers and ini file.=  nope - not on live..
180                 if ($cli && in_array($f, $flist) || in_array('_all_', $flist )) {
181                     
182                    //|| $f=='pman.ini' || preg_match('/\.js$/', $f))) {
183                     echo "COPY $src $tg". ($cli ? "\n" : "<BR>");
184                     copy($src, $tg);
185                     continue;
186                 }
187                 
188                 // diff the two..
189                 $cmd = "$diff -u -w ". escapeshellarg($tg) . ' ' . escapeshellarg($src);
190                  
191                 $out = array(); $ret = 0;
192                 exec($cmd, $out, $ret);
193                 if ($ret ==0) { // files match..
194                     continue;
195                 }
196                 // var_dump($ret);
197                 echo "\n" .implode( "\n" , $out) . "\n";
198                
199                 
200             }
201             
202             
203         }
204         
205         
206         
207         
208     }
209      
210     /**
211      * Scan the folders for DataObjects
212      * - Use the list of php files in DataObjects folders 
213      *   to determine which module owns which database table.
214      * 
215      */
216     
217     
218     function scanModules()
219     {
220         
221         $options = &PEAR::getStaticProperty('DB_DataObject','options');
222         if (isset($options['modtables'])) {
223             $this->modtables = $options['modtables'];
224             $this->modmap = $options['modmap'];
225             $this->modsql = $options['modsql'];
226             return;
227         }
228         
229         $ff = HTML_Flexyframework::get();
230         
231         $top = $ff->page->rootDir .'/Pman';
232         $this->modtables = array();
233         $this->modmap = array();
234         $this->modmapsql = array();
235         
236         foreach(scandir($top) as $m) {
237             
238             if (!strlen($m) || 
239                     $m[0] == '.' || 
240                     !is_dir($top .'/'.$m) || 
241                     !file_exists($top .'/'.$m.'/DataObjects')
242                 ) {
243                 continue;
244             }
245             $this->modtables[$m] = array();
246             $this->modsql[$m] = array();
247             foreach(scandir($top .'/'.$m.'/DataObjects') as $f) {
248                 if (!strlen($f) ||   $m[0] == '.') {
249                     continue;
250                 }
251                 if (preg_match('/\.sql$/', $f))  {
252                     $this->modsql[$m][] = $f;
253                 }
254                                 
255                 if (preg_match('/\.php$/', $f))  {
256                     $tn = strtolower(preg_replace('/\.php$/', '', $f));
257                     $this->modtables[$m][] = $tn;
258                     $this->modmap[$tn] = $m;
259                     continue;
260                 }
261             }
262         }
263         $options['modtables'] = $this->modtables;
264         $options['modmap'] = $this->modmap;
265         $options['modsql'] = $this->modsql;
266        // print_r($options);
267         
268     }
269     /**
270      * 
271      * this is run first, so picks up any missing dataobject files..
272      */
273     
274     function generateDefinitions()
275     {
276         if (!$this->tables) {
277             $this->debug("-- NO TABLES -- \n");
278             return;
279         }
280         if (!isset($this->modmap)) {
281             $this->scanModules();
282         }
283          $options = &PEAR::getStaticProperty('DB_DataObject','options');
284         $builder_options = PEAR::getStaticProperty('Pman_Builder','options');
285         $ignore = empty($builder_options['skip_tables']) ? array() : $builder_options['skip_tables'];
286         
287          $mods = $options['mods'];
288         $inis = array();
289         $this->_newConfig = '';
290         foreach($this->tables as $this->table) {
291             
292             $tn  = strtolower($this->table);
293             //print_r($this->modmap);//[$tn]);//
294             
295             
296             
297             if (!isset($this->modmap[$tn])) {
298                 
299                 if (in_array($this->table, $ignore)) {
300                     continue;
301                 }
302                 if (empty($mods)) {
303                 
304                 
305                    die("No existing DataObject file found for table {$this->table} 
306             
307 - either add it to Pman_Builder[skip_tables] or\n
308 - run generator and specify that module..
309 - create an empty file in the related Module/DataObjects directory
310 eg. 
311 touch Pman/????/DataObjects/".ucfirst($this->table).".php
312    
313    ");
314                 }
315                 // use mods to determine where it should output to..
316                 //var_dump($mods);exit;
317                 $this->modmap[$tn] = $mods[0];
318                 
319                 
320             }
321             $mod = $this->modmap[$tn];
322             $inis[$mod] = isset($inis[$mod]) ? $inis[$mod] : '';
323             
324             
325             $this->_newConfig = '';
326             $this->_generateDefinitionsTable();
327             
328             
329             $inis[$mod] .= $this->_newConfig;
330         }
331         return; // we do not generate in ifiles any more..
332          
333     }
334     
335     function generateClasses() 
336     {
337       // print_R($this->modmap);
338        // die("generateClasses");
339         $options = &PEAR::getStaticProperty('DB_DataObject','options');
340         
341         $ff = HTML_Flexyframework::get();
342         
343         $rd = $options['rootDir'];
344         $mods = $options['mods'];
345         $this->_extends = 'DB_DataObject';
346         $this->_extendsFile = 'DB/DataObject.php';
347         $cli = $options['cli'];
348
349         foreach($this->tables as $this->table) {
350             $this->table        = trim($this->table);
351             $tn  = strtolower($this->table);
352             $mod = $this->modmap[$tn];
353             
354              if (!empty($mods) && !in_array($mod, $mods)) {
355                 continue;
356             }
357             
358             
359             $this->classname    = 'Pman_'.$mod . '_DataObjects_'. ucfirst($this->table); // replace odd chars?
360            
361            
362             $outfilename    = $rd.'/'.$mod.'/'. ucfirst($this->table).'.php';
363             $orig           = $ff->page->rootDir .'/Pman/'.$mod.'/DataObjects/'. ucfirst($this->table).'.php';
364             
365            
366                 // file_get_contents???
367             
368             $oldcontents = file_exists($orig) ? file_get_contents($orig) : '';
369             
370              
371             echo "GENERATE: " .   $this->classname  . ($cli ? "\n" : "<BR>");
372             
373             $out = $this->_generateClassTable($oldcontents);
374             
375             // get rid of static GET!!!
376             $out = preg_replace('/(\n|\r\n)\s*function staticGet[^\n]+(\n|\r\n)/s', '', $out);
377             $out = preg_replace('#/\* Static get \*/#s', '', $out);
378               
379             if (!file_exists(dirname($outfilename))) {
380                 mkdir(dirname($outfilename), 0755, true);
381             }
382            // $this->debug( "writing $this->classname\n");
383             //$tmpname = tempnam(session_save_path(),'DataObject_');
384             file_put_contents($outfilename, $out);
385             
386         }
387     }
388     
389     
390         
391    // function generateDefinitions() { }
392     ////function generateForeignKeys() { }
393    // function generateClasses() { }
394    
395       
396      
397      
398    
399     function parseConfig()
400     {
401          $options = &PEAR::getStaticProperty('DB_DataObject','options');
402         
403         if (isset($options['modtables'])) {
404             $this->modtables = $options['modtables'];
405             $this->modmap = $options['modmap'];
406             $this->modsql = $options['modsql'];
407         }
408         
409         $ff = HTML_Flexyframework::get();
410         $dirs = array($ff->page->rootDir.'/Pman/DataObjects'); // not used anymore!
411         foreach($this->modtables as $m=>$ts) {
412             $dirs[] = $ff->page->rootDir.'/Pman/'.$m.'/DataObjects';
413         }
414         
415          //echo '<PRE>';print_R($ini);//exit;
416         
417         
418          
419     }
420      
421         //var_dump($table);
422         //print_r( $this->def['readers'][$table]);
423        // print_r( $this->def['colmodels'][$table]);
424         //print_r($this->def['readers'][$table]); exit;
425         
426       
427        
428     function writeFileEx($n, $f, $str) 
429     {
430         if (file_exists($f)) {
431             // all - will not overwrite stuff.. (only being specific willl)
432             if (!in_array($n, $this->overwrite)) {
433                 $this->writeFile($f.'.generated',$str);
434                 return;
435             }
436         }
437         $this->writeFile($f,$str);
438         
439         
440     }
441     function writeFile($f, $str)
442     {
443         require_once 'System.php';
444         System::mkdir(array('-p', dirname($f)));
445         // overwrite???
446         echo "write: $f\n";
447         file_put_contents($f, $str);
448     } 
449    
450 }
451