Ejemplo n.º 1
0
 /**
  * Provides a array with all model names
  *
  * @return array
  */
 public function loadModels()
 {
     $models = Doctrine::loadModels($this->modelDir, Doctrine::MODEL_LOADING_CONSERVATIVE);
     $models = Doctrine::initializeModels($models);
     $this->models = Doctrine::filterInvalidModels($models);
     return $this->models;
 }
Ejemplo n.º 2
0
 /**
  * doExport
  *
  * FIXME: This function has ugly hacks in it for temporarily disabling INDEXBY query parts of tables 
  * to export.
  *
  * Update from jwage: I am not sure if their is any other better solution for this. It may be the correct
  * solution to disable the indexBy settings for tables when exporting data fixtures. Maybe a better idea 
  * would be to extract this functionality to a pair of functions to enable/disable the index by settings 
  * so simply turn them on and off when they need to query for the translations standalone and don't need 
  * it to be indexed by the lang.
  *
  * @return void
  */
 public function doExport()
 {
     $models = Doctrine::getLoadedModels();
     $specifiedModels = $this->getModels();
     $data = array();
     // for situation when the $models array is empty, but the $specifiedModels array isn't
     if (empty($models)) {
         $models = $specifiedModels;
     }
     $models = Doctrine::initializeModels($models);
     // temporarily disable indexBy query parts of selected and related tables
     $originalIndexBy = array();
     foreach ($models as $name) {
         $table = Doctrine::getTable($name);
         if (!is_null($indexBy = $table->getBoundQueryPart('indexBy'))) {
             $originalIndexBy[$name] = $indexBy;
             $table->bindQueryPart('indexBy', null);
         }
     }
     foreach ($models as $name) {
         if (!empty($specifiedModels) and !in_array($name, $specifiedModels)) {
             continue;
         }
         $results = Doctrine::getTable($name)->findAll();
         if ($results->count() > 0) {
             $data[$name] = $results;
         }
     }
     // Restore the temporarily disabled indexBy query parts
     foreach ($originalIndexBy as $name => $indexBy) {
         Doctrine::getTable($name)->bindQueryPart('indexBy', $indexBy);
     }
     $data = $this->prepareData($data);
     return $this->dumpData($data);
 }
Ejemplo n.º 3
0
 protected function _diff($from, $to)
 {
     $fromModels = Doctrine::initializeModels(Doctrine::loadModels($from, Doctrine::MODEL_LOADING_AGGRESSIVE));
     $toModels = Doctrine::initializeModels(Doctrine::loadModels($to, Doctrine::MODEL_LOADING_AGGRESSIVE));
     // Build schema information for the models
     $fromInfo = $this->_buildModelInformation($fromModels);
     $toInfo = $this->_buildModelInformation($toModels);
     $this->_decreaseInformations($fromInfo, $toInfo);
     // Build array of changes between the from and to information
     $changes = $this->_buildChanges($fromInfo, $toInfo);
     $this->_cleanup();
     return $changes;
 }
Ejemplo n.º 4
0
 public function __construct()
 {
     // Take a guess at the core model name, and initialize that model. This is important! It will build relationships properly
     // prior to anything being loaded in a core application page while preventing initialization of models that are unlikely to be used.
     //
     // TODO: Change this to initialize all models within this plugin's models/ directory
     if (is_array($this->preloadModels)) {
         foreach ($this->preloadModels as $modelName) {
             Doctrine::initializeModels($modelName);
         }
     }
     $modelName = str_replace('_Plugin', '', get_class($this));
     Doctrine::initializeModels($modelName);
 }
 protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $yaml = sfYaml::load($options['file']);
     Doctrine::initializeModels(array_keys($yaml));
     foreach ($yaml as $model => $tasks) {
         $table = Doctrine::getTable($model);
         $table->getRecordListener()->setOption('disabled', true);
         foreach ($tasks as $key => $task) {
             $this->logSection('mask', sprintf('Masking data of the "%s" model ("%s" task)', $model, $key));
             $q = $table->createQuery();
             $q = $this->parseCondition($q, $model, (array) $task['condition']);
             $q = $this->parseValue($q, $model, (array) $task['values'], (array) $task['options']);
             if ($q) {
                 $q->execute();
             }
             $this->logSection('mask', sprintf('Masked data of the "%s" model ("%s" task)', $model, $key));
         }
     }
 }
