Parser.php 12.8 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
    /**
zYne's avatar
zYne committed
47
     * @var array $_relationAliases         relation aliases
zYne's avatar
zYne committed
48
     */
zYne's avatar
zYne committed
49
    protected $_aliases   = array();
zYne's avatar
zYne committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    /**
     * 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
66 67 68 69 70 71 72 73 74 75 76 77 78 79
        return $this->_table;
    }
    /**
     * getPendingRelation
     *
     * @return array            an array defining a pending relation
     */
    public function getPendingRelation($name) 
    {
    	if ( ! isset($this->_pending[$name])) {
            throw new Doctrine_Relation_Exception('Unknown pending relation ' . $name);
    	}
    	
    	return $this->_pending[$name];
zYne's avatar
zYne committed
80 81 82 83 84 85 86 87
    }
    /**
     * binds a relation
     *
     * @param string $name
     * @param string $field
     * @return void
     */
zYne's avatar
zYne committed
88
    public function bind($name, $options = array())
zYne's avatar
zYne committed
89 90 91 92 93 94 95
    {
        if (isset($this->relations[$name])) {
            unset($this->relations[$name]);
        }

        $lower = strtolower($name);

zYne's avatar
zYne committed
96 97
        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
98 99 100 101 102 103 104
        }

        $e    = explode(' as ', $name);
        $name = $e[0];

        if (isset($e[1])) {
            $alias = $e[1];
zYne's avatar
zYne committed
105
            $this->_aliases[$name] = $alias;
zYne's avatar
zYne committed
106 107 108
        } else {
            $alias = $name;
        }
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));
zYne's avatar
zYne committed
114
    }
zYne's avatar
zYne committed
115 116 117 118 119 120
    /**
     * getRelation
     *
     * @param string $alias      relation alias
     */
    public function getRelation($alias, $recursive = true)
zYne's avatar
zYne committed
121
    {
zYne's avatar
zYne committed
122 123
        if (isset($this->_relations[$alias])) {
            return $this->_relations[$alias];
zYne's avatar
zYne committed
124 125
        }

zYne's avatar
zYne committed
126 127
        if (isset($this->_pending[$alias])) {
            $def = $this->_pending[$alias];
zYne's avatar
zYne committed
128
        
129 130
            // check if reference class name exists
            // if it does we are dealing with association relation
zYne's avatar
zYne committed
131 132
            if (isset($def['refClass'])) {
                $def = $this->completeAssocDefinition($def);
zYne's avatar
zYne committed
133 134 135 136 137 138
                $localClasses = array_merge($this->_table->getOption('parents'), array($this->_table->getComponentName()));

                if ( ! isset($this->_pending[$def['refClass']]) && 
                     ! isset($this->_relations[$def['refClass']])) {
                    
                    $def['refTable']->getRelationParser()->bind($this->_table->getComponentName(),
139 140 141 142
                                                                array('type'    => Doctrine_Relation::ONE,
                                                                      'local'   => $def['local'],
                                                                      'foreign' => $this->_table->getIdentifier(),
                                                                      ));
zYne's avatar
zYne committed
143

144 145
                    $this->bind($def['refClass'], array('type' => Doctrine_Relation::MANY, 
                                                        'foreign' => $def['local']));
zYne's avatar
zYne committed
146 147
                }
                if (in_array($def['class'], $localClasses)) {
zYne's avatar
zYne committed
148
                    $rel = new Doctrine_Relation_Association_Self($def);
zYne's avatar
zYne committed
149
                } else {
zYne's avatar
zYne committed
150
                    $rel = new Doctrine_Relation_Association($def);
zYne's avatar
zYne committed
151
                }
zYne's avatar
zYne committed
152
            } else {
153
                // simple foreign key relation
zYne's avatar
zYne committed
154
                $def = $this->completeDefinition($def);
155 156 157 158 159 160

                if (isset($def['localKey'])) {
                    $rel = new Doctrine_Relation_LocalKey($def);
                } else {
                    $rel = new Doctrine_Relation_ForeignKey($def);
                }
zYne's avatar
zYne committed
161
            }
zYne's avatar
zYne committed
162
            if (isset($rel)) {
163 164 165 166
                // unset pending relation
                unset($this->_pending[$alias]);

                $this->_relations[$alias] = $rel;
zYne's avatar
zYne committed
167 168 169 170 171 172 173
                return $rel;
            }
        }
        if ($recursive) {
            return $this->getRelation($name, false);
        } else {
            throw new Doctrine_Table_Exception($this->options['name'] . " doesn't have a relation to " . $name);
zYne's avatar
zYne committed
174 175
        }
    }
zYne's avatar
zYne committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189
    /**
     * 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
190 191 192 193 194 195
    /**
     * Completes the given association definition
     *
     * @param array $def    definition array to be completed
     * @return array        completed definition array
     */
