public function testTest()
    {
        $yml = <<<END
---
detect_relations: true
Ticket_1118_User:
  columns:
    username: string(255)
    password: string(255)
    ticket__1118__profile_id: string

Ticket_1118_Profile:
  columns:
    id:
      type: integer(4)
      autoincrement: true
      primary: true
    name: string(255)
END;
        try {
            file_put_contents('test.yml', $yml);
            $import = new Doctrine_Import_Schema();
            $array = $import->buildSchema('test.yml', 'yml');
            // Test that ticket__1118__profile_id is changed to to be integer(4) since the primary key of
            // the relationship is set to that
            $this->assertEqual($array['Ticket_1118_User']['columns']['ticket__1118__profile_id']['type'], 'integer');
            $this->assertEqual($array['Ticket_1118_User']['columns']['ticket__1118__profile_id']['length'], '4');
            $this->pass();
        } catch (Exception $e) {
            $this->fail();
        }
        unlink('test.yml');
    }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $this->logSection('doctrine', 'generating model classes');
     $config = $this->getCliConfig();
     $this->_checkForPackageParameter($config['yaml_schema_path']);
     $tmpPath = sfConfig::get('sf_cache_dir') . DIRECTORY_SEPARATOR . 'tmp';
     if (!file_exists($tmpPath)) {
         Doctrine_Lib::makeDirectories($tmpPath);
     }
     $plugins = $this->configuration->getPlugins();
     foreach ($this->configuration->getAllPluginPaths() as $plugin => $path) {
         if (!in_array($plugin, $plugins)) {
             continue;
         }
         $schemas = sfFinder::type('file')->name('*.yml')->in($path . '/config/doctrine');
         foreach ($schemas as $schema) {
             $tmpSchemaPath = $tmpPath . DIRECTORY_SEPARATOR . $plugin . '-' . basename($schema);
             $models = Doctrine_Parser::load($schema, 'yml');
             if (!isset($models['package'])) {
                 $models['package'] = $plugin . '.lib.model.doctrine';
                 $models['package_custom_path'] = $path . '/lib/model/doctrine';
             }
             Doctrine_Parser::dump($models, 'yml', $tmpSchemaPath);
         }
     }
     $options = array('generateBaseClasses' => true, 'generateTableClasses' => true, 'packagesPath' => sfConfig::get('sf_plugins_dir'), 'packagesPrefix' => 'Plugin', 'suffix' => '.class.php', 'baseClassesDirectory' => 'base', 'baseClassName' => 'sfDoctrineRecord');
     $options = array_merge($options, sfConfig::get('doctrine_model_builder_options', array()));
     $import = new Doctrine_Import_Schema();
     $import->setOptions($options);
     $import->importSchema(array($tmpPath, $config['yaml_schema_path']), 'yml', $config['models_path']);
 }
    public function testTest()
    {
        $yml = <<<END
---
Ticket_1527_User:
  columns:
    username:
      type: string(255)
      extra:
        test: 123
    password:
      type: string(255)
END;

        $import = new Doctrine_Import_Schema();
        $schema = $import->buildSchema($yml, 'yml');
        $this->assertEqual($schema['Ticket_1527_User']['columns']['username']['extra']['test'], '123');

        $path = dirname(__FILE__) . '/../tmp';
        $import->importSchema($yml, 'yml', $path);
        
        require_once($path . '/generated/BaseTicket_1527_User.php');
        require_once($path . '/Ticket_1527_User.php');
        $username = Doctrine::getTable('Ticket_1527_User')->getDefinitionOf('username');
        $this->assertEqual($username['extra']['test'], '123');
    }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $config = $this->getCliConfig();
     $pluginSchemaDirectories = glob(sfConfig::get('sf_plugins_dir') . DIRECTORY_SEPARATOR . '*' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine');
     $pluginSchemas = sfFinder::type('file')->name('*.yml')->in($pluginSchemaDirectories);
     $tmpPath = sfConfig::get('sf_cache_dir') . DIRECTORY_SEPARATOR . 'tmp';
     if (!file_exists($tmpPath)) {
         Doctrine_Lib::makeDirectories($tmpPath);
     }
     foreach ($pluginSchemas as $schema) {
         $schema = str_replace('/', DIRECTORY_SEPARATOR, $schema);
         $plugin = str_replace(sfConfig::get('sf_plugins_dir') . DIRECTORY_SEPARATOR, '', $schema);
         $e = explode(DIRECTORY_SEPARATOR, $plugin);
         $plugin = $e[0];
         $name = basename($schema);
         $tmpSchemaPath = $tmpPath . DIRECTORY_SEPARATOR . $plugin . '-' . $name;
         $models = Doctrine_Parser::load($schema, 'yml');
         if (!isset($models['package'])) {
             $models['package'] = $plugin . '.lib.model.doctrine';
         }
         Doctrine_Parser::dump($models, 'yml', $tmpSchemaPath);
     }
     $import = new Doctrine_Import_Schema();
     $import->setOption('generateBaseClasses', true);
     $import->setOption('generateTableClasses', true);
     $import->setOption('packagesPath', sfConfig::get('sf_plugins_dir'));
     $import->setOption('packagesPrefix', 'Plugin');
     $import->setOption('suffix', '.class.php');
     $import->setOption('baseClassesDirectory', 'generated');
     $import->setOption('baseClassName', 'sfDoctrineRecord');
     $import->importSchema(array($tmpPath, $config['yaml_schema_path']), 'yml', $config['models_path']);
     $this->dispatcher->notify(new sfEvent($this, 'command.log', array($this->formatter->formatSection('doctrine', 'Generated models successfully'))));
 }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $this->logSection('doctrine', 'generating model classes');
     $config = $this->getCliConfig();
     $builderOptions = $this->configuration->getPluginConfiguration('sfDoctrinePlugin')->getModelBuilderOptions();
     $stubFinder = sfFinder::type('file')->prune('base')->name('*' . $builderOptions['suffix']);
     $before = $stubFinder->in($config['models_path']);
     $schema = $this->prepareSchemaFile($config['yaml_schema_path']);
     $import = new Doctrine_Import_Schema();
     $import->setOptions($builderOptions);
     $import->importSchema($schema, 'yml', $config['models_path']);
     // markup base classes with magic methods
     foreach (sfYaml::load($schema) as $model => $definition) {
         // Start OrangeHRM Modified Section
         $subPackageName = $this->getSubPackageName($definition);
         // End OrangeHRM Modified Section
         $file = sprintf('%s%s/%s/Base%s%s', $config['models_path'], isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $builderOptions['baseClassesDirectory'], $model, $builderOptions['suffix']);
         $code = file_get_contents($file);
         // introspect the model without loading the class
         if (preg_match_all('/@property (\\w+) \\$(\\w+)/', $code, $matches, PREG_SET_ORDER)) {
             $properties = array();
             foreach ($matches as $match) {
                 $properties[$match[2]] = $match[1];
             }
             $typePad = max(array_map('strlen', array_merge(array_values($properties), array($model))));
             $namePad = max(array_map('strlen', array_keys(array_map(array('sfInflector', 'camelize'), $properties))));
             $setters = array();
             $getters = array();
             foreach ($properties as $name => $type) {
                 $camelized = sfInflector::camelize($name);
                 $collection = 'Doctrine_Collection' == $type;
                 $getters[] = sprintf('@method %-' . $typePad . 's %s%-' . ($namePad + 2) . 's Returns the current record\'s "%s" %s', $type, 'get', $camelized . '()', $name, $collection ? 'collection' : 'value');
                 $setters[] = sprintf('@method %-' . $typePad . 's %s%-' . ($namePad + 2) . 's Sets the current record\'s "%s" %s', $model, 'set', $camelized . '()', $name, $collection ? 'collection' : 'value');
             }
             // use the last match as a search string
             $code = str_replace($match[0], $match[0] . PHP_EOL . ' * ' . PHP_EOL . ' * ' . implode(PHP_EOL . ' * ', array_merge($getters, $setters)), $code);
             // Start OrangeHRM Modified Section
             $tokens = array('##SUBPACKAGE##' => $subPackageName);
             $code = str_replace(array_keys($tokens), array_values($tokens), $code);
             // End OrangeHRM Modified Section
             file_put_contents($file, $code);
         }
     }
     $properties = parse_ini_file(sfConfig::get('sf_config_dir') . '/properties.ini', true);
     $tokens = array('##PACKAGE##' => isset($properties['symfony']['name']) ? $properties['symfony']['name'] : 'symfony', '##SUBPACKAGE##' => 'model', '##NAME##' => isset($properties['symfony']['author']) ? $properties['symfony']['author'] : 'Your name here', ' <##EMAIL##>' => '', "{\n\n}" => "{\n}\n");
     // cleanup new stub classes
     $after = $stubFinder->in($config['models_path']);
     $this->getFilesystem()->replaceTokens(array_diff($after, $before), '', '', $tokens);
     // cleanup base classes
     $baseFinder = sfFinder::type('file')->name('Base*' . $builderOptions['suffix']);
     $baseDirFinder = sfFinder::type('dir')->name('base');
     $this->getFilesystem()->replaceTokens($baseFinder->in($baseDirFinder->in($config['models_path'])), '', '', $tokens);
     $this->reloadAutoload();
 }
 /**
  * Execute task
  * 
  * @param   array   $arguments  Task arguments [optional]
  * @param   array   $options    Task options [optional]
  * @return  void
  */
 protected function execute($arguments = array(), $options = array())
 {
     $this->logSection('doctrine', 'generating model classes');
     $config = $this->getCliConfig();
     $builderOptions = $this->configuration->getPluginConfiguration('sfDoctrinePlugin')->getModelBuilderOptions();
     $finder = sfFinder::type('file')->prune('base')->name('*' . $builderOptions['suffix']);
     $before = $finder->in($config['models_path']);
     $schema = $this->prepareSchemaFile($config['yaml_schema_path']);
     $import = new Doctrine_Import_Schema();
     $import->setOptions($builderOptions);
     $import->importSchema($schema, 'yml', $config['models_path']);
     $base = $builderOptions['baseClassesDirectory'];
     $suff = $builderOptions['suffix'];
     $src = array('##PACKAGE##', '##SUBPACKAGE##', '##NAME##', ' <##EMAIL##>');
     // markup base classes with magic methods
     foreach (sfYaml::load($schema) as $model => $definition) {
         $package = isset($definition['package']) ? substr($definition['package'], 0, strpos($definition['package'], '.')) : '';
         $basePath = $config['models_path'] . ($package ? '/' . $package : '') . '/';
         $file = $basePath . $base . '/Base' . $model . $suff;
         $code = file_get_contents($file);
         // introspect the model without loading the class
         if (preg_match_all('/@property (\\w+) \\$(\\w+)/', $code, $matches, PREG_SET_ORDER)) {
             $properties = array();
             foreach ($matches as $match) {
                 $properties[$match[2]] = $match[1];
             }
             $typePad = max(array_map('strlen', array_merge(array_values($properties), array($model))));
             $namePad = max(array_map('strlen', array_keys(array_map(array('sfInflector', 'camelize'), $properties))));
             $setters = array();
             $getters = array();
             foreach ($properties as $name => $type) {
                 $camelized = sfInflector::camelize($name);
                 $collection = 'Doctrine_Collection' == $type;
                 $getters[] = sprintf('@method %-' . $typePad . 's %s%-' . ($namePad + 2) . 's Returns the current record\'s "%s" %s', $type, 'get', $camelized . '()', $name, $collection ? 'collection' : 'value');
                 $setters[] = sprintf('@method %-' . $typePad . 's %s%-' . ($namePad + 2) . 's Sets the current record\'s "%s" %s', $model, 'set', $camelized . '()', $name, $collection ? 'collection' : 'value');
             }
             $dst = array(dinGeneratorSigner::getProjectName(), 'lib.model.doctrine' . ($package ? '.' . $package : '') . '.base', dinGeneratorSigner::getAuthor(), '');
             $code = str_replace($match[0], $match[0] . PHP_EOL . ' * ' . PHP_EOL . ' * ' . implode(PHP_EOL . ' * ', array_merge($getters, $setters)), $code);
             $code = str_replace($src, $dst, $code);
             file_put_contents($file, $code);
         }
         $this->replaceLibClasses($basePath, $model, $package, $suff);
         if ($package) {
             $basePath = $this->configuration->getPluginConfiguration($package)->getRootDir() . '/lib/model/doctrine/';
             $this->replaceLibClasses($basePath, $model, $package, $suff, true);
         }
     }
     $this->reloadAutoload();
 }
    public function testImportOfHieriarchyOfPluginGeneration()
    {
        $yml = <<<END
---
WikiTest:
  actAs:
    I18n:
      fields: [title, content]
      actAs:
        Versionable:
          fields: [title, content]
        Searchable:
          fields: [title, content]
        Sluggable:
          fields: [title]
  columns:
    title: string(255)
    content: string
END;
        
        file_put_contents('wiki.yml', $yml);
        $path = dirname(__FILE__) . '/tmp/import_builder_test';

        $import = new Doctrine_Import_Schema();
        $import->setOption('generateTableClasses', true);
        $import->importSchema('wiki.yml', 'yml', $path);

        // check that the plugin hierarchy will produce the right sql statements
        // this is almost an end-to-end testing :-)
        $models = Doctrine::loadModels($path, Doctrine::MODEL_LOADING_CONSERVATIVE);

        $sql = $this->conn->export->exportClassesSql(array('WikiTest'));

        $result = array(
            0 => 'CREATE TABLE wiki_test_translation_version (id INTEGER, lang CHAR(2), title VARCHAR(255), content VARCHAR(2147483647), version INTEGER, PRIMARY KEY(id, lang, version))',
            1 => 'CREATE TABLE wiki_test_translation_index (id INTEGER, lang CHAR(2), keyword VARCHAR(200), field VARCHAR(50), position INTEGER, PRIMARY KEY(id, lang, keyword, field, position))',
            2 => 'CREATE TABLE wiki_test_translation (id INTEGER, title VARCHAR(255), content VARCHAR(2147483647), lang CHAR(2), version INTEGER, slug VARCHAR(255), PRIMARY KEY(id, lang))',
            3 => 'CREATE TABLE wiki_test (id INTEGER PRIMARY KEY AUTOINCREMENT)',
            4 => 'CREATE INDEX sluggable_idx ON wiki_test_translation (slug)',
        );
            
        foreach($sql as $idx => $req) {
            $this->assertEqual($req, $result[$idx]);
        }        
        
        Doctrine_Lib::removeDirectories($path);
        unlink('wiki.yml');
    }
