Builder.php 19.5 KB
Newer Older
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
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */

/**
 * Doctrine_Import_Builder
 * Import builder is responsible of building Doctrine ActiveRecord classes
 * based on a database schema.
 *
 * @package     Doctrine
 * @subpackage  Import
 * @link        www.phpdoctrine.com
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @since       1.0
 * @version     $Revision$
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author      Jukka Hassinen <Jukka.Hassinen@BrainAlliance.com>
 * @author      Nicolas Bérard-Nault <nicobn@php.net>
 */
class Doctrine_Import_Builder
{
    /**
40 41 42 43 44
     * Path
     * 
     * the path where imported files are being generated
     *
     * @var string $path
45 46 47
     */
    private $path = '';

48 49 50 51 52 53 54
    /**
     * suffix
     * 
     * File suffix to use when writing class definitions
     *
     * @var string $suffix
     */
55 56
    private $suffix = '.class.php';
    
57 58 59 60 61 62 63
    /**
     * generateBaseClasses
     * 
     * Bool true/false for whether or not to generate base classes
     *
     * @var string $suffix
     */
64 65
    private $generateBaseClasses = false;
    
66 67 68 69 70 71 72
    /**
     * baseClassesDirectory
     * 
     * Directory to put the generate base classes in
     *
     * @var string $suffix
     */
73 74
    private $baseClassesDirectory = 'generated';
    
75 76 77 78 79 80 81
    /**
     * tpl
     *
     * Class template used for writing classes
     *
     * @var $tpl
     */
82 83
    private static $tpl;
    
84 85 86 87 88
    /**
     * __construct
     *
     * @return void
     */
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
    public function __construct()
    {
        $this->loadTemplate();
    }

    /**
     * setTargetPath
     *
     * @param string path   the path where imported files are being generated
     * @return
     */
    public function setTargetPath($path)
    {
        if ( ! file_exists($path)) {
            mkdir($path, 0777);
        }

        $this->path = $path;
    }
    
    /**
     * generateBaseClasses
     *
     * Specify whether or not to generate classes which extend from generated base classes
     *
     * @param string $bool
     * @return void
     * @author Jonathan H. Wage
     */
    public function generateBaseClasses($bool = null)
    {
      if ($bool !== null) {
        $this->generateBaseClasses = $bool;
      }
      
      return $this->generateBaseClasses;
    }
    
    /**
     * getTargetPath
     *
     * @return string       the path where imported files are being generated
     */
    public function getTargetPath()
    {
        return $this->path;
    }

