示例#1
0
 /**
  * Get items from ZOO module params.
  *
  * @param AppData $params Module Parameter
  * @return array Items
  */
 public function getItems($params)
 {
     $items = array();
     if ($application = $this->app->table->application->get($params->get('application', 0))) {
         // set one or multiple categories
         $category = (int) $params->get('category', 0);
         if ($params->get('subcategories')) {
             $categories = $application->getCategoryTree(true);
             if (isset($categories[$category])) {
                 $category = array_merge(array($category), array_keys($categories[$category]->getChildren(true)));
             }
         }
         // get items
         if ($params->get('mode') == 'item') {
             if (($item = $this->app->table->item->get($params->get('item_id'))) && $item->isPublished() && $item->canAccess()) {
                 $items[] = $item;
             }
         } else {
             if ($params->get('mode') == 'types') {
                 $items = $this->app->table->item->getByType($params->get('type'), $application->id, true, null, $params->get('order', array('_itemname')), 0, $params->get('count', 4));
             } else {
                 $items = $this->app->table->item->getByCategory($application->id, $category, true, null, $params->get('order', array('_itemname')), 0, $params->get('count', 4));
             }
         }
     }
     return $items;
 }
 public function testValidateReturnsFalseWhenTwoTablesHaveSamePhpName()
 {
     $table1 = new Table('foo');
     $table2 = new Table('bar');
     $table2->setPhpName('Foo');
     $database = new Database();
     $database->addTable($table1);
     $database->addTable($table2);
     $appData = new AppData();
     $appData->addDatabase($database);
     $validator = new PropelSchemaValidator($appData);
     $this->assertFalse($validator->validate());
     $this->assertContains('Table "bar" declares a phpName already used in another table', $validator->getErrors());
 }
 public static function get_instance()
 {
     if (is_null(self::$instance)) {
         self::$instance = new static();
     }
     return self::$instance;
 }
示例#4
0
 /**
  * Class Constructor
  *
  * @param string|array $data The data to read. Could be either an array or a json string
  *
  * @since 1.0.0
  */
 public function __construct($data = array())
 {
     // decode JSON string
     if (is_string($data)) {
         $data = json_decode($data, $this->_assoc);
     }
     parent::__construct($data);
 }
示例#5
0
 public static function save($filename, $data = array())
 {
     $base = array('version' => null, 'data' => null);
     $version = AppData::first();
     $base['version'] = array('schema' => $version->schema_version, 'data' => $version->data_version, 'seq' => $version->data_sequence_no, 'built' => date('Y-m-d H:i:s'));
     $base['data'] = $data;
     file_put_contents(FileHandler::path() . $filename . '.json', json_encode($base));
 }
function print_style()
{
    $styles = AppData::get_instance()->styles;
    ob_start();
    foreach ($styles as $style) {
        echo '<link href="' . $style . '" rel="stylesheet">';
    }
    ob_end_flush();
}
示例#7
0
 public function __construct()
 {
     $this->started = session_id() !== '';
     if (false === $this->started) {
         AppData::createCommomFolders();
         $this->path(AppData::storagePath() . '/session');
         $this->name('inphinit');
         session_start();
         $this->started = true;
     }
 }
 public function testValidateReturnsTrueWhenTwoTablesHaveSamePhpNameInDifferentNamespaces()
 {
     $column1 = new Column('id');
     $column1->setPrimaryKey(true);
     $table1 = new Table('foo');
     $table1->addColumn($column1);
     $table1->setNamespace('Foo');
     $column2 = new Column('id');
     $column2->setPrimaryKey(true);
     $table2 = new Table('bar');
     $table2->addColumn($column2);
     $table2->setPhpName('Foo');
     $table2->setNamespace('Bar');
     $database = new Database();
     $database->addTable($table1);
     $database->addTable($table2);
     $appData = new AppData();
     $appData->addDatabase($database);
     $validator = new PropelSchemaValidator($appData);
     $this->assertTrue($validator->validate());
 }