Ejemplo n.º 6
0
 /**
  * doExport
  *
  * @return void
  */
 public function doExport()
 {
     $models = Doctrine::getLoadedModels();
     $specifiedModels = $this->getModels();
     $data = array();
     // for situation when the $models array is empty, but the $specifiedModels array isn't
     if (empty($models)) {
         $models = $specifiedModels;
     }
     $models = Doctrine::initializeModels($models);
     foreach ($models as $name) {
         if (!empty($specifiedModels) and !in_array($name, $specifiedModels)) {
             continue;
         }
         $results = Doctrine::getTable($name)->findAll();
         if ($results->count() > 0) {
             $data[$name] = $results;
         }
     }
     $data = $this->prepareData($data);
     return $this->dumpData($data);
 }
 /**
  * Loads all Doctrine builders.
  */
 protected function loadModels()
 {
     Doctrine::loadModels($this->generatorManager->getConfiguration()->getModelDirs(), Doctrine::MODEL_LOADING_CONSERVATIVE);
     $models = Doctrine::getLoadedModels();
     $models = Doctrine::initializeModels($models);
     $this->models = Doctrine::filterInvalidModels($models);
     return $this->models;
 }
Ejemplo n.º 8
0
 public function delete()
 {
     $identifier = $this->identifier();
     $identifier = implode(', ', $identifier);
     // If column aggregation is used on this model we will have $class_type defined. Ensure it's set model is loaded
     if (isset($this['class_type'])) {
         kohana::log('debug', 'Initialized model ' . $this['class_type'] . ' for delete operation.');
         Doctrine::initializeModels($this->class_type);
     }
     if (!self::getBaseTransactionObject()) {
         self::setBaseSaveObject($this);
     }
     try {
         // Before we run the parrent we need to unlink our number
         // this is because the parent will lock the record and if we
         // are proxied then we will not be able to get the necessary fields
         // populated (ya that was a bitch to figure out)
         if (get_parent_class($this) == 'Bluebox_Record') {
             $class_type = get_class($this) . 'Number';
             //transform to class name
         } else {
             $class_type = get_parent_class($this) . 'Number';
             //transform to original parent's class name
         }
         $numbers = Doctrine_Query::create()->from('Number n')->where('class_type = ?', $class_type)->andWhere('foreign_id = ?', $identifier)->execute();
         foreach ($numbers as $number) {
             kohana::log('debug', 'Scheduling detach of number ' . $number['number_id'] . ' from ' . get_class($this) . ' ' . $identifier);
             $number->class_type = NULL;
             $number->foreign_id = 0;
         }
         parent::delete();
         // Ok now if we got this far go ahead an unlink the number, we didnt
         // unlink above because we where not sure if we are in a transaction
         // and if we are not we want to delete to succeed before we unlink :)
         if (!empty($numbers)) {
             foreach ($numbers as $number) {
                 kohana::log('debug', 'Detaching number ' . $number['number_id']);
                 $number->save();
             }
         }
         // Done with any events that may use this
         if (self::getBaseTransactionObject() == $this) {
             self::setBaseSaveObject(NULL);
         }
         $identifier = $this->identifier();
         $identifier = implode(', ', $identifier);
         Kohana::log('debug', 'Deleted record ' . get_class($this) . ' ' . $identifier);
         return TRUE;
     } catch (Doctrine_Validator_Exception $e) {
         Kohana::log('error', 'Doctrine_Validator_Exception: ' . $e->getMessage());
         self::normalizeErrors($e);
         return FALSE;
     } catch (Doctrine_Transaction_Exception $e) {
         Kohana::log('error', 'Doctrine_Transaction_Exception: ' . $e->getMessage());
         self::setBaseSaveObject(NULL);
         throw new Doctrine_Transaction_Exception($e->getMessage());
         return FALSE;
     } catch (Doctrine_Connection_Exception $e) {
         Kohana::log('error', 'Doctrine_Connection_Exception (' . get_class($this) . '): ' . $e->getMessage());
         self::setBaseSaveObject(NULL);
         throw new Doctrine_Connection_Exception($e->getMessage());
         return FALSE;
     } catch (Exception $e) {
         Kohana::log('error', 'Unhandled ' . get_class($e) . ': ' . $e->getMessage());
         self::setBaseSaveObject(NULL);
         throw new Exception($e->getMessage());
         return FALSE;
     }
 }
