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