示例#9
0
 /**
  * 
  * @param \AppData $myAppData
  * @param string $targetDbName
  */
 public static function getDbFromXml(&$myAppData, $targetDbName)
 {
     $db = self::getDbConnector($targetDbName);
     $xmlDbFiles = self::buildTargetDbSchema($targetDbName);
     // Initialize XmlToAppData object
     $appDataObject = new \XmlToAppData(new CentreonMysqlPlatform($db), null, 'utf-8');
     // Get DB File
     foreach ($xmlDbFiles as $dbFile) {
         $myAppData->joinAppDatas(array($appDataObject->parseFile($dbFile)));
         unset($appDataObject);
         $appDataObject = new \XmlToAppData(new CentreonMysqlPlatform($db), null, 'utf-8');
     }
     unset($appDataObject);
 }
示例#10
0
 public function __construct($expires = 900, $lastModified = 0, $prefix = '')
 {
     $this->expires = $expires;
     if (AppData::createFolder('cache/output') === false) {
         return null;
     }
     $this->lastModified = $lastModified === 0 ? REQUEST_TIME + $this->expires : $lastModified;
     $filename = INPHINIT_PATH . 'storage/cache/output/~';
     if (false === empty($prefix)) {
         $filename .= strlen($prefix) . '.' . sha1($prefix) . '_';
     }
     $path = \UtilsPath();
     $filename .= sha1($path) . '-' . strlen($path);
     $lastModify = $filename . '.1';
     $this->cacheName = $filename;
     if (file_exists($filename) && file_exists($lastModify)) {
         $data = file_get_contents($lastModify);
         if ($data !== false && $data > REQUEST_TIME) {
             $this->isCache = true;
             header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $data) . ' GMT');
             header('Etag: ' . sha1_file($filename));
             if (self::match($data)) {
                 Response::status(304);
             } else {
                 App::on('ready', array($this, 'show'));
             }
             return null;
         }
     }
     $this->cacheTmp = AppData::createTmp();
     $tmp = fopen($this->cacheTmp, 'wb');
     if ($tmp === false) {
         return null;
     }
     $this->handle = $tmp;
     App::on('ready', array($this, 'finish'));
     App::buffer(array($this, 'write'), 1024);
 }
    public function testValidateReturnsFalseWhenCrossRefTableHasTwoFksToTheSameTable()
    {
        $schema = <<<EOF
<database name="bookstore">
    <table name="book">
        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
        <column name="title" type="VARCHAR" size="100" primaryString="true" />
    </table>
    <table name="book_book" isCrossRef="true">
        <column name="parent_id" type="INTEGER" primaryKey="true" required="true"/>
        <column name="child_id" type="INTEGER" primaryKey="true" required="true"/>
        <foreign-key foreignTable="book">
            <reference local="child_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="book">
            <reference local="parent_id" foreign="id"/>
        </foreign-key>
    </table>
</database>
EOF;
        $builder = new PropelQuickBuilder();
        $builder->setSchema($schema);
        $database = $builder->getDatabase();
        $appData = new AppData();
        $appData->addDatabase($database);
        $validator = new PropelSchemaValidator($appData);
        $this->assertFalse($validator->validate());
        $this->assertContains('Table "book_book" implements an equal nest relationship for table "book". This feature is not supported', $validator->getErrors());
    }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connections = $this->getConnections($databaseManager);
     //$connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     $i = new afsDbInfo();
     $this->logSection('propel', 'Reading databases structure...');
     $ad = new AppData();
     $totalNbTables = 0;
     foreach ($connections as $name => $params) {
         $pdo = $databaseManager->getDatabase($name)->getConnection();
         $database = new Database($name);
         $platform = $this->getPlatform($databaseManager, $name);
         $database->setPlatform($platform);
         $database->setDefaultIdMethod(IDMethod::NATIVE);
         $parser = $this->getParser($databaseManager, $name, $pdo);
         //$parser->setMigrationTable($options['migration-table']);
         $parser->setPlatform($platform);
         $nbTables = $parser->parse($database);
         $ad->addDatabase($database);
         $totalNbTables += $nbTables;
         $this->logSection('propel', sprintf('  %d tables imported from database "%s"', $nbTables, $name), null, 'COMMENT');
     }
     if ($totalNbTables) {
         $this->logSection('propel', sprintf('%d tables imported from databases.', $totalNbTables));
     } else {
         $this->logSection('propel', 'Database is empty');
     }
     $this->logSection('propel', 'Loading XML schema files...');
     Phing::startup();
     // required to locate behavior classes...
     $this->schemaToXML(self::DO_NOT_CHECK_SCHEMA, 'generated-');
     $this->copyXmlSchemaFromPlugins('generated-');
     $appData = $this->getModels($databaseManager, true);
     $this->logSection('propel', sprintf('%d tables defined in the schema files.', $appData->countTables()));
     $this->cleanup(true);
     $this->logSection('sql-diff', 'Comparing databases and schemas...');
     $manager = new PropelMigrationManager();
     $manager->setConnections($connections);
     foreach ($ad->getDatabases() as $database) {
         $name = $database->getName();
         $filenameDiff = sfConfig::get('sf_data_dir') . "/sql/{$name}." . time() . ".diff.sql";
         $this->logSection('sql-diff', sprintf('  Comparing database "%s"', $name), null, 'COMMENT');
         if (!$appData->hasDatabase($name)) {
             // FIXME: tables present in database but not in XML
             continue;
         }
         $databaseDiff = PropelDatabaseComparator::computeDiff($database, $appData->getDatabase($name));
         if (!$databaseDiff) {
             //no diff
         }
         $this->logSection('sql-diff', sprintf('Structure of database was modified in datasource "%s": %s', $name, $databaseDiff->getDescription()));
         $platform = $this->getPlatform($databaseManager, $name);
         //up sql
         $upDiff = $platform->getModifyDatabaseDDL($databaseDiff);
         //down sql
         $downDiff = $platform->getModifyDatabaseDDL($databaseDiff->getReverseDiff());
         if ($databaseDiff) {
             $this->logSection('sql-diff', "Writing file {$filenameDiff}");
             afStudioUtil::writeFile($filenameDiff, $upDiff);
             if ($options['insert'] === true || $options['insert'] === 'true') {
                 $this->logSection('sql-diff', "Inserting sql diff");
                 $i->executeSql($upDiff, Propel::getConnection($name));
             }
             if ($options['build'] === true || $options['build'] === 'true') {
                 $this->logSection('sql-diff', 'Creating models from current schema');
                 $this->createTask('propel:build-model')->run();
                 $this->logSection('sql-diff', 'Creating forms from current schema');
                 $this->createTask('propel:build-forms')->run();
                 $this->logSection('sql-diff', 'Setting AppFlower project permissions');
                 $this->createTask('afs:fix-perms')->run();
                 $this->logSection('sql-diff', 'Creating AppFlower validator cache');
                 $this->createTask('appflower:validator-cache')->run(array('frontend', 'cache', 'yes'));
                 $this->logSection('sql-diff', 'Clearing Symfony cache');
                 $this->createTask('cc')->run();
             }
         }
     }
 }