示例#8
0
 public function testClassExistsAfterImport()
 {
     Doctrine_Core::setModelsDirectory(dirname(__FILE__) . '/DC95/models');
     $import = new Doctrine_Import_Schema();
     $import->setOptions(array('pearStyle' => true, 'baseClassesDirectory' => null, 'baseClassPrefix' => 'Base_', 'classPrefix' => 'DC95_', 'classPrefixFiles' => true));
     $modelsPath = dirname(__FILE__) . '/DC95/models';
     $import->importSchema(dirname(__FILE__) . '/DC95/schema.yml', 'yml', $modelsPath);
     /*
     $this->assertTrue(file_exists($modelsPath . '/DC95/Base/Article.php'));
     $this->assertTrue(file_exists($modelsPath . '/DC95/Base/Article/Category.php'));
     $this->assertTrue(file_exists($modelsPath . '/DC95/Article.php'));
     $this->assertTrue(file_exists($modelsPath . '/DC95/Article/Category.php'));
     */
     Doctrine_Core::setModelsDirectory(null);
     Doctrine_Lib::removeDirectories(dirname(__FILE__) . '/DC95/models');
 }
示例#9
0
 /**
  * Modify options for Zend Framework model compliant code-generation.
  *
  * @return array
  */
 public function getOptions()
 {
     $options = parent::getOptions();
     $options['pearStyle'] = false;
     $options['baseClassesDirectory'] = 'Base';
     $options['baseClassPrefix'] = '';
     $options['classPrefix'] = '';
     $options['classPrefixFiles'] = true;
     return $options;
 }