Ejemplo n.º 9
0
 /**
  * generateMigrationsFromModels
  *
  * @param string $modelsPath 
  * @return void
  */
 public function generateMigrationsFromModels($modelsPath = null, $modelLoading = null)
 {
     if ($modelsPath !== null) {
         $models = Doctrine::filterInvalidModels(Doctrine::loadModels($modelsPath, $modelLoading));
     } else {
         $models = Doctrine::getLoadedModels();
     }
     $models = Doctrine::initializeModels($models);
     $foreignKeys = array();
     foreach ($models as $model) {
         $export = Doctrine::getTable($model)->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 = 'ApplyForeignKeyConstraints';
         $up = '';
         $down = '';
         foreach ($foreignKeys as $tableName => $definitions) {
             $tableForeignKeyNames[$tableName] = array();
             foreach ($definitions as $definition) {
                 $definition['name'] = $tableName . '_' . implode('_', (array) $definition['local']);
                 $up .= $this->buildCreateForeignKey($tableName, $definition);
                 $down .= $this->buildDropForeignKey($tableName, $definition);
             }
         }
         $this->generateMigrationClass($className, array(), $up, $down);
     }
     return true;
 }
Ejemplo n.º 10
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::filterInvalidModels(Doctrine::loadModels($modelsPath, $modelLoading));
     } else {
         $models = Doctrine::getLoadedModels();
     }
     $models = Doctrine::initializeModels($models);
     $foreignKeys = array();
     foreach ($models as $model) {
         $table = Doctrine::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;
 }
Ejemplo n.º 11
0
 public function setUp()
 {
     $thisClass = $this->getInvoker();
     $thisClassName = $thisClass->getTable()->getComponentName();
     if (!empty($thisClass->relationType)) {
         $this->relationType = $thisClass->relationType;
         $mode = ' hasMany ';
     } else {
         $mode = ' hasOne ';
     }
     // If this class is extending Bluebox_Class directly, then load any possibly related models and setup our subclasses
     if (get_parent_class($thisClass) == 'Bluebox_Record') {
         // Go through every model and figure out if it is an extension of this model. If so, relate it via subclasses
         // Note that for efficiency, we assume that we only need to inspect classes that end in the same name as our base class
         // i.e. if the base class is named 'Device' we would only look at other models named things like 'SipDevice' or 'IaxDevice'
         //kohana::log('debug', '*** We are setting up the base class ' . $thisClassName . '...');
         foreach (Doctrine::getLoadedModelFiles() as $model => $dir) {
             if (substr($model, strlen($model) - strlen($thisClassName), strlen($thisClassName)) == $thisClassName) {
                 if (is_subclass_of($model, $thisClassName)) {
                     Doctrine::initializeModels($model);
                 }
             }
         }
     } else {
         // We are extending some other class. Figure out the pieces
         $baseClassName = get_parent_class($thisClass);
         $relatesTo = substr($thisClassName, 0, strlen($thisClassName) - strlen($baseClassName));
         if (self::DEBUG) {
             kohana::log('debug', '*** Setting up extended version of ' . $baseClassName . ' (' . $thisClassName . ")");
         }
         if (class_exists($relatesTo, TRUE)) {
             $relatedPrimaryKey = Doctrine::getTable($relatesTo)->getIdentifier();
             if (self::DEBUG) {
                 kohana::log('debug', $thisClassName . $mode . $relatesTo);
             }
             // Relate this class to the foreign model. So if this was DeviceNumber, this would relate us to Device
             if ($this->relationType == Doctrine_Relation::MANY) {
                 $thisClass->hasMany($relatesTo, array('local' => 'foreign_id', 'foreign' => $relatedPrimaryKey), $this->relationType);
             } else {
                 $thisClass->hasOne($relatesTo, array('local' => 'foreign_id', 'foreign' => $relatedPrimaryKey), $this->relationType);
             }
             // Also relate the base class to the foreign model.
             if (self::DEBUG) {
                 kohana::log('debug', $baseClassName . $mode . $relatesTo);
             }
             $foreignTable = Doctrine::getTable($baseClassName);
             $foreignTable->bind(array($relatesTo, array('local' => 'foreign_id', 'foreign' => $relatedPrimaryKey)), $this->relationType);
             // Unfortunately, we can't turn off individual constraints in Doctrine. So we must turn off constratints for the
             // entire table, because foreign_id may map to multiple different other tables. This is only necessary on
             // concrete tables, since the inheritance tables aren't "real" tables and don't get created anyway.
             // TODO: Find a better solution to keeping constraint checks !
             $thisClass->setAttribute(Doctrine::ATTR_EXPORT, Doctrine::EXPORT_ALL ^ Doctrine::EXPORT_CONSTRAINTS);
             $foreignTable->setAttribute(Doctrine::ATTR_EXPORT, Doctrine::EXPORT_ALL ^ Doctrine::EXPORT_CONSTRAINTS);
             // Create the relation on the other side, too
             if (self::DEBUG) {
                 kohana::log('debug', $relatesTo . $mode . $thisClassName . " (as {$baseClassName})");
             }
             $foreignTable = Doctrine::getTable($relatesTo);
             $foreignTable->bind(array($thisClassName . ' as ' . $baseClassName, array('local' => $relatedPrimaryKey, 'foreign' => 'foreign_id')), $this->relationType);
             // Now also relate to subclasses of the foreign model. So if there were other types of Devices, relate us to them, too
             foreach (Doctrine::getLoadedModelFiles() as $model => $dir) {
                 if (substr($model, strlen($model) - strlen($relatesTo), strlen($relatesTo)) == $relatesTo) {
                     if (is_subclass_of($model, $relatesTo)) {
                         if (self::DEBUG) {
                             kohana::log('debug', $model . $mode . $thisClassName . " (searched for instances of {$relatesTo})\n");
                         }
                         Doctrine::getTable($thisClassName)->addRecordListener(new PolymorphicRecordListener($model));
                         $foreignTable = Doctrine::getTable($model);
                         $foreignTable->bind(array($thisClassName . ' as ' . $baseClassName, array('local' => $relatedPrimaryKey, 'foreign' => 'foreign_id')), $this->relationType);
                     }
                 }
             }
         }
     }
 }