示例#13
0
 protected function dropTables()
 {
     $db = Di::getDefault()->get('db_centreon');
     $platform = new CentreonMysqlPlatform($db);
     // Get current DB State
     $currentDb = self::initializeCurrentSchema($platform);
     // Retreive target DB State
     $updatedAppData = new \AppData($platform);
     $appDataObject = new \XmlToAppData(new CentreonMysqlPlatform($db), null, 'utf-8');
     $updatedAppData->joinAppDatas(array($appDataObject->parseFile(__DIR__ . '/data/empty.xml')));
     unset($appDataObject);
     /* @todo Fatorize */
     $diff = \PropelDatabaseComparator::computeDiff($currentDb, $updatedAppData->getDatabase('centreon'), false);
     if (false !== $diff) {
         $strDiff = $platform->getModifyDatabaseDDL($diff);
         $sqlToBeExecuted = \PropelSQLParser::parseString($strDiff);
         \PropelSQLParser::executeString($strDiff, $db);
     }
 }
示例#14
0
 /**
  * Validates the submitted element
  *
  * @param AppData $value  value
  * @param AppData $params submission parameters
  *
  * @return array
  * @throws AppValidatorException
  */
 public function _validateSubmission($value, $params)
 {
     // init vars
     $trusted_mode = $params->get('trusted_mode');
     // get old file value
     $old_file = $this->get('file');
     $file = '';
     // get file from select list
     if ($trusted_mode && ($file = $value->get('image'))) {
         if (!$this->_inUploadPath($file) && $file != $old_file) {
             throw new AppValidatorException(sprintf('This file is not located in the upload directory.'));
         }
         if (!JFile::exists($file)) {
             throw new AppValidatorException(sprintf('This file does not exist.'));
         }
     } else {
         try {
             // get the uploaded file information
             $userfile = $this->_getUploadedFile();
             // validator hack for element error message after submission controller redirect
             if ((empty($userfile) || empty($userfile['tmp_name'])) && ($value->get('filename') || $value->get('image'))) {
                 if ($message = $this->app->jbsession->get($this->identifier . '||' . $this->key(), 'jbimage_validate')) {
                     throw new AppValidatorException($message);
                 }
             }
             // hack hide undefined error after redirect
             if (!empty($userfile)) {
                 $max_upload_size = $this->config->get('max_upload_size', '512') * 1024;
                 $max_upload_size = empty($max_upload_size) ? null : $max_upload_size;
                 $file = $this->app->validator->create('file', array('mime_type_group' => 'image', 'max_size' => $max_upload_size))->addMessage('mime_type_group', 'Uploaded file is not an image.')->clean($userfile);
             }
         } catch (AppValidatorException $e) {
             $this->app->jbsession->set($this->identifier . '||' . $this->key(), $e->getMessage(), 'jbimage_validate');
             if ($e->getCode() != UPLOAD_ERR_NO_FILE) {
                 throw $e;
             }
             if (!$trusted_mode && $old_file && $value->get('image')) {
                 $file = $old_file;
             }
         }
     }
     if ($params->get('required') && empty($file)) {
         throw new AppValidatorException('Please select an image to upload.');
     }
     $result = array('file' => $this->_moveUploadedFiles($file));
     if ($trusted_mode) {
         $result['title'] = $this->app->validator->create('string', array('required' => false))->clean($value->get('title'));
         $result['link'] = $this->app->validator->create('url', array('required' => false), array('required' => 'Please enter an URL.'))->clean($value->get('link'));
         $result['target'] = $this->app->validator->create('', array('required' => false))->clean($value->get('target'));
         $result['rel'] = $this->app->validator->create('string', array('required' => false))->clean($value->get('rel'));
     }
     $this->next();
     return $result;
 }