    /**
138 139 140
     * loadTemplate
     * 
     * Loads the class template used for generating classes
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
     *
     * @return void
     */
    public function loadTemplate() 
    {
        if (isset(self::$tpl)) {
            return;
        }

        self::$tpl =<<<END
/**
 * This class has been auto-generated by the Doctrine ORM Framework
 */
%sclass %s extends %s
{
%s
%s
158
%s
159 160 161 162 163
}
END;

    }

164 165 166 167
    /*
     * Build the accessors
     *
     * @param  string $table
168
     * @param  array  $columns
169 170 171
     */
    public function buildAccessors(array $options, array $columns)
    {
172 173 174
        $ret = '';
        foreach ($columns as $name => $column) {
            // getters
175
            $ret .= "\n\tpublic function get".Doctrine::classify($name)."(\$load = true)\n";
176
            $ret .= "\t{\n";
177
            $ret .= "\t\treturn \$this->get('{$name}', \$load);\n";
178 179 180
            $ret .= "\t}\n";

            // setters
181
            $ret .= "\n\tpublic function set".Doctrine::classify($name)."(\${$name}, \$load = true)\n";
182
            $ret .= "\t{\n";
183
            $ret .= "\t\treturn \$this->set('{$name}', \${$name}, \$load);\n";
184 185 186 187
            $ret .= "\t}\n";
        }

        return $ret;
188 189
    }

190 191 192 193 194 195
    /*
     * Build the table definition of a Doctrine_Record object
     *
     * @param  string $table
     * @param  array  $tableColumns
     */
196
    public function buildTableDefinition(array $options, array $columns, array $relations, array $indexes, array $attributes, array $templates, array $actAs)
197 198 199 200 201 202
    {
        $ret = array();
        
        $i = 0;
        
        if (isset($options['inheritance']['extends']) && !isset($options['override_parent'])) {
203
            $ret[$i] = "\t\tparent::setTableDefinition();";
204 205 206 207
            $i++;
        }
        
        if (isset($options['tableName']) && !empty($options['tableName'])) {
208
            $ret[$i] = "\t\t".'$this->setTableName(\''. $options['tableName'].'\');';
209 210 211
            
            $i++;
        }
212
        
213
        foreach ($columns as $name => $column) {
214
            $ret[$i] = "\t\t".'$this->hasColumn(\'' . $name . '\', \'' . $column['type'] . '\'';
215 216 217 218 219 220 221 222 223
            
            if ($column['length']) {
                $ret[$i] .= ', ' . $column['length'];
            } else {
                $ret[$i] .= ', null';
            }

            $a = array();

224
            if (isset($column['default'])) {
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
                $a[] = '\'default\' => ' . var_export($column['default'], true);
            }
            if (isset($column['notnull']) && $column['notnull']) {
                $a[] = '\'notnull\' => true';
            }
            if (isset($column['primary']) && $column['primary']) {
                $a[] = '\'primary\' => true';
            }
            if ((isset($column['autoinc']) && $column['autoinc']) || isset($column['autoincrement']) && $column['autoincrement']) {
                $a[] = '\'autoincrement\' => true';
            }
            if (isset($column['unique']) && $column['unique']) {
                $a[] = '\'unique\' => true';
            }
            if (isset($column['unsigned']) && $column['unsigned']) {
                $a[] = '\'unsigned\' => true';
            }
            if ($column['type'] == 'enum' && isset($column['values']) ) {
                $a[] = '\'values\' => array(\'' . implode('\',\'', $column['values']) . '\')';
            }

            if ( ! empty($a)) {
                $ret[$i] .= ', ' . 'array(';
                $length = strlen($ret[$i]);
                $ret[$i] .= implode(',' . PHP_EOL . str_repeat(' ', $length), $a) . ')';
            }
            
            $ret[$i] .= ');';

            if ($i < (count($columns) - 1)) {
                $ret[$i] .= PHP_EOL;
            }
            $i++;
        }
        
260 261 262 263 264 265
        $ret[$i] = $this->buildIndexes($indexes);
        $i++;
        
        $ret[$i] = $this->buildAttributes($attributes);
        $i++;
        
266 267 268 269 270
        $ret[$i] = $this->buildTemplates($templates);
        $i++;
        
        $ret[$i] = $this->buildActAs($actAs);
        
271 272 273 274 275
        if (!empty($ret)) {
          return "\n\tpublic function setTableDefinition()"."\n\t{\n".implode("\n", $ret)."\n\t}";
        }
    }
    
276 277 278 279 280
    public function buildTemplates(array $templates)
    {
        $build = '';
        foreach ($templates as $name => $options) {
            
281
            if (is_array($options) && !empty($options)) {
282 283 284 285
                $optionsPhp = $this->arrayToPhpArrayCode($options);
            
                $build .= "\t\t\$this->loadTemplate('" . $name . "', " . $optionsPhp . ");\n";
            } else {
286 287 288 289 290
                if (isset($templates[0])) {
                    $build .= "\t\t\$this->loadTemplate('" . $options . "');\n";
                } else {
                    $build .= "\t\t\$this->loadTemplate('" . $name . "');\n";
                }
291 292 293 294 295 296 297 298 299 300
            }
        }
        
        return $build;
    }
    
    public function buildActAs(array $actAs)
    {
        $build = '';
        foreach ($actAs as $name => $options) {
301 302 303 304 305 306 307 308 309 310 311
            if (is_array($options) && !empty($options)) {
                $optionsPhp = $this->arrayToPhp($options);
                
                $build .= "\t\t\$this->actAs('" . $name . "', " . $optionsPhp . ");\n";
            } else {
                if (isset($actAs[0])) {
                    $build .= "\t\t\$this->actAs('" . $options . "');\n";
                } else {
                    $build .= "\t\t\$this->actAs('" . $name . "');\n";
                }
            }
312 313 314 315 316
        }
        
        return $build;
    }
    
317
    protected function arrayToPhp(array $array)
318
    {
319 320 321 322
        ob_start();
        var_export($array);
        $php = ob_get_contents();
        ob_end_clean();
323
        
324
        return $php;
325 326
    }
    
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    public function buildAttributes(array $attributes)
    {
        $build = "\n";
        foreach ($attributes as $key => $value) {
            if (!is_array($value)) {
                $value = array($value);
            }
            
            $values = '';
            foreach ($value as $attr) {
                $values .= "Doctrine::" . strtoupper($key) . "_" . strtoupper($attr) . ' ^ ';
            }
            
            // Trim last ^
            $values = substr($values, 0, strlen($values) - 3);
342
            
343 344 345 346 347 348 349 350 351 352 353
            $build .= "\t\t\$this->setAttribute(Doctrine::ATTR_" . strtoupper($key) . ", " . $values . ");\n";
        }
        
        return $build;
    }
    
