Factory.php 11.3 KB
Newer Older
1
<?php 
romanb's avatar
romanb committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 *  $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.org>.
 */
21 22

/**
romanb's avatar
romanb committed
23 24
 * The metadata factory is used to create ClassMetadata objects that contain all the
 * metadata of a class.
25 26
 *
 * @package Doctrine
romanb's avatar
romanb committed
27
 * @since   1.0
28 29 30 31 32 33 34
 */
class Doctrine_ClassMetadata_Factory
{
    protected $_conn;
    protected $_driver;
    
    /**
romanb's avatar
romanb committed
35
     * The already loaded metadata objects.
36 37 38
     */
    protected $_loadedMetadata = array();
    
romanb's avatar
romanb committed
39 40 41 42 43 44 45 46
    /**
     * Constructor.
     * Creates a new factory instance that uses the given connection and metadata driver
     * implementations.
     *
     * @param $conn    The connection to use.
     * @param $driver  The metadata driver to use.
     */
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 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
    public function __construct(Doctrine_Connection $conn, $driver)
    {
        $this->_conn = $conn;
        $this->_driver = $driver;
    }
    
    /**
     * Returns the metadata object for a class.
     *
     * @param string $className  The name of the class.
     * @return Doctrine_Metadata
     */
    public function getMetadataFor($className)
    {
        if (isset($this->_loadedMetadata[$className])) {
            return $this->_loadedMetadata[$className];
        }
        $this->_loadClasses($className, $this->_loadedMetadata);
        
        return $this->_loadedMetadata[$className];
    }
    
    /**
     * Loads the metadata of the class in question and all it's ancestors whose metadata
     * is still not loaded.
     *
     * @param string $name   The name of the class for which the metadata should get loaded.
     * @param array  $tables The metadata collection to which the loaded metadata is added.
     */
    protected function _loadClasses($name, array &$classes)
    {
        $parentClass = $name;
        $parentClasses = array();
        $loadedParentClass = false;
        while ($parentClass = get_parent_class($parentClass)) {
            if ($parentClass == 'Doctrine_Record') {
                break;
            }
            if (isset($classes[$parentClass])) {
                $loadedParentClass = $parentClass;
                break;
            }
            $parentClasses[] = $parentClass;
        }
        $parentClasses = array_reverse($parentClasses);
        $parentClasses[] = $name;
        
        if ($loadedParentClass) {
            $class = $classes[$loadedParentClass];
        } else {
            $rootClassOfHierarchy = count($parentClasses) > 0 ? array_shift($parentClasses) : $name;
            $class = new Doctrine_ClassMetadata($rootClassOfHierarchy, $this->_conn);
            $this->_loadMetadata($class, $rootClassOfHierarchy);
            $classes[$rootClassOfHierarchy] = $class;
        }
        
        if (count($parentClasses) == 0) {
            return $class;
        }
        
        // load metadata of subclasses
        // -> child1 -> child2 -> $name
        
        $parent = $class;
        foreach ($parentClasses as $subclassName) {
            $subClass = new Doctrine_ClassMetadata($subclassName, $this->_conn);
            $subClass->setInheritanceType($parent->getInheritanceType(), $parent->getInheritanceOptions());
            $this->_addInheritedFields($subClass, $parent);
            $this->_addInheritedRelations($subClass, $parent);
            $this->_loadMetadata($subClass, $subclassName);
romanb's avatar
romanb committed
117
            if ($parent->getInheritanceType() == Doctrine::INHERITANCE_TYPE_SINGLE_TABLE) {
118 119 120 121 122 123 124 125 126 127 128 129
                $subClass->setTableName($parent->getTableName());
            }
            $classes[$subclassName] = $subClass;
            $parent = $subClass;
        }
    }
    
    protected function _addInheritedFields($subClass, $parentClass)
    {
        foreach ($parentClass->getColumns() as $name => $definition) {
            $fullName = "$name as " . $parentClass->getFieldName($name);
            $definition['inherited'] = true;
romanb's avatar
romanb committed
130
            $subClass->mapColumn($fullName, $definition['type'], $definition['length'],
131 132 133 134 135
                    $definition);
        }
    }
    
    protected function _addInheritedRelations($subClass, $parentClass) {
136 137
        foreach ($parentClass->getRelationParser()->getRelationDefinitions() as $name => $definition) {
            $subClass->getRelationParser()->addRelationDefinition($name, $definition);
138 139 140 141
        }
    }
    