示例#10
0
 public function testBuildSchema()
 {
     $schema = new Doctrine_Import_Schema();
     $array = $schema->buildSchema('schema.yml', 'yml');
     $model = $array['SchemaTestUser'];
     $this->assertTrue(array_key_exists('connection', $model));
     $this->assertTrue(array_key_exists('className', $model));
     $this->assertTrue(array_key_exists('tableName', $model));
     $this->assertTrue(array_key_exists('columns', $model) && is_array($model['columns']));
     $this->assertTrue(array_key_exists('relations', $model) && is_array($model['relations']));
     $this->assertTrue(array_key_exists('indexes', $model) && is_array($model['indexes']));
     $this->assertTrue(array_key_exists('attributes', $model) && is_array($model['attributes']));
     $this->assertTrue(array_key_exists('templates', $model) && is_array($model['columns']));
     $this->assertTrue(array_key_exists('actAs', $model) && is_array($model['actAs']));
     $this->assertTrue(array_key_exists('options', $model) && is_array($model['options']));
     $this->assertTrue(array_key_exists('package', $model));
     $this->assertTrue(array_key_exists('inheritance', $model) && is_array($model['inheritance']));
     $this->assertTrue(array_key_exists('detect_relations', $model) && is_bool($model['detect_relations']));
     $this->assertEqual($array['AliasTest']['columns']['test_col']['name'], 'test_col as test_col_alias');
 }