/*
 * This file is part of sfDoctrineGraphvizPlugin
 * (c) 2009 David PHAM-VAN
 * (c) 2009 Dejan Spasic <*****@*****.**>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
require_once dirname(__FILE__) . '/../../../bootstrap.php';
require_once dirname(__FILE__) . '/../../../../lib/generator/doctrineGraphvizMcdGenerator.class.php';
// path to model directory
$modelDir = dirname(__FILE__) . '/../../../_files/model';
// retrieve modelnames
$modelNames = Doctrine::loadModels($modelDir, Doctrine::MODEL_LOADING_CONSERVATIVE);
$modelNames = Doctrine::initializeModels($modelNames);
$modelNames = Doctrine::filterInvalidModels($modelNames);
$subject = new doctrineGraphvizMcdGenerator();
$t = new lime_test(8, new lime_output_color());
$t->ok("" === $subject->getBuffer(), "Test if ->getBuffer() is empty");
$t->ok($subject->generate($modelNames) instanceof doctrineGraphvizMcdGenerator, "Test if generate return a object from type doctrineGraphvizMcdGenerator");
$t->ok(is_string($subject->getBuffer()) && "" !== $subject->getBuffer(), "Test if the current buffer is form type string and not empty");
$t->ok($subject->flushBuffer($modelNames) instanceof doctrineGraphvizMcdGenerator, "Test if ->flushBuffer() return a object from type doctrineGraphvizMcdGenerator");
$t->ok("" === $subject->getBuffer(), "Test if ->flushBuffer() flushed the buffer");
$t->ok($subject->generate($modelNames)->getBuffer() === file_get_contents(dirname(__FILE__) . '/../../../_files/expected/mcd.schema.dot'), "Test the generated graphviz");
try {
    $subject->generate('foo');
    $t->fail('Generate did not throw a exception');
} catch (Exception $e) {
    $t->ok($e instanceof InvalidArgumentException, '->generate throw a InvalidArgumentException');
    $t->ok($e->getMessage() === "First Argument must be from type array. [string] given.", "Test the messsage from exception");
Ejemplo n.º 13
0
 /**
  * Generate a diff between the from and to schema information
  *
  * @param  string $from     Path to set of models to migrate from
  * @param  string $to       Path to set of models to migrate to
  * @return array  $changes
  */
 protected function _diff($from, $to)
 {
     // Load the from and to models
     $fromModels = Doctrine::initializeModels(Doctrine::loadModels($from));
     $toModels = Doctrine::initializeModels(Doctrine::loadModels($to));
     // Build schema information for the models
     $fromInfo = $this->_buildModelInformation($fromModels);
     $toInfo = $this->_buildModelInformation($toModels);
     // Build array of changes between the from and to information
     $changes = $this->_buildChanges($fromInfo, $toInfo);
     $this->_cleanup();
     return $changes;
 }