Ejemplo n.º 1
0
    /**
     * Generate a set of migrations from a set of models
     *
     * @param  string $modelsPath    Path to models
     * @param  string $modelLoading  What type of model loading to use when loading the models
     * @return boolean
     */
    public function generateMigrationsFromModels($modelsPath = null, $modelLoading = null)
    {
        if ($modelsPath !== null) {
            $models = Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels($modelsPath, $modelLoading));
        } else {
            $models = Doctrine_Core::getLoadedModels();
        }

        $models = Doctrine_Core::initializeModels($models);

        $foreignKeys = array();

        foreach ($models as $model) {
            $table = Doctrine_Core::getTable($model);
            if ($table->getTableName() !== $this->migration->getTableName()) {
                $export = $table->getExportableFormat();

                $foreignKeys[$export['tableName']] = $export['options']['foreignKeys'];

                $up = $this->buildCreateTable($export);
                $down = $this->buildDropTable($export);

                $className = 'Add' . Doctrine_Inflector::classify($export['tableName']);

                $this->generateMigrationClass($className, array(), $up, $down);
            }
        }

        if ( ! empty($foreignKeys)) {
            $className = 'AddFks';

            $up = array();
            $down = array();
            foreach ($foreignKeys as $tableName => $definitions)    {
                $tableForeignKeyNames[$tableName] = array();

                foreach ($definitions as $definition) {
                    $up[] = $this->buildCreateForeignKey($tableName, $definition);
                    $down[] = $this->buildDropForeignKey($tableName, $definition);
                }
            }

            $up = implode("\n", $up);
            $down = implode("\n", $down);
            if ($up || $down) {
                $this->generateMigrationClass($className, array(), $up, $down);
            }
        }

        return true;
    }