示例#11
0
 /**
  * Generate a yaml schema file from an existing directory of models
  *
  * @param string $yamlPath Path to your yaml schema files
  * @param string $directory Directory to generate your models in
  * @param array  $options Array of options to pass to the schema importer
  * @return void
  */
 public static function generateModelsFromYaml($yamlPath, $directory, $options = array())
 {
     $import = new Doctrine_Import_Schema();
     $import->setOptions($options);
     return $import->importSchema($yamlPath, 'yml', $directory);
 }
示例#12
0
 public function testBuildSchema()
 {
     $import = new Doctrine_Import_Schema();
     $array = $import->buildSchema('Ticket/1617_schema.yml', 'yml');
     $this->assertEqual($array['term']['columns']['language']['name'], 'lang as language');
 }
 /**
  * Removes and returns globals from the supplied array of models.
  *
  * @param array $models An array of model definitions
  *
  * @return array An array of globals
  * 
  * @see Doctrine_Import_Schema::getGlobalDefinitionKeys()
  */
 protected function filterSchemaGlobals(&$models)
 {
     $globals = array();
     $globalKeys = Doctrine_Import_Schema::getGlobalDefinitionKeys();
     foreach ($models as $key => $value) {
         if (in_array($key, $globalKeys)) {
             $globals[$key] = $value;
             unset($models[$key]);
         }
     }
     return $globals;
 }