    /**
142 143 144 145
     * Loads the metadata of a specified class.
     *
     * @param Doctrine_ClassMetadata $class  The container for the metadata.
     * @param string $name  The name of the class for which the metadata will be loaded.
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
     */
    protected function _loadMetadata(Doctrine_ClassMetadata $class, $name)
    {
        if ( ! class_exists($name) || empty($name)) {
            /*try {
                throw new Exception();
            } catch (Exception $e) {
                echo $e->getTraceAsString();
            }*/
            throw new Doctrine_Exception("Couldn't find class " . $name . ".");
        }

        $names = array();
        $className = $name;
        // get parent classes
        do {
            if ($className === 'Doctrine_Record') {
                break;
            } else if ($className == $name) {
                continue;
            }
            $names[] = $className;
        } while ($className = get_parent_class($className));

        if ($className === false) {
171 172 173 174 175
            try {
                throw new Exception();
            } catch (Exception $e) {
                echo $e->getTraceAsString() . "<br />";
            }
176 177 178 179
            throw new Doctrine_ClassMetadata_Factory_Exception("Unknown component '$className'.");
        }

        // save parents
romanb's avatar
romanb committed
180
        $class->setParentClasses($names);
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

        // load further metadata
        $this->_driver->loadMetadataForClass($name, $class);
        
        $tableName = $class->getTableName();
        if ( ! isset($tableName)) {
            $class->setTableName(Doctrine::tableize($class->getClassName()));
        }
        
        $this->_initIdentifier($class);
        
        return $class;
    }
    
    /**
     * Initializes the class identifier(s)/primary key(s).
     *
     * @param Doctrine_Metadata  The metadata container of the class in question.
     */
    protected function _initIdentifier(Doctrine_ClassMetadata $class)
    {
202
        switch (count((array)$class->getIdentifier())) {
203
            case 0:
romanb's avatar
romanb committed
204
                if ($class->getInheritanceType() == Doctrine::INHERITANCE_TYPE_JOINED &&
205
                        count($class->getParentClasses()) > 0) {
206
                            
207
                    $parents = $class->getParentClasses();
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
                    $root = end($parents);
                    $rootClass = $class->getConnection()->getMetadata($root);
                    $class->setIdentifier($rootClass->getIdentifier());
                    
                    if ($class->getIdentifierType() !== Doctrine::IDENTIFIER_AUTOINC) {
                        $class->setIdentifierType($rootClass->getIdentifierType());
                    } else {
                        $class->setIdentifierType(Doctrine::IDENTIFIER_NATURAL);
                    }

                    // add all inherited primary keys
                    foreach ((array) $class->getIdentifier() as $id) {
                        $definition = $rootClass->getDefinitionOf($id);

                        // inherited primary keys shouldn't contain autoinc
                        // and sequence definitions
                        unset($definition['autoincrement']);
                        unset($definition['sequence']);

                        // add the inherited primary key column
                        $fullName = $rootClass->getColumnName($id) . ' as ' . $id;
                        $class->setColumn($fullName, $definition['type'], $definition['length'],
                                $definition, true);
                    }
                } else {
                    $definition = array('type' => 'integer',
                                        'length' => 20,
                                        'autoincrement' => true,
                                        'primary' => true);
                    $class->setColumn('id', $definition['type'], $definition['length'], $definition, true);
238
                    $class->setIdentifier(array('id'));
239 240 241 242
                    $class->setIdentifierType(Doctrine::IDENTIFIER_AUTOINC);
                }
                break;
            case 1:
243
                foreach ((array)$class->getIdentifier() as $pk) {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
                    $columnName = $class->getColumnName($pk);
                    $thisColumns = $class->getColumns();
                    $e = $thisColumns[$columnName];

                    $found = false;

                    foreach ($e as $option => $value) {
                        if ($found) {
                            break;
                        }

                        $e2 = explode(':', $option);

                        switch (strtolower($e2[0])) {
                            case 'autoincrement':
                            case 'autoinc':
                                $class->setIdentifierType(Doctrine::IDENTIFIER_AUTOINC);
                                $found = true;
                                break;
                            case 'seq':
                            case 'sequence':
                                $class->setIdentifierType(Doctrine::IDENTIFIER_SEQUENCE);
                                $found = true;

                                if ($value) {
romanb's avatar
romanb committed
269
                                    $class->setTableOption('sequenceName', $value);
270 271
                                } else {
                                    if (($sequence = $class->getAttribute(Doctrine::ATTR_DEFAULT_SEQUENCE)) !== null) {
romanb's avatar
romanb committed
272
                                        $class->setTableOption('sequenceName', $sequence);
273
                                    } else {
romanb's avatar
romanb committed
274 275
                                        $class->setTableOption('sequenceName', $class->getConnection()
                                                ->getSequenceName($class->getTableName()));
276 277 278 279 280 281 282 283 284 285 286
                                    }
                                }
                                break;
                        }
                    }
                    $identifierType = $class->getIdentifierType();
                    if ( ! isset($identifierType)) {
                        $class->setIdentifierType(Doctrine::IDENTIFIER_NATURAL);
                    }
                }

287
                $class->setIdentifier(array($pk));
288 289 290 291 292 293 294 295 296 297 298

                break;
            default:
                $class->setIdentifierType(Doctrine::IDENTIFIER_COMPOSITE);
        }
    }
    
}