    public function buildIndexes(array $indexes)
    {
      $build = '';

      foreach ($indexes as $indexName => $definitions) {
354
          $build = "\n\t\t".'$this->index(\'' . $indexName . '\', array(';
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

          foreach ($definitions as $name => $value) {

            // parse fields
            if ($name === 'fields' || $name === 'columns') {
              $build .= '\'fields\' => array(';

              foreach ($value as $fieldName => $fieldValue) {
                $build .= '\'' . $fieldName . '\' => array( ';

                // parse options { sorting, length, primary }
                if (isset($fieldValue) && $fieldValue) {
                  foreach ($fieldValue as $optionName => $optionValue) {

                    $build .= '\'' . $optionName . '\' => ';

                    // check primary option, mark either as true or false
                    if ($optionName === 'primary') {
                    	$build .= (($optionValue == 'true') ? 'true' : 'false') . ', ';
                    	continue;
                    }

                    // convert sorting option to uppercase, for instance, asc -> ASC
                    if ($optionName === 'sorting') {
                    	$build .= '\'' . strtoupper($optionValue) . '\', ';
                    	continue;
381
                    }
382 383 384

                    // check the rest of the options
                    $build .= '\'' . $optionValue . '\', ';
385 386
                  }
                }
387 388

                $build .= '), ';
389 390
              }
            }
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406

            // parse index type option, 4 choices { unique, fulltext, gist, gin }
            if ($name === 'type') {
            	$build .= '), \'type\' => \'' . $value . '\'';
            }

            // add extra ) if type definition is not declared
            if (!isset($definitions['type'])) {
            	$build .= ')';
            }
          }

          $build .= '));';
      }

      return $build;
407
    }
408
    
409 410 411 412 413
    public function buildSetUp(array $options, array $columns, array $relations)
    {
        $ret = array();
        $i = 0;
        
414
        if (! (isset($options['override_parent']) && $options['override_parent'] === true)) {
415
            $ret[$i] = "\t\tparent::setUp();";
416 417 418 419 420 421 422 423 424 425 426 427 428
            $i++;
        }
        
        foreach ($relations as $name => $relation) {
            $class = isset($relation['class']) ? $relation['class']:$name;
            $alias = (isset($relation['alias']) && $relation['alias'] !== $relation['class']) ? ' as ' . $relation['alias'] : '';

            if ( ! isset($relation['type'])) {
                $relation['type'] = Doctrine_Relation::ONE;
            }

            if ($relation['type'] === Doctrine_Relation::ONE || 
                $relation['type'] === Doctrine_Relation::ONE_COMPOSITE) {
429
                $ret[$i] = "\t\t".'$this->hasOne(\'' . $class . $alias . '\'';
430
            } else {
431
                $ret[$i] = "\t\t".'$this->hasMany(\'' . $class . $alias . '\'';
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
            }
            
            $a = array();

            if (isset($relation['refClass'])) {
                $a[] = '\'refClass\' => ' . var_export($relation['refClass'], true);
            }
            
            if (isset($relation['deferred']) && $relation['deferred']) {
                $a[] = '\'default\' => ' . var_export($relation['deferred'], true);
            }
            
            if (isset($relation['local']) && $relation['local']) {
                $a[] = '\'local\' => ' . var_export($relation['local'], true);
            }
            
            if (isset($relation['foreign']) && $relation['foreign']) {
                $a[] = '\'foreign\' => ' . var_export($relation['foreign'], true);
            }
            
            if (isset($relation['onDelete']) && $relation['onDelete']) {
                $a[] = '\'onDelete\' => ' . var_export($relation['onDelete'], true);
            }
            
            if (isset($relation['onUpdate']) && $relation['onUpdate']) {
                $a[] = '\'onUpdate\' => ' . var_export($relation['onUpdate'], true);
            }
            
460 461 462 463
            if (isset($relation['equal']) && $relation['equal']) { 
                $a[] = '\'equal\' => ' . var_export($relation['equal'], true); 
            }
            
464 465 466 467 468 469
            if ( ! empty($a)) {
                $ret[$i] .= ', ' . 'array(';
                $length = strlen($ret[$i]);
                $ret[$i] .= implode(',' . PHP_EOL . str_repeat(' ', $length), $a) . ')';
            }
            
470
            $ret[$i] .= ');'."\n";
471 472 473 474 475 476 477 478 479 480 481 482 483
            $i++;
        }
        
        if (isset($options['inheritance']['keyField']) && isset($options['inheritance']['keyValue'])) {
            $i++;
            $ret[$i] = "\t\t".'$this->setInheritanceMap(array(\''.$options['inheritance']['keyField'].'\' => '.$options['inheritance']['keyValue'].'));';
        }
        
        if (!empty($ret)) {
          return "\n\tpublic function setUp()\n\t{\n".implode("\n", $ret)."\n\t}";
        }
    }
    
484
    public function buildDefinition(array $options, array $columns, array $relations = array(), array $indexes = array(), $attributes = array(), array $templates = array(), array $actAs = array())
485 486 487 488
    {
        if ( ! isset($options['className'])) {
            throw new Doctrine_Import_Builder_Exception('Missing class name.');
        }
489

490
        $abstract = isset($options['abstract']) && $options['abstract'] === true ? 'abstract ':null;
491 492
        $className = $options['className'];
        $extends = isset($options['inheritance']['extends']) ? $options['inheritance']['extends']:'Doctrine_Record';
493

494
        if (!(isset($options['no_definition']) && $options['no_definition'] === true)) {
495
            $definition = $this->buildTableDefinition($options, $columns, $relations, $indexes, $attributes, $templates, $actAs);
496
            $setUp = $this->buildSetUp($options, $columns, $relations);
497 498 499
        } else {
            $definition = null;
            $setUp = null;
500 501
        }
        
502
        $accessors = (isset($options['generate_accessors']) && $options['generate_accessors'] === true) ? $this->buildAccessors($options, $columns):null;
503 504 505 506 507
        
        $content = sprintf(self::$tpl, $abstract,
                                       $className,
                                       $extends,
                                       $definition,
508 509
                                       $setUp,
                                       $accessors);
510 511 512 513
        
        return $content;
    }

514
    public function buildRecord(array $options, array $columns, array $relations = array(), array $indexes = array(), array $attributes = array(), array $templates = array(), array $actAs = array())
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
    {
        if ( !isset($options['className'])) {
            throw new Doctrine_Import_Builder_Exception('Missing class name.');
        }

        if ( !isset($options['fileName'])) {
            if (empty($this->path)) {
                throw new Doctrine_Import_Builder_Exception('No build target directory set.');
            }
            

            if (is_writable($this->path) === false) {
                throw new Doctrine_Import_Builder_Exception('Build target directory ' . $this->path . ' is not writable.');
            }

            $options['fileName']  = $this->path . DIRECTORY_SEPARATOR . $options['className'] . $this->suffix;
        }
        
        if ($this->generateBaseClasses()) {
          
          // We only want to generate this one if it doesn't already exist
          if (!file_exists($options['fileName'])) {
            $optionsBak = $options;
            
            unset($options['tableName']);
            $options['inheritance']['extends'] = 'Base' . $options['className'];
            $options['requires'] = array($this->baseClassesDirectory . DIRECTORY_SEPARATOR  . $options['inheritance']['extends'] . $this->suffix);
            $options['no_definition'] = true;
            
544
            $this->writeDefinition($options);
545 546 547 548 549 550 551 552 553 554 555 556 557
            
            $options = $optionsBak;
          }
          
          $generatedPath = $this->path . DIRECTORY_SEPARATOR . $this->baseClassesDirectory;
          
          if (!file_exists($generatedPath)) {
            mkdir($generatedPath);
          }
          
          $options['className'] = 'Base' . $options['className'];
          $options['abstract'] = true;
          $options['fileName']  = $generatedPath . DIRECTORY_SEPARATOR . $options['className'] . $this->suffix;
558
          $options['override_parent'] = true;
559
          
560
          $this->writeDefinition($options, $columns, $relations, $indexes, $attributes, $templates, $actAs);
561
        } else {
562
          $this->writeDefinition($options, $columns, $relations, $indexes, $attributes, $templates, $actAs);
563 564 565
        }
    }
    
566
    public function writeDefinition(array $options, array $columns = array(), array $relations = array(), array $indexes = array(), array $attributes = array(), array $templates = array(), array $actAs = array())
567
    {
568
        $content = $this->buildDefinition($options, $columns, $relations, $indexes, $attributes, $templates, $actAs);
569
        $code = "<?php\n";
570
        
571 572 573 574 575 576
        if (isset($options['requires'])) {
            if (!is_array($options['requires'])) {
                $options['requires'] = array($options['requires']);
            }

            foreach ($options['requires'] as $require) {
577
                $code .= "require_once('".$require."');\n";
578 579 580
            }
        }
        
581 582 583 584 585
        if (isset($options['connection']) && $options['connection']) {
            $code .= "// Connection Component Binding\n";
            $code .= "Doctrine_Manager::getInstance()->bindComponent('" . $options['connectionClassName'] . "', '" . $options['connection'] . "');\n";
        }
        
586 587 588 589 590 591 592
        $code .= PHP_EOL . $content;

        $bytes = file_put_contents($options['fileName'], $code);

        if ($bytes === false) {
            throw new Doctrine_Import_Builder_Exception("Couldn't write file " . $options['fileName']);
        }
593
    }
594
}