Parser.php 16.5 KB
Newer Older
zYne's avatar
zYne committed
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 40
<?php
/*
 *  $Id: Table.php 1397 2007-05-19 19:54:15Z zYne $
 *
 * 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_Relation_Parser
 *
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @package     Doctrine
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @version     $Revision: 1397 $
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 */
class Doctrine_Relation_Parser 
{
    /**
     * @var Doctrine_Table $_table          the table object this parser belongs to
     */
    protected $_table;
    /**
     * @var array $_relations               an array containing all the Doctrine_Relation objects for this table
     */
zYne's avatar
zYne committed
41
    protected $_relations = array();
zYne's avatar
zYne committed
42
    /**
zYne's avatar
zYne committed
43
     * @var array $_pending                 relations waiting for parsing
zYne's avatar
zYne committed
44
     */
zYne's avatar
zYne committed
45
    protected $_pending   = array();
zYne's avatar
zYne committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    /**
     * constructor
     *
     * @param Doctrine_Table $table         the table object this parser belongs to
     */
    public function __construct(Doctrine_Table $table) 
    {
        $this->_table = $table;
    }
    /**
     * getTable
     *
     * @return Doctrine_Table   the table object this parser belongs to
     */
    public function getTable()
    {
zYne's avatar
zYne committed
62 63 64 65 66 67 68 69 70
        return $this->_table;
    }
    /**
     * getPendingRelation
     *
     * @return array            an array defining a pending relation
     */
    public function getPendingRelation($name) 
    {
71
        if ( ! isset($this->_pending[$name])) {
zYne's avatar
zYne committed
72
            throw new Doctrine_Relation_Exception('Unknown pending relation ' . $name);
73 74 75
        }
        
        return $this->_pending[$name];
zYne's avatar
zYne committed
76
    }
zYne's avatar
zYne committed
77 78 79 80 81 82 83 84 85
    