示例#14
0
 public function testInheritanceGeneration()
 {
     $path = dirname(__FILE__) . '/import_builder_test';
     $import = new Doctrine_Import_Schema();
     $import->setOption('generateTableClasses', true);
     $import->importSchema('schema.yml', 'yml', $path);
     $models = Doctrine_Core::loadModels($path, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);
     $schemaTestInheritanceParent = new ReflectionClass('SchemaTestInheritanceParent');
     $schemaTestInheritanceChild1 = new ReflectionClass('SchemaTestInheritanceChild1');
     $schemaTestInheritanceChild2 = new ReflectionClass('SchemaTestInheritanceChild2');
     $schemaTestInheritanceParentTable = new ReflectionClass('SchemaTestInheritanceParentTable');
     $schemaTestInheritanceChild1Table = new ReflectionClass('SchemaTestInheritanceChild1Table');
     $schemaTestInheritanceChild2Table = new ReflectionClass('SchemaTestInheritanceChild2Table');
     $this->assertTrue($schemaTestInheritanceParent->isSubClassOf('Doctrine_Record'));
     $this->assertTrue($schemaTestInheritanceParent->isSubClassOf('BaseSchemaTestInheritanceParent'));
     $this->assertTrue($schemaTestInheritanceParent->isSubClassOf('PackageSchemaTestInheritanceParent'));
     $this->assertTrue($schemaTestInheritanceChild1->isSubClassOf('BaseSchemaTestInheritanceChild1'));
     $this->assertTrue($schemaTestInheritanceChild2->isSubClassOf('BaseSchemaTestInheritanceChild2'));
     $this->assertTrue($schemaTestInheritanceChild1->isSubClassOf('SchemaTestInheritanceParent'));
     $this->assertTrue($schemaTestInheritanceChild1->isSubClassOf('BaseSchemaTestInheritanceParent'));
     $this->assertTrue($schemaTestInheritanceChild2->isSubClassOf('SchemaTestInheritanceParent'));
     $this->assertTrue($schemaTestInheritanceChild2->isSubClassOf('BaseSchemaTestInheritanceParent'));
     $this->assertTrue($schemaTestInheritanceChild2->isSubClassOf('SchemaTestInheritanceChild1'));
     $this->assertTrue($schemaTestInheritanceChild2->isSubClassOf('BaseSchemaTestInheritanceChild1'));
     $this->assertTrue($schemaTestInheritanceChild2->isSubClassOf('PackageSchemaTestInheritanceParent'));
     $this->assertTrue($schemaTestInheritanceParentTable->isSubClassOf('Doctrine_Table'));
     $this->assertTrue($schemaTestInheritanceChild1Table->isSubClassOf('SchemaTestInheritanceParentTable'));
     $this->assertTrue($schemaTestInheritanceChild1Table->isSubClassOf('PackageSchemaTestInheritanceParentTable'));
     $this->assertTrue($schemaTestInheritanceChild2Table->isSubClassOf('SchemaTestInheritanceParentTable'));
     $this->assertTrue($schemaTestInheritanceChild2Table->isSubClassOf('PackageSchemaTestInheritanceParentTable'));
     $this->assertTrue($schemaTestInheritanceChild2Table->isSubClassOf('SchemaTestInheritanceChild1Table'));
     $this->assertTrue($schemaTestInheritanceChild2Table->isSubClassOf('PackageSchemaTestInheritanceChild1Table'));
     # Simple Inheritance
     $schemaTestSimpleInheritanceParent = new ReflectionClass('SchemaTestSimpleInheritanceParent');
     $schemaTestSimpleInheritanceChild = new ReflectionClass('SchemaTestSimpleInheritanceChild');
     $this->assertTrue($schemaTestSimpleInheritanceParent->hasMethod('setTableDefinition'));
     $this->assertTrue($schemaTestSimpleInheritanceChild->isSubClassOf('SchemaTestSimpleInheritanceParent'));
     # Class Table Inheritance
     $schemaTestClassTableInheritanceParent = new ReflectionClass('SchemaTestClassTableInheritanceParent');
     $schemaTestClassTableInheritanceChild = new ReflectionClass('SchemaTestClassTableInheritanceChild');
     # Concrete Inheritance
     $schemaTestConcreteInheritanceParent = new ReflectionClass('SchemaTestConcreteInheritanceParent');
     $schemaTestConcreteInheritanceChild = new ReflectionClass('SchemaTestConcreteInheritanceChild');
     # Column Aggregation Inheritance
     $schemaTestColumnAggregationInheritanceParent = new ReflectionClass('SchemaTestColumnAggregationInheritanceParent');
     $schemaTestColumnAggregationInheritanceChild = new ReflectionClass('SchemaTestColumnAggregationInheritanceChild');
     $sql = Doctrine_Core::generateSqlFromArray(array('SchemaTestSimpleInheritanceParent', 'SchemaTestSimpleInheritanceChild'));
     $this->assertEqual(count($sql), 1);
     $this->assertEqual($sql[0], 'CREATE TABLE schema_test_simple_inheritance_parent (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255), description VARCHAR(255))');
     $sql = Doctrine_Core::generateSqlFromArray(array('SchemaTestClassTableInheritanceParent', 'SchemaTestClassTableInheritanceChild'));
     $this->assertEqual(count($sql), 2);
     $this->assertEqual($sql[0], 'CREATE TABLE schema_test_class_table_inheritance_parent (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255))');
     $this->assertEqual($sql[1], 'CREATE TABLE schema_test_class_table_inheritance_child (id INTEGER, title VARCHAR(255), description VARCHAR(255), PRIMARY KEY(id))');
     $sql = Doctrine_Core::generateSqlFromArray(array('SchemaTestConcreteInheritanceParent', 'SchemaTestConcreteInheritanceChild'));
     $this->assertEqual(count($sql), 2);
     $this->assertEqual($sql[0], 'CREATE TABLE schema_test_concrete_inheritance_parent (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255))');
     $this->assertEqual($sql[1], 'CREATE TABLE schema_test_concrete_inheritance_child (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255), title VARCHAR(255), description VARCHAR(255))');
     $sql = Doctrine_Core::generateSqlFromArray(array('SchemaTestColumnAggregationInheritanceParent', 'SchemaTestColumnAggregationInheritanceChild'));
     $this->assertEqual(count($sql), 2);
     $this->assertEqual($sql[0], 'CREATE TABLE schema_test_column_aggregation_inheritance_parent (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255), type VARCHAR(255), title VARCHAR(255), description VARCHAR(255))');
     $this->assertEqual($sql[1], 'CREATE INDEX schema_test_column_aggregation_inheritance_parent_type_idx ON schema_test_column_aggregation_inheritance_parent (type)');
     Doctrine_Lib::removeDirectories($path);
 }