示例#15
0
 /**
  * Get interface params for all core elements that used in widgets.
  * @return array
  */
 public function elementsInterfaceParams()
 {
     $options = array();
     $parameters = $this->loadParams();
     $variant = $this->_list->current();
     foreach ($parameters as $params) {
         if (($element = $variant->get($params['identifier'])) && $element->isCore()) {
             $params = new AppData($params);
             $element = $this->_storage->configure($element, array('index' => $params->get('_index'), 'position' => $params->get('_position'), 'template' => $params->get('_template')));
             $options[$element->getElementType()] = $element->interfaceParams($params);
         }
     }
     return $options;
 }
示例#16
0
 /**
  * Builds the assign element info from JSON.
  *
  * @param AppData $data the export data
  *
  * @return array Assign element info
  */
 public function getImportInfo(AppData $data)
 {
     $info = array();
     $application = $this->app->zoo->getApplication();
     // get frontpage count
     $info['frontpage_count'] = (bool) $data->find('categories._root');
     // get category count
     $info['category_count'] = max(array(count($data->get('categories', array())) - (int) $info['frontpage_count'], 0));
     // get types
     $type_elements = array();
     foreach ($application->getTypes() as $type) {
         foreach ($type->getElements() as $element) {
             $type_elements[$type->id][$element->getElementType()][] = $element;
         }
     }
     // get item types
     $info['items'] = array();
     foreach ($data->get('items', array()) as $alias => $item) {
         $group = $item['group'];
         if (!isset($info['items'][$group])) {
             $info['items'][$group]['item_count'] = 0;
             $info['items'][$group]['elements'] = array();
             if (isset($item['elements'])) {
                 foreach ($item['elements'] as $alias => $element) {
                     if (!isset($info['items'][$group]['elements'][$alias])) {
                         // add element type
                         $info['items'][$group]['elements'][$alias]['type'] = ucfirst($element['type']);
                         // add element name
                         $info['items'][$group]['elements'][$alias]['name'] = $element['name'];
                         // add elements to assign too
                         $info['items'][$group]['elements'][$alias]['assign'] = array();
                         foreach ($type_elements as $type => $assign_elements) {
                             if (isset($assign_elements[$element['type']])) {
                                 $info['items'][$group]['elements'][$alias]['assign'][$type] = $assign_elements[$element['type']];
                             }
                         }
                     }
                 }
             }
         }
         $info['items'][$group]['item_count'] += 1;
     }
     return $info;
 }
