PageRenderTime 45ms CodeModel.GetById 16ms app.highlight 24ms RepoModel.GetById 1ms app.codeStats 0ms

/core/general/Models.php

http://oraculum-php.googlecode.com/
PHP | 552 lines | 527 code | 20 blank | 5 comment | 53 complexity | 819dbc4463af011c079e99651c456517 MD5 | raw file
  1<?php
  2class Oraculum_Models
  3{
  4    private $_dsn=NULL;
  5    private $_dsntype=2;
  6    private $_user=NULL;
  7    private $_pass=NULL;
  8    private $_host=NULL;
  9    private $_driver=NULL;
 10    private $_database=NULL;
 11    private $_driveroptions=array();
 12    private $_model=NULL;
 13    public static $connection=NULL;
 14
 15    public function __construct($model=NULL) {
 16        if(!defined('MODEL_DIR')):
 17            define('MODEL_DIR', 'models');
 18        endif;
 19        Oraculum::Load('DBO');
 20        Oraculum::Load('ActiveRecord');
 21        return (!is_null($model))?$this->LoadModel($model):$this;
 22    }
 23
 24    public function LoadModel($model=NULL) {
 25        if(!is_null($model)):
 26			$model=strtolower($model);
 27            $modelfile=MODEL_DIR.'/'.$model.'.php';
 28            if(file_exists($modelfile)):
 29                include($modelfile);
 30            else:
 31                throw new Exception('[Erro CGM17] Modelo nao encontrado ('.$modelfile.') ');
 32            endif;
 33            if($this->_dsntype==2):
 34                $dsn=preg_split('[://|:|@|/]', $this->_dsn);
 35                $this->_driver=strtolower($dsn[0]);
 36                $this->_user=$dsn[1];
 37                $this->_pass=$dsn[2];
 38                $this->_host=$dsn[3];
 39                $this->_database=$dsn[4];
 40                $this->_driveroptions=isset($dsn[5])?$dsn[5]:NULL;
 41                $this->_dsn=$this->_driver.':host='.$this->_host.';dbname='.$this->_database;
 42            endif;
 43            $this->_model=$model;
 44        endif;
 45        if((!isset(self::$connection))||(!is_null(self::$connection))):
 46            $this->PDO();
 47        endif;
 48        return $this;
 49    }
 50
 51    public static function CloseModel() {
 52       self::$connection = NULL;
 53    }
 54    public function SaveModel($table='all', $debug=TRUE) {
 55        $table=strtolower($table);
 56        if($table=='all'):
 57            $tables=self::$connection->query('SHOW TABLES')->fetchAll();
 58            foreach($tables as $table):
 59                $dtodir=MODEL_DIR.'/dto/';
 60                $daodir=MODEL_DIR.'/dao/';
 61                if(!file_exists($dtodir)):
 62                    if(is_writable(MODEL_DIR)):
 63                        mkdir($dtodir);
 64                    else:
 65                        throw new Exception('[Erro CGM53] Sem permissao para criar diretorio DTO');
 66                    endif;
 67                endif;
 68                if(!file_exists($daodir)):
 69                    if(is_writable(MODEL_DIR)):
 70                        mkdir($daodir);
 71                    else:
 72                        throw new Exception('[Erro CGM61] Sem permissao para criar diretorio DAO');
 73                    endif;
 74                endif;
 75
 76                $modelfile=$dtodir.$table[0].'.php';
 77                if(is_writable($dtodir)):
 78                    $model=$this->GenerateDTO($table[0], FALSE);
 79                    $mf=fopen($modelfile, 'w');
 80                    fwrite($mf, $model);
 81                    fclose($mf);
 82                else:
 83                    throw new Exception('[Erro CGM71] O arquivo nao pode ser gravado ('.$modelfile.')');
 84                endif;
 85
 86                $modelfile=$daodir.$table[0].'.php';
 87                if(is_writable($daodir)):
 88                    $model=$this->GenerateDAO($table[0], FALSE);
 89                    $mf=fopen($modelfile, 'w');
 90                    fwrite($mf, $model);
 91                    fclose($mf);
 92                else:
 93                    throw new Exception('[Erro CGM81] O arquivo nao pode ser gravado ('.$modelfile.')');
 94                endif;
 95            endforeach;
 96        endif;
 97        if($debug):
 98            echo 'Classes geradas com sucesso!<br />';
 99            echo 'Para carregar as classes geradas em alguma &aacute;rea do site utilize o seguinte c&oacute;digo:<br />';
100            echo '<pre>';
101            highlight_string("<?php\n\tOraculum::Load('Models');\n\t\$db=new Oraculum_Models('".$this->_model."');\n\t\$db->LoadModelClass();");
102            echo '</pre>';
103        endif;
104    }
105
106    public function LoadModelClass($model='all', $type='AR', $key='id') {
107        if(!is_null($model)):
108            if($model=='all'):
109                if($type=='DO'):
110                    foreach(glob(MODEL_DIR.'/dto/*.php') as $filename):
111                        include_once($filename);
112                    endforeach;
113                    foreach(glob(MODEL_DIR.'/dao/*.php') as $filename):
114                        include_once($filename);
115                    endforeach;
116                else:
117                    foreach(glob(MODEL_DIR.'/ar/*.php') as $filename):
118                        include_once($filename);
119                    endforeach;
120                endif;
121            else:
122                $model=strtolower($model);
123                if($type=='DO'):
124                    $modelfile=MODEL_DIR.'/dto/'.$model.'.php';
125                    if(file_exists($modelfile)):
126                        include($modelfile);
127                    else:
128                        throw new Exception('[Erro CGM93] Modelo nao encontrado ('.$modelfile.') ');
129                    endif;
130                    $modelfile=MODEL_DIR.'/dao/'.$model.'.php';
131                    if(file_exists($modelfile)):
132                        include($modelfile);
133                    else:
134                        throw new Exception('[Erro CGM93] Modelo nao encontrado ('.$modelfile.') ');
135                    endif;
136                else:
137                    $modelfile=MODEL_DIR.'/ar/'.$model.'.php';
138                    if(file_exists($modelfile)):
139                        include_once($modelfile);
140                    else:
141                        if(!$this->LoadDynamicModelClass($model, $key)):
142                            throw new Exception('[Erro CGM93] Modelo nao encontrado ('.$modelfile.') ');
143                        endif;
144                    endif;
145                endif;
146            endif;
147        endif;
148        return $this;
149    }
150    public function LoadDynamicModelClass($model=NULL, $key='id') {
151        if(!is_null($model)):
152            $class=ucwords($model);
153            if (!class_exists($class)):
154                $eval='class '.$class.' extends ActiveRecord{';
155                $eval.=' public function __construct(){';
156                $eval.='     parent::__construct(get_class($this))';
157                $eval.='     ->setKey(array(\''.$key.'\'));';
158                $eval.=' }';
159                $eval.='}';
160                eval($eval);
161            endif;
162            return true;
163        else:
164            throw new Exception('[Erro CGM160] Modelo nao informado ('.$model.') ');
165        endif;
166        return $this;
167    }
168
169    public function PDO()
170    {
171        if(extension_loaded('pdo')):
172            if(in_array($this->_driver, PDO::getAvailableDrivers())):
173                try {
174                    self::$connection=new PDO($this->_dsn, $this->_user, (!$this->_pass?'':$this->_pass), $this->_driveroptions);
175                    self::$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
176                } catch (PDOException $e) {
177                    throw new Exception('PDO Connection Error: '.$e->getMessage());
178                }
179                return self::$connection;
180            else:
181                throw new Exception('[Error CGM54] Nao ha driver disponivel para \''.$this->_driver.'\'');
182            endif;
183        else:
184            throw new Exception('[Error CGM57] Extensao PDO nao carregada');
185        endif;
186    }
187
188    public function GenerateClass($table='all', $create=TRUE) {
189        $table=strtolower($table);
190        if($table=='all'):
191            $tables=self::$connection->query('SHOW TABLES')->fetchAll();
192            foreach ($tables as $table):
193                $this->GenerateDTO($table[0], $create);
194                $this->GenerateDAO($table[0], $create);
195            endforeach;
196        else:
197            try {
198                $desc=self::$connection->query('DESC '.$table)->fetchAll();
199                $classedto=ucwords($table).'DTO';
200                $class='  class '.$classedto.' extends DBO'."\n";
201                $class.="  {\n";
202                $contador=0;
203                foreach($desc as $d):
204                    $campo[$contador]=$d['Field'];
205                    $tipo[$contador]=$d['Type'];
206                    $null[$contador]=$d['Null'];
207                    $key[$contador]=$d['Key'];
208                    $default[$contador]=$d['Default'];
209                    $extra[$contador]=$d['Extra'];
210                    if(is_null($default[$contador])):
211                        $default[$contador]='NULL';
212                    else:
213                        $default[$contador]="'".$default[$contador]."'";
214                    endif;
215                    if (strpos($tipo[$contador], 'int')===false):
216                        $tiposql[$contador]="%s";
217                    else:
218                        $tiposql[$contador]="%u";
219                    endif;
220					$contador++;
221				endforeach;
222				for($c=0; $c<$contador; $c++):
223					$class.="    public \$".$campo[$c]."=".$default[$c].";\n";
224				endfor;
225				$class.="\n    public function ".$classedto."(){}\n";
226
227				for ($c=0; $c<$contador; $c++):
228					$name=ucwords($campo[$c]);
229					if($key[$c]!=''):
230						$class.="\n    // ".$name." (".$key[$c]." ".$tipo[$c].")\n";
231					else:
232						$class.="\n    // ".$name." (".$tipo[$c].")\n";
233					endif;
234					$class.="    public function get".$name."()\n";
235					$class.="    {\n";
236					$class.="      return \$this->".$campo[$c].";\n";
237					$class.="    }\n";
238					$class.="    public function set".$name."($".$campo[$c].")\n";
239					$class.="    {\n";
240					$class.="      \$this->".$campo[$c]."=\$".$campo[$c].";\n";
241					$class.="    }\n";
242				endfor;
243				$class.="  }\n";
244				if($create):
245					eval($class);
246				else:
247					return "<?php \n".$class;
248				endif;
249            } catch (PDOException $e) {
250                throw new Exception('PDO Connection Error: '.$e->getMessage());
251            }
252        endif;
253	}
254
255    public function GenerateDTO ($table='all', $create=TRUE) {
256        $table=strtolower($table);
257        if($table=='all'):
258            $tables=self::$connection->query('SHOW TABLES')->fetchAll();
259            foreach($tables as $table):
260                $this->GenerateDTO($table[0], $create);
261            endforeach;
262        else:
263            try {
264                $desc=self::$connection->query('DESC '.$table)->fetchAll();
265                $classedto=ucwords($table).'DTO';
266                $class="  class ".$classedto."\n";
267                $class.="  {\n";
268                $contador=0;
269                foreach($desc as $d):
270                    $campo[$contador]=$d['Field'];
271                    $tipo[$contador]=$d['Type'];
272                    $null[$contador]=$d['Null'];
273                    $key[$contador]=$d['Key'];
274                    $default[$contador]=$d['Default'];
275                    $extra[$contador]=$d['Extra'];
276                    if(is_null($default[$contador])):
277                        $default[$contador]='NULL';
278                    else:
279                        $default[$contador]="'".$default[$contador]."'";
280                    endif;
281                    if(strpos($tipo[$contador], 'int')===false):
282                        $tiposql[$contador]="%s";
283                    else:
284                        $tiposql[$contador]="%u";
285                    endif;
286                    $contador++;
287				endforeach;
288                    for($c=0; $c<$contador; $c++):
289                        $class.="    private \$".$campo[$c]."=".$default[$c].";\n";
290                    endfor;
291                    $class.="\n    public function ".$classedto."(){}\n";
292
293                    for($c=0; $c<$contador; $c++):
294                        $name=ucwords($campo[$c]);
295                        if($key[$c]!=''):
296                            $class.="\n    // ".$name." (".$key[$c]." ".$tipo[$c].")\n";
297                        else:
298                            $class.="\n    // ".$name." (".$tipo[$c].")\n";
299                        endif;
300                        $class.="    public function get".$name."()\n";
301                        $class.="    {\n";
302                        $class.="      return \$this->".$campo[$c].";\n";
303                        $class.="    }\n";
304                        $class.="    public function set".$name."($".$campo[$c].")\n";
305                        $class.="    {\n";
306                        $class.="      \$this->".$campo[$c]."=\$".$campo[$c].";\n";
307                        $class.="    }\n";
308                    endfor;
309                    $class.="  }\n";
310                    if($create):
311                        eval($class);
312                    else:
313                        return "<?php \n".$class;
314                    endif;
315            } catch (PDOException $e) {
316                throw new Exception('PDO Connection Error: '.$e->getMessage());
317            }
318        endif;
319    }
320
321    public function GenerateDAO($table='all', $create=TRUE) {
322        $table=strtolower($table);
323        if($table=='all'):
324            $tables=self::$connection->query('SHOW TABLES')->fetchAll();
325            foreach($tables as $table):
326                $this->GenerateDAO($table[0], $create);
327            endforeach;
328        else:
329            try {
330                $desc=self::$connection->query('DESC '.$table)->fetchAll();
331                $classedao=ucwords($table).'DAO';
332                $classedto=ucwords($table).'DTO';
333                $classdao="  class ".$classedao." extends DBO\n";
334                $classdao.="  {\n\n";
335                //foreach ($desc as $d) {
336
337                $contador=sizeof($desc);
338                if($contador>0):
339                    $classdao.="    // Select All\n";
340                    $classdao.="    public function getAll(\$limit=10)\n";
341                    $classdao.="    {\n";
342                    $classdao.="      \$objDto=new ".$classedto."();\n";
343                    $classdao.="      \$return=array();\n";
344                    $classdao.="      if(floor(\$limit)!=0)\n";
345                    $classdao.="      {\n";
346                    $classdao.="      	\$sqllimit=\"LIMIT \".floor(\$limit);\n";
347                    $classdao.="      }\n";
348                    $classdao.="      else\n";
349                    $classdao.="      {\n";
350                    $classdao.="      	\$sqllimit=\"\";\n";
351                    $classdao.="      }\n";
352                    $classdao.="      \$sql=\"SELECT * FROM ".$table." \".\$sqllimit;\n";
353                    $classdao.="      \$resultado=\$this->execSQL(\$sql);\n";
354                    $classdao.="      \$dados=\$this->dados(\$resultado);\n";
355                    $classdao.="      foreach(\$dados as \$d) {\n";
356                    //$classdao.="      while(\$dados=\$this->dados(\$resultado))\n";
357                    //$classdao.="      {\n";
358                    foreach ($desc as $d):
359                        $name=ucwords($d[0]);
360                        //$classdao.="var_dump(\$dados);";
361                        $classdao.="        \$objDto->set".$name."(stripslashes(\$d['".$d[0]."']));\n";
362                        //$classdao.="        \$objDto->set".$name."(stripslashes(\$dados['".$d[0]."']));\n";
363                    endforeach;
364                    $classdao.="        \$return[]=clone \$objDto;\n";
365                    $classdao.="      }\n";
366                    $classdao.="      return \$return;\n";
367                    $classdao.="    }\n\n";
368
369                    $classdao.="    // Select by Id\n";
370                    $classdao.="    public function getById(\$id)\n";
371                    $classdao.="    {\n";
372                    $classdao.="      \$objDto=new ".$classedto."();\n";
373                    $classdao.="      \$sql=sprintf('SELECT * FROM ".$table." WHERE codigo=\"%u\"',\$this->secsql(\$id));\n";
374                    $classdao.="      \$resultado=\$this->execSQL(\$sql);\n";
375                    $classdao.="      if(\$this->linhas(\$resultado)==1)\n";
376                    $classdao.="      {\n";
377                    $classdao.="      \$dados=\$this->dados(\$resultado);\n";
378                    $classdao.="      foreach(\$dados as \$d) {\n";
379                    foreach($desc as $d):
380                        $name=ucwords($d[0]);
381                        $classdao.="        \$objDto->set".$name."(stripslashes(\$d['".$d[0]."']));\n";
382                    endforeach;
383                    $classdao.="        \$return=clone \$objDto;\n";
384                    $classdao.="      }\n";
385                    $classdao.="      }\n";
386                    $classdao.="      else\n";
387                    $classdao.="      {\n";
388                    $classdao.="        \$return=NULL;\n";
389                    $classdao.="      }\n";
390                    $classdao.="      return \$return;\n";
391                    $classdao.="    }\n\n";
392
393                    $classdao.="    // Insert\n";
394                    $classdao.="    public function insert(".$classedto." \$objDto)\n";
395                    $classdao.="    {\n";
396                    $classdao.="      \$sql=sprintf('INSERT INTO ".$table." (";
397                    $c=0;
398                    foreach($desc as $d):
399                        $classdao.=$d[0];
400                        if ($c<$contador-1):
401                            $classdao.=",";
402                        endif;
403                        $c++;
404                    endforeach;
405                    $classdao.=") VALUES (";
406                    $c=0;
407                    foreach($desc as $d):
408                        if(strpos($d[1], 'int')===false):
409                            $classdao.="\"%s\"";
410                        else:
411                            $classdao.="\"%u\"";
412                        endif;
413                        if($c<$contador-1):
414                            $classdao.=",";
415                        endif;
416                        $c++;
417                    endforeach;
418                    $classdao.=")',\n";
419                    $c=0;
420                    foreach($desc as $d):
421                        $name=ucwords($d[0]);
422                        $classdao.="               \$this->secsql(\$objDto->get".$name."())";
423                        if($c<$contador-1):
424                            $classdao.=",\n";
425                        endif;
426                        $c++;
427                    endforeach;
428                    $classdao.="              );\n";
429                    $classdao.="      \$this->execSQL(\$sql);\n";
430                    $classdao.="      \$objDto->setCodigo(mysql_insert_id());\n";
431                    $classdao.="      return \$objDto;\n";
432                    $classdao.="    }\n\n";
433                    $classdao.="    // Update\n";
434                    $classdao.="    public function update(".$classedto." \$objDto)\n";
435                    $classdao.="    {\n";
436                    $classdao.="      if(!\$objDto->getCodigo())\n";
437                    $classdao.="        throw new Exception('Valor da chave primaria invalido');\n";
438                    $classdao.="      \$sql=sprintf('UPDATE ".$table." SET ";
439                    $c=0;
440                    foreach($desc as $d):
441                        if(strpos($d[1], 'int')===false):
442                            $classdao.=$d[0]."=\"%s\"";
443                        else:
444                            $classdao.=$d[0]."=\"%u\"";
445                        endif;
446                        if($c<$contador-1):
447                            $classdao.=", ";
448                        endif;
449                        $c++;
450                    endforeach;
451                    $classdao.=" WHERE codigo=\"%u\"',\n";
452                    $c=0;
453                    foreach($desc as $d):
454                        $name=ucwords($d[0]);
455                        $classdao.="               \$this->secsql(\$objDto->get".$name."())";
456                        if($c<$contador-1):
457                            $classdao.=",\n";
458                        endif;
459                        $c++;
460                    endforeach;
461                    $classdao.="              );\n";
462                    $classdao.="      \$this->execSQL(\$sql);\n";
463                    $classdao.="    }\n\n";
464                    $classdao.="    // Delete\n";
465                    $classdao.="    public function delete(".$classedto." \$objDto)\n";
466                    $classdao.="    {\n";
467                    $classdao.="      if(\$objDto->getCodigo()==NULL)\n";
468                    $classdao.="          throw new Exception('Valor da chave primaria invalido.');\n";
469                    $classdao.="      \$sql=sprintf('DELETE FROM ".$table." WHERE codigo=\"%u\"',\$this->secsql(\$objDto->getCodigo()));\n";
470                    $classdao.="      \$this->execSQL(\$sql);\n";
471                    $classdao.="    }\n\n";
472                    $classdao.="    // Save\n";
473                    $classdao.="    public function save(".$classedto." &\$objDto)\n";
474                    $classdao.="    {\n";
475                    $classdao.="      if(\$objDto->getCodigo()!== null)\n";
476                    $classdao.="      {\n";
477                    $classdao.="        \$this->update(\$objDto);\n";
478                    $classdao.="      }\n";
479                    $classdao.="      else\n";
480                    $classdao.="      {\n";
481                    $classdao.="        \$this->insert(\$objDto);\n";
482                    $classdao.="      }\n";
483                    $classdao.="    }\n\n";
484
485                    $classdao.="    // SecSQL\n";
486                    $classdao.="    public function secsql(\$string)\n";
487                    $classdao.="    {\n";
488                    $classdao.="      \$string=mysql_real_escape_string(\$string);\n";
489                    $classdao.="      return \$string;\n";
490                    $classdao.="    }\n";
491                    $classdao.="  }\n";
492                    if($create):
493                        eval($classdao);
494                    else:
495                        return "<?php \n".$classdao;
496                    endif;
497                endif;
498            } catch (PDOException $e) {
499                throw new Exception('PDO Connection Error: '.$e->getMessage());
500            }
501        endif;
502    }
503
504    public function GenerateAR($table='all', $create=TRUE) {
505        if($table=='all'):
506            $tables=self::$connection->query('SHOW TABLES')->fetchAll();
507            foreach($tables as $table):
508                $this->GenerateAR($table[0], $create);
509            endforeach;
510        else:
511            $table=strtolower($table);
512            $classear=ucwords($table);
513            $class="class ".$classear." extends ActiveRecord{\n";
514            $class.="\tpublic function __construct(){\n";
515            $class.="\t\tparent::__construct(get_class(\$this));\n";
516            $class.="\t}\n";
517            $class.="}\n";
518            if($create):
519                eval($class);
520            else:
521                return "<?php \n".$class;
522            endif;
523        endif;
524    }
525	
526	public function LoadTable($table=NULL) {
527		if(is_null($table)):
528			throw new Exception ('[Erro CGM66] Tabela nao informada');
529		else:
530			return $this->LoadDynamicModelClass($table);
531		endif;
532	}
533
534    public function setDsn($dsn=NULL) {
535		if(is_null($dsn)):
536			throw new Exception ('[Erro CGM414] DSN nao informado');
537		else:
538            $this->_dsn=$dsn;
539			$dsn=preg_split('[://|:|@|/]', $this->_dsn);
540			$this->_driver=strtolower($dsn[0]);
541			$this->_user=$dsn[1];
542			$this->_pass=$dsn[2];
543			$this->_host=$dsn[3];
544			$this->_database=$dsn[4];
545			$this->_driveroptions=isset($dsn[5])?$dsn[5]:NULL;
546		endif;
547    }
548	
549    public function getModelName() {
550        return $this->_model;
551    }
552}