示例#15
0
 /**
  * importSchema
  *
  * A method to import a Schema and translate it into a Doctrine_Record object
  *
  * @param  string $schema       The file containing the XML schema
  * @param  string $format       Format of the schema file
  * @param  string $directory    The directory where the Doctrine_Record class will be written
  * @param  array  $models       Optional array of models to import
  *
  * @return void
  */
 protected function _importSchema($schema, $format = 'yml', $directory = null, $options = array())
 {
     $schema = (array) $schema;
     $builder = new Install_Api_DoctrineBuilder();
     $builder->setTargetPath($directory);
     $builder->setOptions($options);
     $importer = new Doctrine_Import_Schema();
     $array = $importer->buildSchema($schema, $format);
     if (count($array) == 0) {
         throw new Doctrine_Import_Exception(sprintf('No ' . $format . ' schema found in ' . implode(", ", $schema)));
     }
     foreach ($array as $name => $definition) {
         $builder->buildRecord($definition);
     }
 }
    /**
     * @see sfTask
     */
    protected function execute($arguments = array(), $options = array())
    {
        $this->logSection('doctrine', 'generating model classes');
        $config = $this->getCliConfig();
        $builderOptions = $this->configuration->getPluginConfiguration('sfDoctrinePlugin')->getModelBuilderOptions();
        $stubFinder = sfFinder::type('file')->prune('base')->name('*' . $builderOptions['suffix']);
        $before = $stubFinder->in($config['models_path']);
        $schema = $this->prepareSchemaFile($config['yaml_schema_path']);
        $import = new Doctrine_Import_Schema();
        $import->setOptions($builderOptions);
        $import->importSchema($schema, 'yml', $config['models_path']);
        $listFiles = array();
        $listDir = array();
        $bI = array('package' => isset($properties['symfony']['name']) ? $properties['symfony']['name'] : 'symfony', 'subpackage' => 'model', 'author' => isset($properties['symfony']['author']) ? $properties['symfony']['author'] : 'Your name here');
        $baseRecordFile = sprintf("%s/BaseDoctrineRecord.class.php", $config['models_path']);
        $baseRecordFileContent = <<<EOF
<?php

/**
 * Base doctrin record.
 *
 * @package    {$bI['package']}
 * @subpackage {$bI['subpackage']}
 * @author     {$bI['author']}
 */


##class## BaseDoctrineRecord extends sfPostgresDoctrineRecord
{
}

EOF;
        if (!file_exists($baseRecordFile)) {
            file_put_contents($baseRecordFile, str_replace('##class##', 'class', $baseRecordFileContent));
        }
        // markup base classes with magic methods
        foreach (sfYaml::load($schema) as $model => $definition) {
            $file = sprintf('%s%s/%s/Base%s%s', $config['models_path'], isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $builderOptions['baseClassesDirectory'], $model, $builderOptions['suffix']);
            $code = file_get_contents($file);
            // introspect the model without loading the class
            if (preg_match_all('/@property (\\w+) \\$(\\w+)/', $code, $matches, PREG_SET_ORDER)) {
                $properties = array();
                foreach ($matches as $match) {
                    $properties[$match[2]] = $match[1];
                }
                $typePad = max(array_map('strlen', array_merge(array_values($properties), array($model))));
                $namePad = max(array_map('strlen', array_keys(array_map(array('sfInflector', 'camelize'), $properties))));
                $setters = array();
                $getters = array();
                foreach ($properties as $name => $type) {
                    $camelized = sfInflector::camelize($name);
                    $collection = 'Doctrine_Collection' == $type;
                    $getters[] = sprintf('@method %-' . $typePad . 's %s%-' . ($namePad + 2) . 's Returns the current record\'s "%s" %s', $type, 'get', $camelized . '()', $name, $collection ? 'collection' : 'value');
                    $setters[] = sprintf('@method %-' . $typePad . 's %s%-' . ($namePad + 2) . 's Sets the current record\'s "%s" %s', $model, 'set', $camelized . '()', $name, $collection ? 'collection' : 'value');
                }
                // use the last match as a search string
                $code = str_replace($match[0], $match[0] . PHP_EOL . ' * ' . PHP_EOL . ' * ' . implode(PHP_EOL . ' * ', array_merge($getters, $setters)), $code);
                $newfile = sprintf('%s%s%s/%s/Base%s%s', $config['models_path'], isset($definition['package']) && false !== stripos($definition['package'], 'plugin') && 0 !== stripos($definition['package'], 'plugin') ? '/plugins' : '/project', isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $builderOptions['baseClassesDirectory'], $model, $builderOptions['suffix']);
                $newtablefile = sprintf('%s%s%s/%sTable%s', $config['models_path'], isset($definition['package']) && false !== stripos($definition['package'], 'plugin') && 0 !== stripos($definition['package'], 'plugin') ? '/plugins' : '/project', isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix']);
                $newdir = sprintf('%s%s%s/%s', $config['models_path'], isset($definition['package']) && false !== stripos($definition['package'], 'plugin') && 0 !== stripos($definition['package'], 'plugin') ? '/plugins' : '/project', isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $builderOptions['baseClassesDirectory']);
                if (!file_exists($newdir)) {
                    mkdir($newdir, 0777, true);
                }
                $listDir[sprintf('%s%s/%s', $config['models_path'], isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $builderOptions['baseClassesDirectory'])] = true;
                $listDir[sprintf('%s%s', $config['models_path'], isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '')] = true;
                if (!file_exists(str_replace(sprintf('%s/Base', $builderOptions['baseClassesDirectory']), '', $newfile))) {
                    $listFiles[sprintf('%s%s/%s%s', $config['models_path'], isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix'])] = str_replace(sprintf('%s/Base', $builderOptions['baseClassesDirectory']), '', $newfile);
                } else {
                    unlink(sprintf('%s%s/%s%s', $config['models_path'], isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix']));
                }
                if (!file_exists($newtablefile)) {
                    $listFiles[sprintf('%s%s/%sTable%s', $config['models_path'], isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix'])] = $newtablefile;
                } else {
                    unlink(sprintf('%s%s/%sTable%s', $config['models_path'], isset($definition['package']) ? '/' . substr($definition['package'], 0, strpos($definition['package'], '.')) : '', $model, $builderOptions['suffix']));
                }
                $code = str_replace(" extends sfDoctrineRecord", " extends BaseDoctrineRecord", $code);
                file_put_contents($newfile, $code);
                unlink($file);
            }
        }
        $properties = parse_ini_file(sfConfig::get('sf_config_dir') . '/properties.ini', true);
        $tokens = array('##PACKAGE##' => isset($properties['symfony']['name']) ? $properties['symfony']['name'] : 'symfony', '##SUBPACKAGE##' => 'model', '##NAME##' => isset($properties['symfony']['author']) ? $properties['symfony']['author'] : 'Your name here', ' <##EMAIL##>' => '', "{\n\n}" => "{\n}\n");
        // cleanup new stub classes
        $after = $stubFinder->in($config['models_path']);
        $this->getFilesystem()->replaceTokens(array_diff($after, $before), '', '', $tokens);
        // cleanup base classes
        $baseFinder = sfFinder::type('file')->name('Base*' . $builderOptions['suffix']);
        $baseDirFinder = sfFinder::type('dir')->name('base');
        $this->getFilesystem()->replaceTokens($baseFinder->in($baseDirFinder->in($config['models_path'])), '', '', $tokens);
        // cleanup new table classes
        $tableFinder = sfFinder::type('file')->prune('base')->name('*Table' . $builderOptions['suffix']);
        foreach (array_diff($tableFinder->in($config['models_path']), $before) as $file) {
            $contents = file_get_contents($file);
            file_put_contents($file, sfToolkit::stripComments($contents));
        }
        foreach ($listFiles as $old => $new) {
            rename($old, $new);
        }
        foreach ($listDir as $dir => $val) {
            if (file_exists($dir)) {
                if (($files = @scandir($dir)) && count($files) <= 2) {
                    rmdir($dir);
                }
            }
        }
        $this->reloadAutoload();
    }