示例#17
0
 /** Sets up the Propel model. */
 public function setUp()
 {
     $appData = new AppData(new MysqlPlatform());
     $this->database = new Database();
     $appData->addDatabase($this->database);
 }
示例#18
0
 /**
  * 
  * @param \AppData $myAppData
  * @param string $targetDbName
  */
 public static function getDbFromXml(&$myAppData, $operation, $targetDbName)
 {
     // Initialize configuration
     $di = Di::getDefault();
     $targetDb = 'db_' . $targetDbName;
     $db = $di->get($targetDb);
     $xmlDbFiles = self::getAllXmlFiles($operation, $targetDbName);
     // Initialize XmlToAppData object
     $appDataObject = new \XmlToAppData(new \Centreon\Custom\Propel\CentreonMysqlPlatform($db), null, 'utf-8');
     // Get DB File
     foreach ($xmlDbFiles as $dbFile) {
         $myAppData->joinAppDatas(array($appDataObject->parseFile($dbFile)));
         unset($appDataObject);
         $appDataObject = new \XmlToAppData(new \Centreon\Custom\Propel\CentreonMysqlPlatform($db), null, 'utf-8');
     }
     unset($appDataObject);
 }
示例#19
0
?>
" />
    <meta property="og:type" content="website" />
    <meta property="og:image" content="http://ia.media-imdb.com/images/rock.jpg" />
    <!--  Android 5 Chrome Color-->
    <meta name="theme-color" content="#EE6E73">
    <!-- CSS-->
    <link href="template/css/prism.css" rel="stylesheet">
    <link href="template/css/ghpages-materialize.css" type="text/css" rel="stylesheet" media="screen,projection">
    <link href="http://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css">
    <?php 
print_style();
?>
    <script>
        var AppData = <?php 
echo AppData::get_instance()->toJson();
?>
    </script>
    <!--  Scripts-->
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="template/js/jquery.timeago.min.js"></script>
    <script src="template/js/prism.js"></script>
    <script src="template/js/materialize.js"></script>
    <script src="template/js/toc.js"></script>
    <script src="template/js/youtube.js"></script>
    <script src="template/js/init.js"></script>
    <!-- Google Plus Button-->
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <?php 
print_script();
?>
示例#20
0
 /**
  * @param null $default
  * @return mixed
  */
 public function getDescription($default = null)
 {
     return JText::_($this->config->get('description', $default));
 }