    public function hasRelation($name)
    {
        if ( ! isset($this->_pending[$name]) && ! isset($this->_relations[$name])) {
            return false;
        }
        
        return true;
    }
zYne's avatar
zYne committed
86 87 88 89 90 91 92
    /**
     * binds a relation
     *
     * @param string $name
     * @param string $field
     * @return void
     */
zYne's avatar
zYne committed
93
    public function bind($name, $options = array())
zYne's avatar
zYne committed
94 95 96 97 98 99 100
    {
        if (isset($this->relations[$name])) {
            unset($this->relations[$name]);
        }

        $lower = strtolower($name);

zYne's avatar
zYne committed
101 102
        if ($this->_table->hasColumn($lower)) {
            throw new Doctrine_Relation_Exception("Couldn't bind relation. Column with name " . $lower . ' already exists!');
zYne's avatar
zYne committed
103 104 105 106
        }

        $e    = explode(' as ', $name);
        $name = $e[0];
zYne's avatar
zYne committed
107
        $alias = isset($e[1]) ? $e[1] : $name;
zYne's avatar
zYne committed
108

zYne's avatar
zYne committed
109 110 111 112
        if ( ! isset($options['type'])) {
            throw new Doctrine_Relation_Exception('Relation type not set.');
        }

zYne's avatar
zYne committed
113
        $this->_pending[$alias] = array_merge($options, array('class' => $name, 'alias' => $alias));
114 115

        $m = Doctrine_Manager::getInstance();
zYne's avatar
zYne committed
116
        
117 118 119 120 121 122 123
        if (isset($options['onDelete'])) {
            $m->addDeleteAction($name, $this->_table->getComponentName(), $options['onDelete']);
        }
        if (isset($options['onUpdate'])) {
            $m->addUpdateAction($name, $this->_table->getComponentName(), $options['onUpdate']);
        }

zYne's avatar
zYne committed
124
        return $this->_pending[$alias];
zYne's avatar
zYne committed
125
    }
zYne's avatar
zYne committed
126 127 128 129 130 131
    /**
     * getRelation
     *
     * @param string $alias      relation alias
     */
    public function getRelation($alias, $recursive = true)
zYne's avatar
zYne committed
132
    {
zYne's avatar
zYne committed
133 134
        if (isset($this->_relations[$alias])) {
            return $this->_relations[$alias];
zYne's avatar
zYne committed
135 136
        }

zYne's avatar
zYne committed
137 138
        if (isset($this->_pending[$alias])) {
            $def = $this->_pending[$alias];
zYne's avatar
zYne committed
139
        
140 141
            // check if reference class name exists
            // if it does we are dealing with association relation
zYne's avatar
zYne committed
142 143
            if (isset($def['refClass'])) {
                $def = $this->completeAssocDefinition($def);
zYne's avatar
zYne committed
144 145 146
                $localClasses = array_merge($this->_table->getOption('parents'), array($this->_table->getComponentName()));

                if ( ! isset($this->_pending[$def['refClass']]) && 
147
                     ! isset($this->_relations[$def['refClass']])) {
zYne's avatar
zYne committed
148

zYne's avatar
zYne committed
149 150 151 152 153 154 155 156 157
                    $parser = $def['refTable']->getRelationParser();
                    if ( ! $parser->hasRelation($this->_table->getComponentName())) {
                        $parser->bind($this->_table->getComponentName(),
                                      array('type'    => Doctrine_Relation::ONE,
                                            'local'   => $def['local'],
                                            'foreign' => $this->_table->getIdentifier(),
                                            'localKey' => true,
                                            ));
                    }
zYne's avatar
zYne committed
158

zYne's avatar
zYne committed
159 160 161 162 163
                    if ( ! $this->hasRelation($def['refClass'])) {
                        $this->bind($def['refClass'], array('type' => Doctrine_Relation::MANY,
                                                            'foreign' => $def['local'],
                                                            'local'   => $this->_table->getIdentifier()));
                    }
zYne's avatar
zYne committed
164 165
                }
                if (in_array($def['class'], $localClasses)) {
166
                    $rel = new Doctrine_Relation_Nest($def);
zYne's avatar
zYne committed
167
                } else {
zYne's avatar
zYne committed
168
                    $rel = new Doctrine_Relation_Association($def);
zYne's avatar
zYne committed
169
                }
zYne's avatar
zYne committed
170
            } else {
171
                // simple foreign key relation
zYne's avatar
zYne committed
172
                $def = $this->completeDefinition($def);
173 174

                if (isset($def['localKey'])) {
zYne's avatar
zYne committed
175

176 177 178 179
                    $rel = new Doctrine_Relation_LocalKey($def);
                } else {
                    $rel = new Doctrine_Relation_ForeignKey($def);
                }
zYne's avatar
zYne committed
180
            }
zYne's avatar
zYne committed
181
            if (isset($rel)) {
182 183 184 185
                // unset pending relation
                unset($this->_pending[$alias]);

                $this->_relations[$alias] = $rel;
zYne's avatar
zYne committed
186 187 188 189
                return $rel;
            }
        }
        if ($recursive) {
zYne's avatar
zYne committed
190
            $this->getRelations();
zYne's avatar
zYne committed
191

zYne's avatar
zYne committed
192
            return $this->getRelation($alias, false);
zYne's avatar
zYne committed
193
        } else {
zYne's avatar
zYne committed
194
            throw new Doctrine_Table_Exception('Unknown relation alias ' . $alias);
zYne's avatar
zYne committed
195 196
        }
    }
zYne's avatar
zYne committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210
    /**
     * getRelations
     * returns an array containing all relation objects
     *
     * @return array        an array of Doctrine_Relation objects
     */
    public function getRelations()
    {
        foreach ($this->_pending as $k => $v) {
            $this->getRelation($k);
        }

        return $this->_relations;
    }
zYne's avatar
zYne committed
211 212 213 214 215 216 217 218 219 220
    /**
     * getImpl
     * returns the table class of the concrete implementation for given template
     * if the given template is not a template then this method just returns the
     * table class for the given record
     *
     * @param string $template
     */
    public function getImpl($template)
    {
221
        $conn = $this->_table->getConnection();
zYne's avatar
zYne committed
222 223 224 225 226 227 228 229 230 231 232 233 234

        if (in_array('Doctrine_Template', class_parents($template))) {
            $impl = $this->_table->getImpl($template);
            
            if ($impl === null) {
                throw new Doctrine_Relation_Parser_Exception("Couldn't find concrete implementation for template " . $template);
            }
        } else {
            $impl = $template;
        }

        return $conn->getTable($impl);
    }
zYne's avatar
zYne committed
235 236 237 238 239 240
    /**
     * Completes the given association definition
     *
     * @param array $def    definition array to be completed
     * @return array        completed definition array
     */
zYne's avatar
zYne committed
241 242
    public function completeAssocDefinition($def) 
    {
243
        $conn = $this->_table->getConnection();
zYne's avatar
zYne committed
244 245 246
        $def['table'] = $this->getImpl($def['class']);
        $def['class'] = $def['table']->getComponentName();
        $def['refTable'] = $this->getImpl($def['refClass']);
zYne's avatar
zYne committed
247

248 249 250 251 252 253 254 255 256 257 258 259
        $id = $def['refTable']->getIdentifier();

        if (count($id) > 1) {
            if ( ! isset($def['foreign'])) {
                // foreign key not set
                // try to guess the foreign key
    
                $def['foreign'] = ($def['local'] === $id[0]) ? $id[1] : $id[0];
            }
            if ( ! isset($def['local'])) {
                // foreign key not set
                // try to guess the foreign key
zYne's avatar
zYne committed
260

261 262 263
                $def['local'] = ($def['foreign'] === $id[0]) ? $id[1] : $id[0];
            }
        } else {
zYne's avatar
zYne committed
264

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
            if ( ! isset($def['foreign'])) {
                // foreign key not set
                // try to guess the foreign key
    
                $columns = $this->getIdentifiers($def['table']);
    
                $def['foreign'] = $columns;
            }
            if ( ! isset($def['local'])) {
                // local key not set
                // try to guess the local key
                $columns = $this->getIdentifiers($this->_table);
    
                $def['local'] = $columns;
            }
zYne's avatar
zYne committed
280
        }
zYne's avatar
zYne committed
281 282
        return $def;
    }
zYne's avatar
zYne committed
283 284 285 286 287 288 289 290 291
    /** 
     * getIdentifiers
     * gives a list of identifiers from given table
     *
     * the identifiers are in format:
     * [componentName].[identifier]
     *
     * @param Doctrine_Table $table     table object to retrieve identifiers from
     */
zYne's avatar
zYne committed
292 293
    public function getIdentifiers(Doctrine_Table $table)
    {
294
        if (is_array($table->getIdentifier())) {
zYne's avatar
zYne committed
295 296 297 298 299
            $columns = array();
            foreach((array) $table->getIdentifier() as $identifier) {
                $columns[] = strtolower($table->getComponentName())
                           . '_' . $table->getIdentifier();
            }
300
        } else {
zYne's avatar
zYne committed
301 302
            $columns = strtolower($table->getComponentName())
                           . '_' . $table->getIdentifier();
303
        }
zYne's avatar
zYne committed
304 305

        return $columns;
zYne's avatar
zYne committed
306
    }
307 308 309 310 311 312 313 314
    /**
     * guessColumns
     *
     * @param array $classes                    an array of class names
     * @param Doctrine_Table $foreignTable      foreign table object
     * @return array                            an array of column names
     */
    public function guessColumns(array $classes, Doctrine_Table $foreignTable)
zYne's avatar
zYne committed
315 316 317 318
    {
        $conn = $this->_table->getConnection();

        foreach ($classes as $class) {
319 320 321 322 323
            try {
                $table   = $conn->getTable($class);
            } catch (Doctrine_Table_Exception $e) {
                continue;
            }
zYne's avatar
zYne committed
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
            $columns = $this->getIdentifiers($table);
            $found   = true;

            foreach ((array) $columns as $column) {
                if ( ! $foreignTable->hasColumn($column)) {
                    $found = false;
                    break;
                }
            }
            if ($found) {
                break;
            }
        }
        
        if ( ! $found) {
            throw new Doctrine_Relation_Exception("Couldn't find columns.");
        }

        return $columns;
    }
zYne's avatar
zYne committed
344 345 346 347 348 349
    /**
     * Completes the given definition
     *
     * @param array $def    definition array to be completed
     * @return array        completed definition array
     */
zYne's avatar
zYne committed
350 351
    public function completeDefinition($def)
    {
352
        $conn = $this->_table->getConnection();
zYne's avatar
zYne committed
353 354 355
        $def['table'] = $this->getImpl($def['class']);
        $def['class'] = $def['table']->getComponentName();

zYne's avatar
zYne committed
356 357
        $foreignClasses = array_merge($def['table']->getOption('parents'), array($def['class']));
        $localClasses   = array_merge($this->_table->getOption('parents'), array($this->_table->getComponentName()));
zYne's avatar
zYne committed
358 359 360 361 362 363

        if (isset($def['local'])) {
            if ( ! isset($def['foreign'])) {
                // local key is set, but foreign key is not
                // try to guess the foreign key

zYne's avatar
zYne committed
364 365
                if ($def['local'] === $this->_table->getIdentifier()) {
                    $def['foreign'] = $this->guessColumns($localClasses, $def['table']);
zYne's avatar
zYne committed
366 367 368 369
                } else {
                    // the foreign field is likely to be the
                    // identifier of the foreign class
                    $def['foreign'] = $def['table']->getIdentifier();
370
                    $def['localKey'] = true;
zYne's avatar
zYne committed
371
                }
zYne's avatar
zYne committed
372
            } else {
zYne's avatar
zYne committed
373 374
                if ($def['local'] !== $this->_table->getIdentifier() && 
                    $def['type'] == Doctrine_Relation::ONE) {
zYne's avatar
zYne committed
375
                    $def['localKey'] = true;
zYne's avatar
zYne committed
376
                }
zYne's avatar
zYne committed
377
            }
zYne's avatar
zYne committed
378 379 380 381
        } else {
            if (isset($def['foreign'])) {
                // local key not set, but foreign key is set
                // try to guess the local key
zYne's avatar
zYne committed
382
                if ($def['foreign'] === $def['table']->getIdentifier()) {
383
                    $def['localKey'] = true;
384 385 386 387 388
                    try {
                        $def['local'] = $this->guessColumns($foreignClasses, $this->_table);
                    } catch (Doctrine_Relation_Exception $e) {
                        $def['local'] = $this->_table->getIdentifier();
                    }
zYne's avatar
zYne committed
389
                } else {
zYne's avatar
zYne committed
390
                    $def['local'] = $this->_table->getIdentifier();
zYne's avatar
zYne committed
391 392 393 394 395
                }
            } else {
                // neither local or foreign key is being set
                // try to guess both keys

zYne's avatar
zYne committed
396
                $conn = $this->_table->getConnection();
zYne's avatar
zYne committed
397

zYne's avatar
zYne committed
398 399 400 401 402
                // the following loops are needed for covering inheritance
                foreach ($localClasses as $class) {
                    $table  = $conn->getTable($class);
                    $column = strtolower($table->getComponentName())
                            . '_' . $table->getIdentifier();
zYne's avatar
zYne committed
403

zYne's avatar
zYne committed
404 405 406 407 408
                    foreach ($foreignClasses as $class2) {
                        $table2 = $conn->getTable($class2);
                        if ($table2->hasColumn($column)) {
                            $def['foreign'] = $column;
                            $def['local']   = $table->getIdentifier();
zYne's avatar
zYne committed
409

zYne's avatar
zYne committed
410 411
                            return $def;
                        }
zYne's avatar
zYne committed
412 413
                    }
                }
zYne's avatar
zYne committed
414

zYne's avatar
zYne committed
415 416 417 418 419 420 421 422
                foreach ($foreignClasses as $class) {
                    $table  = $conn->getTable($class);
                    $column = strtolower($table->getComponentName())
                            . '_' . $table->getIdentifier();
                
                    foreach ($localClasses as $class2) {
                        $table2 = $conn->getTable($class2);
                        if ($table2->hasColumn($column)) {
zYne's avatar
zYne committed
423 424
                            $def['foreign']  = $table->getIdentifier();
                            $def['local']    = $column;
zYne's avatar
zYne committed
425
                            $def['localKey'] = true;
zYne's avatar
zYne committed
426
                            return $def;
zYne's avatar
zYne committed
427 428
                        }
                    }
429
                }
zYne's avatar
zYne committed
430 431 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

                // auto-add columns and auto-build relation
                $columns = array();
                foreach ((array) $this->_table->getIdentifier() as $id) {
                    $column = strtolower($table->getComponentName())
                            . '_' . $id;

                    $col = $this->_table->getDefinitionOf($id);
                    $type = $col['type'];
                    $length = $col['length'];

                    unset($col['type']);
                    unset($col['length']);
                    unset($col['autoincrement']);
                    unset($col['sequence']);
                    unset($col['primary']);

                    $def['table']->setColumn($column, $type, $length, $col);
                    
                    $columns[] = $column;
                }
                if (count($columns) > 1) {
                    $def['foreign'] = $columns;
                } else {
                    $def['foreign'] = $columns[0];
                }
                $def['local'] = $this->_table->getIdentifier();
zYne's avatar
zYne committed
457
            }
zYne's avatar
zYne committed
458
        }
zYne's avatar
zYne committed
459
        return $def;
zYne's avatar
zYne committed
460 461
    }
}