zYne's avatar
zYne committed
196 197 198 199 200
    public function completeAssocDefinition($def) 
    {
    	$conn = $this->_table->getConnection();
        $def['table']    = $conn->getTable($def['class']);
        $def['refTable'] = $conn->getTable($def['refClass']);
zYne's avatar
zYne committed
201

zYne's avatar
zYne committed
202 203 204
        if ( ! isset($def['foreign'])) {
            // foreign key not set
            // try to guess the foreign key
zYne's avatar
zYne committed
205

zYne's avatar
zYne committed
206 207 208
            $columns = $this->getIdentifiers($def['table']);

            $def['foreign'] = $columns;
zYne's avatar
zYne committed
209
        }
zYne's avatar
zYne committed
210 211 212 213 214 215 216 217 218 219
        if ( ! isset($def['local'])) {
            // local key not set
            // try to guess the local key
            $columns = $this->getIdentifiers($this->_table);

            $def['local'] = $columns;
        } 

        return $def;
    }
zYne's avatar
zYne committed
220 221 222 223 224 225 226 227 228
    /** 
     * 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
229 230 231 232 233 234 235 236 237 238 239 240 241 242
    public function getIdentifiers(Doctrine_Table $table)
    {
    	if (is_array($table->getIdentifier())) {
            $columns = array();
            foreach((array) $table->getIdentifier() as $identifier) {
                $columns[] = strtolower($table->getComponentName())
                           . '_' . $table->getIdentifier();
            }
    	} else {
            $columns = strtolower($table->getComponentName())
                           . '_' . $table->getIdentifier();
    	}

        return $columns;
zYne's avatar
zYne committed
243
    }
244 245 246 247 248 249 250 251
    /**
     * 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
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    {
        $conn = $this->_table->getConnection();

        foreach ($classes as $class) {
            $table   = $conn->getTable($class);
            $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
277 278 279 280 281 282
    /**
     * Completes the given definition
     *
     * @param array $def    definition array to be completed
     * @return array        completed definition array
     */
zYne's avatar
zYne committed
283 284
    public function completeDefinition($def)
    {
zYne's avatar
zYne committed
285
    	$conn = $this->_table->getConnection();
zYne's avatar
zYne committed
286 287 288
        $def['table'] = $conn->getTable($def['class']);
        $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
289 290 291 292 293 294

        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
295 296
                if ($def['local'] === $this->_table->getIdentifier()) {
                    $def['foreign'] = $this->guessColumns($localClasses, $def['table']);
zYne's avatar
zYne committed
297 298 299 300
                } else {
                    // the foreign field is likely to be the
                    // identifier of the foreign class
                    $def['foreign'] = $def['table']->getIdentifier();
301
                    $def['localKey'] = true;
zYne's avatar
zYne committed
302 303 304 305 306 307
                }
            }
        } 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
308
                if ($def['foreign'] === $def['table']->getIdentifier()) {
309
                    $def['localKey'] = true;
zYne's avatar
zYne committed
310
                    $def['local'] = $this->guessColumns($foreignClasses, $this->_table);
zYne's avatar
zYne committed
311
                } else {
zYne's avatar
zYne committed
312
                    $def['local'] = $this->_table->getIdentifier();
zYne's avatar
zYne committed
313 314 315 316 317
                }
            } else {
                // neither local or foreign key is being set
                // try to guess both keys

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

zYne's avatar
zYne committed
320 321 322 323 324 325 326 327 328 329 330
                // the following loops are needed for covering inheritance
                foreach ($localClasses as $class) {
                    $table  = $conn->getTable($class);
                    $column = strtolower($table->getComponentName())
                            . '_' . $table->getIdentifier();
                
                    foreach ($foreignClasses as $class2) {
                        $table2 = $conn->getTable($class2);
                        if ($table2->hasColumn($column)) {
                            $def['foreign'] = $column;
                            $def['local']   = $table->getIdentifier();
331
                            $def['localKey'] = true;
zYne's avatar
zYne committed
332 333
                            return $def;
                        }
zYne's avatar
zYne committed
334 335
                    }
                }
zYne's avatar
zYne committed
336

zYne's avatar
zYne committed
337 338 339 340 341 342 343 344 345 346 347
                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)) {
                            $def['foreign'] = $table->getIdentifier();
                            $def['local']   = $column;
                            return $def;
zYne's avatar
zYne committed
348 349
                        }
                    }
350 351
                }
                Doctrine::dump($def);
352
                throw new Doctrine_Relation_Parser_Exception("Couldn't complete relation definition.");
zYne's avatar
zYne committed
353
            }
zYne's avatar
zYne committed
354
        }
zYne's avatar
zYne committed
355
        return $def;
zYne's avatar
zYne committed
356 357
    }
}