示例#21
0
 /**
  * Main method builds all the targets for a typical propel project.
  */
 public function main()
 {
     // check to make sure task received all correct params
     $this->validate();
     $generatorConfig = $this->getGeneratorConfig();
     // loading model from database
     $this->log('Reading databases structure...');
     $connections = $generatorConfig->getBuildConnections();
     if (!$connections) {
         throw new Exception('You must define database connection settings in a buildtime-conf.xml file to use diff');
     }
     $totalNbTables = 0;
     $ad = new AppData();
     foreach ($connections as $name => $params) {
         $this->log(sprintf('Connecting to database "%s" using DSN "%s"', $name, $params['dsn']), Project::MSG_VERBOSE);
         $pdo = $generatorConfig->getBuildPDO($name);
         $database = new Database($name);
         $platform = $generatorConfig->getConfiguredPlatform($pdo);
         $database->setPlatform($platform);
         $database->setDefaultIdMethod(IDMethod::NATIVE);
         $parser = $generatorConfig->getConfiguredSchemaParser($pdo);
         $nbTables = $parser->parse($database, $this);
         $ad->addDatabase($database);
         $totalNbTables += $nbTables;
         $this->log(sprintf('%d tables imported from database "%s"', $nbTables, $name), Project::MSG_VERBOSE);
     }
     if ($totalNbTables) {
         $this->log(sprintf('%d tables imported from databases.', $totalNbTables));
     } else {
         $this->log('Database is empty');
     }
     // loading model from XML
     $this->packageObjectModel = true;
     $appDatasFromXml = $this->getDataModels();
     $appDataFromXml = array_pop($appDatasFromXml);
     // comparing models
     $this->log('Comparing models...');
     $manager = new PropelMigrationManager();
     $manager->setConnections($connections);
     $manager->setMigrationDir($this->getOutputDirectory());
     $migrationsUp = array();
     $migrationsDown = array();
     foreach ($ad->getDatabases() as $database) {
         $name = $database->getName();
         $this->log(sprintf('Comparing database "%s"', $name), Project::MSG_VERBOSE);
         if (!$appDataFromXml->hasDatabase($name)) {
             // FIXME: tables present in database but not in XML
             continue;
         }
         $databaseDiff = PropelDatabaseComparator::computeDiff($database, $appDataFromXml->getDatabase($name), $this->isCaseInsensitive());
         if (!$databaseDiff) {
             $this->log(sprintf('Same XML and database structures for datasource "%s" - no diff to generate', $name), Project::MSG_VERBOSE);
             continue;
         }
         $this->log(sprintf('Structure of database was modified in datasource "%s": %s', $name, $databaseDiff->getDescription()));
         $platform = $generatorConfig->getConfiguredPlatform(null, $name);
         $migrationsUp[$name] = $platform->getModifyDatabaseDDL($databaseDiff);
         $migrationsDown[$name] = $platform->getModifyDatabaseDDL($databaseDiff->getReverseDiff());
     }
     if (!$migrationsUp) {
         $this->log('Same XML and database structures for all datasource - no diff to generate');
         return;
     }
     $timestamp = time();
     $migrationFileName = $manager->getMigrationFileName($timestamp);
     $migrationClassBody = $manager->getMigrationClassBody($migrationsUp, $migrationsDown, $timestamp);
     $_f = new PhingFile($this->getOutputDirectory(), $migrationFileName);
     file_put_contents($_f->getAbsolutePath(), $migrationClassBody);
     $this->log(sprintf('"%s" file successfully created in %s', $_f->getName(), $_f->getParent()));
     if ($editorCmd = $this->getEditorCmd()) {
         $this->log(sprintf('Using "%s" as text editor', $editorCmd));
         shell_exec($editorCmd . ' ' . escapeshellarg($_f->getAbsolutePath()));
     } else {
         $this->log('  Please review the generated SQL statements, and add data migration code if necessary.');
         $this->log('  Once the migration class is valid, call the "migrate" task to execute it.');
     }
 }
示例#22
0
 public static function raw($binary = true)
 {
     if (is_readable('php://input')) {
         $mode = $binary === true ? 'rb' : 'r';
         if (PHP_VERSION_ID >= 50600) {
             return fopen('php://input', $mode);
         }
         $tmp = AppData::createTmp();
         if (copy('php://input', $tmp)) {
             return fopen($tmp, $mode);
         }
     }
     return false;
 }
示例#23
0
 /**
  * Validates the submitted element
  * @param AppData $value  value
  * @param AppData $params submission parameters
  * @return array
  * @throws AppValidatorException
  */
 public function validateSubmission($value, $params)
 {
     $images_arr = $value->get('images');
     if (empty($images_arr)) {
         $images_arr = $value;
     }
     if ($params->get('required') && empty($images_arr)) {
         throw new AppValidatorException('Please select an image to upload.');
     }
     $key = 0;
     foreach ($images_arr as $image) {
         $result[$key]['name'] = $this->app->validator->create('string', array('required' => true))->clean($image['name']);
         $key++;
     }
     return $result;
 }
示例#24
0
 /**
  * Magic method to get access to protected property @_options
  * @param string $property
  * @return mixed
  */
 public function __get($property)
 {
     return $this->options->get($property, null);
 }
示例#25
0
    public function testAppendXmlNamespaceWithAutoPackage()
    {
        $schema = <<<EOF
<?xml version="1.0"?>
<table name="test" namespace="\\testNs"/>
EOF;
        $doc = new DOMDocument('1.0');
        $doc->formatOutput = true;
        $config = new GeneratorConfig();
        $config->setBuildProperties(array('propel.namespace.autoPackage' => 'true'));
        $appData = new AppData();
        $appData->setGeneratorConfig($config);
        $db = new Database('testDb');
        $db->setAppData($appData);
        $table = new Table('test');
        $table->setDatabase($db);
        $table->setNamespace('\\testNs');
        $table->appendXml($doc);
        $xmlstr = trim($doc->saveXML());
        $this->assertSame($schema, $xmlstr);
        $schema = <<<EOF
<?xml version="1.0"?>
<table name="test" namespace="\\testNs" package="testPkg"/>
EOF;
        $doc = new DOMDocument('1.0');
        $doc->formatOutput = true;
        $table->setPackage('testPkg');
        $table->appendXml($doc);
        $xmlstr = trim($doc->saveXML());
        $this->assertSame($schema, $xmlstr);
    }
示例#26
0
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connections = $this->getConnections($databaseManager);
     $this->logSection('propel', 'Reading databases structure...');
     $ad = new AppData();
     $totalNbTables = 0;
     foreach ($connections as $name => $params) {
         if ($options['verbose']) {
             $this->logSection('propel', sprintf('  Connecting to database "%s" using DSN "%s"', $name, $params['dsn']), null, 'COMMENT');
         }
         $pdo = $databaseManager->getDatabase($name)->getConnection();
         $database = new Database($name);
         $platform = $this->getPlatform($databaseManager, $name);
         $database->setPlatform($platform);
         $database->setDefaultIdMethod(IDMethod::NATIVE);
         $parser = $this->getParser($databaseManager, $name, $pdo);
         $parser->setMigrationTable($options['migration-table']);
         $parser->setPlatform($platform);
         $nbTables = $parser->parse($database);
         $ad->addDatabase($database);
         $totalNbTables += $nbTables;
         if ($options['verbose']) {
             $this->logSection('propel', sprintf('  %d tables imported from database "%s"', $nbTables, $name), null, 'COMMENT');
         }
     }
     if ($totalNbTables) {
         $this->logSection('propel', sprintf('%d tables imported from databases.', $totalNbTables));
     } else {
         $this->logSection('propel', 'Database is empty');
     }
     $this->logSection('propel', 'Loading XML schema files...');
     Phing::startup();
     // required to locate behavior classes...
     $this->schemaToXML(self::DO_NOT_CHECK_SCHEMA, 'generated-');
     $this->copyXmlSchemaFromPlugins('generated-');
     $appData = $this->getModels($databaseManager, $options['verbose']);
     $this->logSection('propel', sprintf('%d tables defined in the schema files.', $appData->countTables()));
     $this->cleanup($options['verbose']);
     $this->logSection('propel', 'Comparing databases and schemas...');
     $manager = new PropelMigrationManager();
     $manager->setConnections($connections);
     $migrationsUp = array();
     $migrationsDown = array();
     foreach ($ad->getDatabases() as $database) {
         $name = $database->getName();
         if ($options['verbose']) {
             $this->logSection('propel', sprintf('  Comparing database "%s"', $name), null, 'COMMENT');
         }
         if (!$appData->hasDatabase($name)) {
             // FIXME: tables present in database but not in XML
             continue;
         }
         $databaseDiff = PropelDatabaseComparator::computeDiff($database, $appData->getDatabase($name));
         if (!$databaseDiff) {
             if ($options['verbose']) {
                 $this->logSection('propel', sprintf('  Same XML and database structures for datasource "%s" - no diff to generate', $name), null, 'COMMENT');
             }
             continue;
         }
         $this->logSection('propel', sprintf('Structure of database was modified in datasource "%s": %s', $name, $databaseDiff->getDescription()));
         if ($options['verbose']) {
             $this->logBlock($databaseDiff, 'COMMENT');
         }
         $platform = $this->getPlatform($databaseManager, $name);
         $migrationsUp[$name] = $platform->getModifyDatabaseDDL($databaseDiff);
         $migrationsDown[$name] = $platform->getModifyDatabaseDDL($databaseDiff->getReverseDiff());
     }
     if (!$migrationsUp) {
         $this->logSection('propel', 'Same XML and database structures for all datasources - no diff to generate');
         return;
     }
     $timestamp = time();
     $migrationDirectory = sfConfig::get('sf_root_dir') . DIRECTORY_SEPARATOR . $options['migration-dir'];
     $migrationFileName = $manager->getMigrationFileName($timestamp);
     $migrationFilePath = $migrationDirectory . DIRECTORY_SEPARATOR . $migrationFileName;
     if ($options['ask-confirmation'] && !$this->askConfirmation(array(sprintf('Migration class will be generated in %s', $migrationFilePath), 'Are you sure you want to proceed? (Y/n)'), 'QUESTION_LARGE', true)) {
         $this->logSection('propel', 'Task aborted.');
         return 1;
     }
     $this->getFilesystem()->mkdirs($migrationDirectory);
     $migrationClassBody = $manager->getMigrationClassBody($migrationsUp, $migrationsDown, $timestamp);
     file_put_contents($migrationFilePath, $migrationClassBody);
     $this->logSection('propel', sprintf('"%s" file successfully created in %s', $migrationFileName, $migrationDirectory));
     if ($editorCmd = $options['editor-cmd']) {
         $this->logSection('propel', sprintf('Using "%s" as text editor', $editorCmd));
         shell_exec($editorCmd . ' ' . escapeshellarg($migrationFilePath));
     } else {
         $this->logSection('propel', '  Please review the generated SQL statements, and add data migration code if necessary.');
         $this->logSection('propel', '  Once the migration class is valid, call the "propel:migrate" task to execute it.');
     }
 }
示例#27
0
 /**
  * Packages the datamodels to one datamodel per package
  *
  * This applies only when the the packageObjectModel option is set. We need to
  * re-package the datamodels to allow the database package attribute to control
  * which tables go into which SQL file.
  *
  * @return array The packaged datamodels
  */
 protected function packageDataModels()
 {
     static $packagedDataModels;
     if (is_null($packagedDataModels)) {
         $dataModels = $this->getDataModels();
         $dataModel = array_shift($dataModels);
         $packagedDataModels = array();
         $platform = $this->getPlatformForTargetDatabase();
         foreach ($dataModel->getDatabases() as $db) {
             foreach ($db->getTables() as $table) {
                 $package = $table->getPackage();
                 if (!isset($packagedDataModels[$package])) {
                     $dbClone = $this->cloneDatabase($db);
                     $dbClone->setPackage($package);
                     $ad = new AppData($platform);
                     $ad->setName($dataModel->getName());
                     $ad->addDatabase($dbClone);
                     $packagedDataModels[$package] = $ad;
                 }
                 $packagedDataModels[$package]->getDatabase($db->getName())->addTable($table);
             }
         }
     }
     return $packagedDataModels;
 }
示例#28
0
 /**
  * @param array $options
  * @return $this
  */
 public function bindData(array $options = array())
 {
     $elements = new AppData();
     if (isset($options['data'])) {
         $elements->exchangeArray($options['data']);
     }
     foreach ($this->elements as $key => $element) {
         $this->set($key, $this->setElement($element, $elements->get($key)));
     }
     return $this;
 }