public function testClassifyTableize() { $name = "Forum_Category"; $this->assertEqual(Doctrine_Inflector::tableize($name), "forum__category"); $this->assertEqual(Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)), $name); }
/** * Set a record attribute. Allows overriding Doctrine record accessors with Propel style functions * * @param string $name * @param string $value * @param string $load * @return void */ public function set($name, $value, $load = true) { $setter = 'set' . Doctrine_Inflector::classify($name); if (method_exists($this, $setter)) { return $this->{$setter}($value, $load); } return parent::set($name, $value, $load); }
public static function getShortPluginName($name) { // Special shortening for non sympal plugins if (substr($name, 0, 2) == 'sf' && !strstr($name, 'sfSympal')) { return $name; } if (strstr($name, 'sfSympal')) { return substr($name, 8, strlen($name) - 14); } else { return Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)); } }
protected function execute($arguments = array(), $options = array()) { $databaseManager = new sfDatabaseManager($this->configuration); $tmpdir = sfConfig::get('sf_cache_dir') . '/models_tmp'; $ymlTmp = $tmpdir . '/yaml'; $modelTmp = $tmpdir . '/model'; $this->getFileSystem()->mkdirs($ymlTmp); $this->getFileSystem()->mkdirs($modelTmp); $migrationsPath = sfConfig::get('sf_data_dir') . '/migrations/generated'; $config = $this->getCliConfig(); $manager = Doctrine_Manager::getInstance(); $oldAttr = $manager->getAttribute(Doctrine::ATTR_MODEL_LOADING); $manager->setAttribute(Doctrine::ATTR_MODEL_LOADING, Doctrine::MODEL_LOADING_AGGRESSIVE); sfSimpleAutoload::unregister(); Doctrine::generateYamlFromDb($ymlTmp . '/from.yml', array(), array('generateBaseClasses' => false)); sfSimpleAutoload::register(); $manager->setAttribute(Doctrine::ATTR_MODEL_LOADING, $oldAttr); $models = sfFinder::type('file')->name('*.php')->in($config['models_path']); foreach ($models as $model) { $dirname = basename(dirname($model)); $filename = basename($model); if ('base' !== $dirname) { continue; } $normalModelName = str_replace('Base', '', basename($model, '.class.php')); $normalModelRefClass = new ReflectionClass($normalModelName); if ($normalModelRefClass && $normalModelRefClass->isAbstract()) { continue; } $content = file_get_contents($model); $content = str_replace('abstract class Base', 'class ToPrfx', $content); $content = str_replace('extends opDoctrineRecord', 'extends Doctrine_Record', $content); $matches = array(); if (preg_match('/\\$this->setTableName\\(\'([^\']+)\'\\);/', $content, $matches)) { $tableName = $matches[1]; $content = preg_replace('/class [a-zA-Z0-9_]+/', 'class ToPrfx' . Doctrine_Inflector::classify($tableName), $content); file_put_contents($modelTmp . '/ToPrfx' . Doctrine_Inflector::classify($tableName) . '.class.php', $content); } else { file_put_contents($modelTmp . '/' . str_replace('Base', 'ToPrfx', $filename), $content); } } $migration = new Doctrine_Migration($migrationsPath); $diff = new opMigrationDiff($ymlTmp . '/from.yml', $modelTmp, $migration); $changes = $diff->generateMigrationClasses(); $this->getFileSystem()->remove($ymlTmp); $this->getFileSystem()->remove($modelTmp); $numChanges = count($changes, true) - count($changes); if (!$numChanges) { throw new Doctrine_Task_Exception('Could not generate migration classes from difference'); } else { $this->dispatcher->notify(new sfEvent($this, 'command.log', array($this->formatter->formatSection('doctrine', 'Generated migration classes successfully from difference')))); } }
public function setTableDefinition() { $relations = $this->_options['relations']; foreach ($relations as $relation) { $this->_table->setColumn(self::getColumnName($relation, $this->_options['column_suffix']), 'varchar', 255, array('type' => 'varchar', 'length' => 255)); } $format = Doctrine_Inflector::classify($this->_options['serialization_format']); $listerner = "Doctrine_Template_Listener_{$format}Serializable"; if (!class_exists($listerner)) { throw new Expection("The behavior '{$listerner}' does not exist."); } $this->addListener(new $listerner($this->_options)); }
/** * Deserializes relationship(s) * * @param Doctrine_Event $event * @return void */ public function postHydrate(Doctrine_Event $event) { $data = $event->data; $relations = $this->_options['relations']; foreach ($relations as $relation) { $column = Doctrine_Template_Serializable::getColumnName($relation, $this->_options['column_suffix']); $filter = $data[$column]; $model = Doctrine_Inflector::classify($relation['table']); if (!isset($relation['table_method'])) { $query = Doctrine_Core::getTable($model)->createQuery(); if (isset($relation['order_by'])) { $order = $relation['order_by']; $query->addOrderBy($order[0] . ' ' . $order[1]); } $query->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY); $objects = $query->execute(); } else { $tableMethod = $relation['table_method']; $results = Doctrine_Core::getTable($model)->{$tableMethod}(); if ($results instanceof Doctrine_Query) { $objects = $results->execute(); } else { if ($results instanceof Doctrine_Collection) { $objects = $results; } else { if ($results instanceof Doctrine_Record) { $objects = new Doctrine_Collection($model); $objects[] = $results; } else { $objects = array(); } } } } // replace value of column $data[$column] = $this->normalize($objects, $filter); } $event->data = $data; }
/** * doMigrate * * Perform migration for a migration class. Executes the up or down method then processes the changes * * @param string $direction * @return void */ protected function doMigrate($direction) { $method = 'pre' . $direction; $this->{$method}(); if (method_exists($this, $direction)) { $this->{$direction}(); foreach ($this->_changes as $type => $changes) { $process = new Doctrine_Migration_Process(); $funcName = 'process' . Doctrine_Inflector::classify($type); if (!empty($changes)) { $process->{$funcName}($changes); } } } $method = 'post' . $direction; $this->{$method}(); }
/** * buildRelationships * * Loop through an array of schema information and build all the necessary relationship information * Will attempt to auto complete relationships and simplify the amount of information required * for defining a relationship * * @param string $array * @return void */ protected function _buildRelationships($array) { // Handle auto detecting relations by the names of columns // User.contact_id will automatically create User hasOne Contact local => contact_id, foreign => id foreach ($array as $className => $properties) { if (isset($properties['columns']) && !empty($properties['columns']) && isset($properties['detect_relations']) && $properties['detect_relations']) { foreach ($properties['columns'] as $column) { // Check if the column we are inflecting has a _id on the end of it before trying to inflect it and find // the class name for the column if (strpos($column['name'], '_id')) { $columnClassName = Doctrine_Inflector::classify(str_replace('_id', '', $column['name'])); if (isset($array[$columnClassName]) && !isset($array[$className]['relations'][$columnClassName])) { $array[$className]['relations'][$columnClassName] = array(); // Set the detected foreign key type and length to the same as the primary key // of the related table $type = isset($array[$columnClassName]['columns']['id']['type']) ? $array[$columnClassName]['columns']['id']['type'] : 'integer'; $length = isset($array[$columnClassName]['columns']['id']['length']) ? $array[$columnClassName]['columns']['id']['length'] : 8; $array[$className]['columns'][$column['name']]['type'] = $type; $array[$className]['columns'][$column['name']]['length'] = $length; } } } } } foreach ($array as $name => $properties) { if (!isset($properties['relations'])) { continue; } $className = $properties['className']; $relations = $properties['relations']; foreach ($relations as $alias => $relation) { $class = isset($relation['class']) ? $relation['class'] : $alias; if (!isset($array[$class])) { continue; } $relation['class'] = $class; $relation['alias'] = isset($relation['alias']) ? $relation['alias'] : $alias; // Attempt to guess the local and foreign if (isset($relation['refClass'])) { $relation['local'] = isset($relation['local']) ? $relation['local'] : Doctrine_Inflector::tableize($name) . '_id'; $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign'] : Doctrine_Inflector::tableize($class) . '_id'; } else { $relation['local'] = isset($relation['local']) ? $relation['local'] : Doctrine_Inflector::tableize($relation['class']) . '_id'; $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign'] : 'id'; } if (isset($relation['refClass'])) { $relation['type'] = 'many'; } if (isset($relation['type']) && $relation['type']) { $relation['type'] = $relation['type'] === 'one' ? Doctrine_Relation::ONE : Doctrine_Relation::MANY; } else { $relation['type'] = Doctrine_Relation::ONE; } if (isset($relation['foreignType']) && $relation['foreignType']) { $relation['foreignType'] = $relation['foreignType'] === 'one' ? Doctrine_Relation::ONE : Doctrine_Relation::MANY; } $relation['key'] = $this->_buildUniqueRelationKey($relation); $this->_validateSchemaElement('relation', array_keys($relation), $className . '->relation->' . $relation['alias']); $this->_relations[$className][$alias] = $relation; } } // Now we auto-complete opposite ends of relationships $this->_autoCompleteOppositeRelations(); // Make sure we do not have any duplicate relations $this->_fixDuplicateRelations(); // Set the full array of relationships for each class to the final array foreach ($this->_relations as $className => $relations) { $array[$className]['relations'] = $relations; } return $array; }
/** * Process a row and make all the appropriate relations between the imported data * * @param string $rowKey * @param string $row * @return void */ protected function _processRow($rowKey, $row) { $obj = $this->_importedObjects[$rowKey]; foreach ((array) $row as $key => $value) { if (method_exists($obj, 'set' . Doctrine_Inflector::classify($key))) { $func = 'set' . Doctrine_Inflector::classify($key); $obj->{$func}($value); } else { if ($obj->getTable()->hasField($key)) { if ($obj->getTable()->getTypeOf($key) == 'object') { $value = unserialize($value); } $obj->set($key, $value); } else { if ($obj->getTable()->hasRelation($key)) { if (is_array($value)) { if (isset($value[0]) && !is_array($value[0])) { foreach ($value as $link) { if ($obj->getTable()->getRelation($key)->getType() === Doctrine_Relation::ONE) { $obj->set($key, $this->_getImportedObject($link, $obj, $key, $rowKey)); } else { if ($obj->getTable()->getRelation($key)->getType() === Doctrine_Relation::MANY) { $relation = $obj->{$key}; $relation[] = $this->_getImportedObject($link, $obj, $key, $rowKey); } } } } else { $obj->{$key}->fromArray($value); } } else { $obj->set($key, $this->_getImportedObject($value, $obj, $key, $rowKey)); } } else { try { $obj->{$key} = $value; } catch (Exception $e) { // used for Doctrine plugin methods (Doctrine_Template) if (is_callable(array($obj, 'set' . Doctrine_Inflector::classify($key)))) { $func = 'set' . Doctrine_Inflector::classify($key); $obj->{$func}($value); } else { throw new Doctrine_Data_Exception('Invalid fixture element "' . $key . '" under "' . $rowKey . '"'); } } } } } } }
/** * generateMigrationClass * * @return void */ public function generateMigrationClass($className, $options = array(), $up = null, $down = null, $return = false) { $className = Doctrine_Inflector::urlize($className); $className = str_replace('-', '_', $className); $className = Doctrine_Inflector::classify($className); if ($return || !$this->getMigrationsPath()) { return $this->buildMigrationClass($className, null, $options, $up, $down); } else { if (!$this->getMigrationsPath()) { throw new Doctrine_Migration_Exception('You must specify the path to your migrations.'); } $next = (string) $this->migration->getNextVersion(); $fileName = str_repeat('0', 3 - strlen($next)) . $next . '_' . Doctrine_Inflector::tableize($className) . $this->suffix; $class = $this->buildMigrationClass($className, $fileName, $options, $up, $down); $path = $this->getMigrationsPath() . DIRECTORY_SEPARATOR . $fileName; if (class_exists($className) || file_exists($path)) { return false; } file_put_contents($path, $class); return true; } }
/** * set * method for altering properties and Doctrine_Record references * if the load parameter is set to false this method will not try to load uninitialized record data * * @param mixed $name name of the property or reference * @param mixed $value value of the property or reference * @param boolean $load whether or not to refresh / load the uninitialized record data * * @throws Doctrine_Record_Exception if trying to set a value for unknown property / related component * @throws Doctrine_Record_Exception if trying to set a value of wrong type for related component * * @return Doctrine_Record */ public function set($fieldName, $value, $load = true) { if ($this->_table->getAttribute(Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE)) { $componentName = $this->_table->getComponentName(); $mutator = isset(self::$_customMutators[$componentName][$fieldName]) ? self::$_customMutators[$componentName][$fieldName] : 'set' . Doctrine_Inflector::classify($fieldName); if (isset(self::$_customMutators[$componentName][$fieldName]) || method_exists($this, $mutator)) { self::$_customMutators[$componentName][$fieldName] = $mutator; return $this->{$mutator}($value, $load); } } return $this->_set($fieldName, $value, $load); }
/** * Old method retained for backwards compatibility * * @deprecated */ protected function _getTaskClassFromArgs(array $args) { return self::TASK_BASE_CLASS . '_' . Doctrine_Inflector::classify(str_replace('-', '_', $args[1])); }
/** * importSchema * * method for importing existing schema to Doctrine_Record classes * * @param string $directory * @param array $databases * @return array the names of the imported classes */ public function importSchema($directory, array $databases = array(), array $options = array()) { $options['singularize'] = !isset($options['singularize']) ? $this->conn->getAttribute('singularize_import') : $options['singularize']; $connections = Doctrine_Manager::getInstance()->getConnections(); foreach ($connections as $name => $connection) { // Limit the databases to the ones specified by $databases. // Check only happens if array is not empty if (!empty($databases) && !in_array($name, $databases)) { continue; } $builder = new Doctrine_Import_Builder(); $builder->setTargetPath($directory); $builder->setOptions($options); $classes = array(); foreach ($connection->import->listTables() as $table) { $definition = array(); $definition['tableName'] = $table; // echo $table . "<br />\n"; if (!isset($options['singularize']) || $options['singularize'] !== false) { $e = explode('_', Doctrine_Inflector::tableize($table)); foreach ($e as $k => $v) { $e[$k] = Doctrine_Inflector::singularize($v); } $classTable = implode('_', $e); } else { $classTable = Doctrine_Inflector::tableize($table); } $definition['className'] = Doctrine_Inflector::classify($classTable); $definition['columns'] = $connection->import->listTableColumns($table); //var_dump ($definition); $builder->buildRecord($definition); $classes[] = $definition['className']; } } return $classes; }
protected function getIssueFieldName($field) { return Doctrine_Inflector::classify(str_replace('_id', '', $field)); }
/** * Process a row and make all the appropriate relations between the imported data * * @param string $rowKey * @param string $row * @return void */ protected function _processRow($rowKey, $row) { $obj = $this->_importedObjects[$rowKey]; foreach ((array) $row as $key => $value) { // The condition below causes a setter method on a field to be called always, no matter // if it is really a mutator. I find this behaviour inconsistent/buggy. A corrected version // of condition and code below closely resembles that of set() of Doctrine_Record. // -- Jakub Argasiński (argasek@gmail.com): // // if (method_exists($obj, 'set' . Doctrine_Inflector::classify($key))) { // $func = 'set' . Doctrine_Inflector::classify($key); // $obj->$func($value); if ($obj->getTable()->getAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE) || $obj->hasMutator($key)) { $mutator = $obj->hasMutator($key) ? $obj->getMutator($key) : 'set' . Doctrine_Inflector::classify($key); if ($obj->hasMutator($key) || method_exists($this, $key)) { $obj->hasMutator($key, $mutator); return $obj->$mutator($value); } } else if ($obj->getTable()->hasField($key)) { if ($obj->getTable()->getTypeOf($key) == 'object') { $value = unserialize($value); } $obj->set($key, $value); } else if ($obj->getTable()->hasRelation($key)) { if (is_array($value)) { if (isset($value[0]) && ! is_array($value[0])) { foreach ($value as $link) { if ($obj->getTable()->getRelation($key)->getType() === Doctrine_Relation::ONE) { $obj->set($key, $this->_getImportedObject($link, $obj, $key, $rowKey)); } else if ($obj->getTable()->getRelation($key)->getType() === Doctrine_Relation::MANY) { $relation = $obj->$key; $relation[] = $this->_getImportedObject($link, $obj, $key, $rowKey); } } } else { $obj->$key->fromArray($value); } } else { $obj->set($key, $this->_getImportedObject($value, $obj, $key, $rowKey)); } } else { try { $obj->$key = $value; } catch (Exception $e) { // used for Doctrine plugin methods (Doctrine_Template) if (is_callable(array($obj, 'set' . Doctrine_Inflector::classify($key)))) { $func = 'set' . Doctrine_Inflector::classify($key); $obj->$func($value); } else { throw new Doctrine_Data_Exception('Invalid fixture element "'. $key . '" under "' . $rowKey . '"'); } } } } }
/** * importSchema * * method for importing existing schema to Doctrine_Record classes * * @param string $directory * @param array $connections Array of connection names to generate models for * @return array the names of the imported classes */ public function importSchema($directory, array $connections = array(), array $options = array()) { $classes = array(); $manager = Doctrine_Manager::getInstance(); foreach ($manager as $name => $connection) { // Limit the databases to the ones specified by $connections. // Check only happens if array is not empty if (!empty($connections) && !in_array($name, $connections)) { continue; } $builder = new Doctrine_Import_Builder(); $builder->setTargetPath($directory); $builder->setOptions($options); $definitions = array(); foreach ($connection->import->listTables() as $table) { $definition = array(); $definition['tableName'] = $table; $definition['className'] = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); $definition['columns'] = $connection->import->listTableColumns($table); $definition['connection'] = $connection->getName(); $definition['connectionClassName'] = $definition['className']; try { $definition['relations'] = array(); $relations = $connection->import->listTableRelations($table); $relClasses = array(); foreach ($relations as $relation) { $table = $relation['table']; $class = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); if (in_array($class, $relClasses)) { $alias = $class . '_' . (count($relClasses) + 1); } else { $alias = $class; } $relClasses[] = $class; $definition['relations'][$alias] = array('alias' => $alias, 'class' => $class, 'local' => $relation['local'], 'foreign' => $relation['foreign']); } } catch (Exception $e) { } $definitions[strtolower($definition['className'])] = $definition; $classes[] = $definition['className']; } // Build opposite end of relationships foreach ($definitions as $definition) { $className = $definition['className']; $relClasses = array(); foreach ($definition['relations'] as $alias => $relation) { if (in_array($relation['class'], $relClasses) || isset($definitions[$relation['class']]['relations'][$className])) { $alias = $className . '_' . (count($relClasses) + 1); } else { $alias = $className; } $relClasses[] = $relation['class']; $definitions[strtolower($relation['class'])]['relations'][$alias] = array('type' => Doctrine_Relation::MANY, 'alias' => $alias, 'class' => $className, 'local' => $relation['foreign'], 'foreign' => $relation['local']); } } // Build records foreach ($definitions as $definition) { $builder->buildRecord($definition); } } return $classes; }
public function buildAccessors(array $definition) { $accessors = array(); foreach (array_keys($definition['columns']) as $name) { $accessors[] = $name; } foreach ($definition['relations'] as $relation) { $accessors[] = $relation['alias']; } $ret = ''; foreach ($accessors as $name) { // getters $ret .= PHP_EOL . ' public function get' . Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)) . "(\$load = true)" . PHP_EOL; $ret .= " {" . PHP_EOL; $ret .= " return \$this->get('{$name}', \$load);" . PHP_EOL; $ret .= " }" . PHP_EOL; // setters $ret .= PHP_EOL . ' public function set' . Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)) . "(\${$name}, \$load = true)" . PHP_EOL; $ret .= " {" . PHP_EOL; $ret .= " return \$this->set('{$name}', \${$name}, \$load);" . PHP_EOL; $ret .= " }" . PHP_EOL; } return $ret; }
/** * classify * * returns class name from table name * * @param string $tablename * @return string */ public static function classify($tableName) { return Doctrine_Inflector::classify($tableName); }
/** * setOption * * @param string $key * @param string $value * @return void */ public function setOption($key, $value) { $name = 'set' . Doctrine_Inflector::classify($key); if (method_exists($this, $name)) { $this->{$name}($value); } else { $key = '_' . $key; $this->{$key} = $value; } }
protected function execute($arguments = array(), $options = array()) { $name = $arguments['name']; $pluginName = 'sfSympal' . Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)) . 'Plugin'; $path = sfConfig::get('sf_plugins_dir') . '/' . $pluginName; if (!$options['no-confirmation'] && !$this->askConfirmation(array('This command will create a new plugin named ' . $pluginName, 'Are you sure you want to proceed? (y/N)'), 'QUESTION_LARGE', false)) { $this->logSection('sympal', 'Plugin creation aborted'); return 1; } if (is_dir($path)) { if (isset($options['re-generate']) && $options['re-generate']) { $uninstall = new sfSympalPluginUninstallTask($this->dispatcher, $this->formatter); $uninstall->setCommandApplication($this->commandApplication); $uninstallOptions = array(); $uninstallOptions[] = '--delete'; $uninstallOptions[] = '--no-confirmation'; $ret = $uninstall->run(array($name), $uninstallOptions); } else { throw new sfException('A plugin with the name ' . $pluginName . ' already exists!'); } } if (is_dir($path)) { Doctrine_Lib::removeDirectories($path); } $generatePlugin = new sfGeneratePluginTask($this->dispatcher, $this->formatter); $generatePlugin->setCommandApplication($this->commandApplication); $generatePluginOptions = array(); if (isset($options['module']) && !empty($options['module'])) { $generatePluginOptions[] = '--module=' . implode(' --module=', $options['module']); } if (isset($options['test-application'])) { $generatePluginOptions[] = '--test-application=' . $options['test-application']; } if (isset($options['skip-test-dir'])) { $generatePluginOptions[] = '--skip-test-dir'; } $generatePlugin->run(array($pluginName), $generatePluginOptions); $contentType = isset($options['content-type']) ? $options['content-type'] : null; $lowerName = str_replace('-', '_', Doctrine_Inflector::urlize($name)); if ($contentType) { $pluginYamlSchema = <<<EOF --- {$contentType}: actAs: [sfSympalContentTypeTemplate] columns: title: string(255) body: clob EOF; $pluginInstallDataFixtures = <<<EOF # {$pluginName} install data fixtures EOF; } $itemsToCreate = array('config' => null, 'config/doctrine' => null, 'config/routing.yml' => '# ' . $pluginName . ' routing', 'data' => null); if (isset($pluginInstallDataFixtures)) { $itemsToCreate['data/fixtures'] = null; $itemsToCreate['data/fixtures/install.yml'] = $pluginInstallDataFixtures; } if (isset($pluginYamlSchema)) { $itemsToCreate['config/doctrine/schema.yml'] = $pluginYamlSchema; } if (isset($options['theme'])) { $itemsToCreate['config/app.yml'] = sprintf('all: sympal_config: themes: %s: layout: %s stylesheets: - %s', $options['theme'], $options['theme'], '/' . $pluginName . '/css/' . $options['theme'] . '.css'); $itemsToCreate['templates/' . $options['theme'] . '.php'] = file_get_contents($this->configuration->getPluginConfiguration('sfSympalPlugin')->getRootDir() . '/templates/default.php'); $itemsToCreate['web/css/' . $options['theme'] . '.css'] = file_get_contents($this->configuration->getPluginConfiguration('sfSympalPlugin')->getRootDir() . '/web/css/default.css'); } foreach ($itemsToCreate as $item => $value) { $itemPath = $path . '/' . $item; if (!is_null($value)) { $dir = dirname($itemPath); $this->getFilesystem()->mkdirs($dir); file_put_contents($itemPath, $value); } else { $this->getFilesystem()->mkdirs($itemPath); } } if (isset($options['install']) && $options['install']) { $install = new sfSympalPluginInstallTask($this->dispatcher, $this->formatter); $install->setCommandApplication($this->commandApplication); $installOptions = array(); if (isset($options['content-type'])) { $installOptions[] = '--content-type=' . $options['content-type']; } $ret = $install->run(array($name), $installOptions); } $cc = new sfCacheClearTask($this->dispatcher, $this->formatter); $ret = $cc->run(array(), array()); }
protected function getPropertyName($fieldname) { return ckString::lcfirst(Doctrine_Inflector::classify($fieldname)); }
/** * imports data from a php array * * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models * @param string $array array of data, see link for documentation * @param bool $deep whether or not to act on relations * @return void */ public function fromArray(array $array, $deep = true) { $refresh = false; foreach ($array as $key => $value) { if ($key == '_identifier') { $refresh = true; $this->assignIdentifier($value); continue; } if ($deep && $this->getTable()->hasRelation($key)) { if (!$this->{$key}) { $this->refreshRelated($key); } if (is_array($value)) { if (isset($value[0]) && !is_array($value[0])) { $this->unlink($key, array(), false); $this->link($key, $value, false); } else { $this->{$key}->fromArray($value, $deep); } } } else { if ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) { $this->set($key, $value); } else { $method = 'set' . Doctrine_Inflector::classify($key); try { if (is_callable(array($this, $method))) { $this->{$method}($value); } } catch (Doctrine_Record_Exception $e) { } } } } if ($refresh) { $this->refresh(); } }
public function buildPhpDocs(array $definition) { $ret = array(); $ret[] = $definition['className']; $ret[] = ''; $ret[] = 'This class has been auto-generated by the Doctrine ORM Framework'; $ret[] = ''; $properties = array(); $getters = array(); $setters = array(); if (isset($definition['is_base_class']) && $definition['is_base_class'] || !$this->generateBaseClasses()) { foreach ($definition['columns'] as $name => $column) { $name = isset($column['name']) ? $column['name'] : $name; // extract column name & field name if (stripos($name, ' as ')) { if (strpos($name, ' as')) { $parts = explode(' as ', $name); } else { $parts = explode(' AS ', $name); } if (count($parts) > 1) { $fieldName = $parts[1]; } else { $fieldName = $parts[0]; } $name = $parts[0]; } else { $fieldName = $name; $name = $name; } $phpTypeMap = array("enum" => "string", "datetime" => "string", "timestamp" => "string", "clob" => "string", "date" => "string", "time" => "string", "varchar" => "string", "char" => "string", "decimal" => "float", "blob" => "object", "gzip" => "object", "bit" => "binary", "varbit" => "binary", "inet" => "string", "boolean" => "bool", "integer" => "int", "string" => "string"); /** * @var double $phpCommentMap; */ $phpCommentMap = array("time" => "Time in ISO-8601 format (HH:MI:SS)", "date" => "Date in ISO-8601 format (YYYY-MM-DD)", "datetime" => "Date and time in ISO-8601 format (YYYY-MM-DD HH:MI)", "timestamp" => "Timestamp in ISO-8601 format (YYYY-MM-DD HH:MI:SS)", "gzip" => "A gzipped object", "object" => "A doctrine serialized object", "enum" => "Possible values (%s)"); $phpType = $column["type"]; if (isset($phpTypeMap[$column["type"]])) { $phpType = $phpTypeMap[$column["type"]]; } $commentOptions = array(); if (isset($column["length"]) && $column["length"] != null) { if (isset($column["fixed"]) && $column["fixed"] == true) { $commentOptions[] = sprintf("Type: %s(%s) fixed-size", $column["type"], $column["length"]); } else { $commentOptions[] = sprintf("Type: %s(%s)", $column["type"], $column["length"]); } } else { $commentOptions[] = sprintf("Type: %s", $column["type"]); } if (isset($column["unique"]) && $column["unique"] == true) { $commentOptions[] = sprintf("unique"); } if (isset($column["primary"]) && $column["primary"] == true) { $commentOptions[] = sprintf("primary key"); } if (isset($column["notblank"]) && $column["notblank"] == true) { $commentOptions[] = "required"; } if (isset($column["default"]) && $column["default"] != null) { $commentOptions[] = sprintf('default "%s"', $column["default"]); } if (isset($phpCommentMap[$column["type"]])) { $comment = $phpCommentMap[$column["type"]]; if ($column['type'] == "enum") { $comment = sprintf($comment, strtoupper(join(", ", $column["values"]))); } $commentOptions[] = $comment; } $comment = join(", ", $commentOptions); $fieldName = trim($fieldName); $properties[] = array($phpType, $fieldName, $comment); $getters[] = array($phpType, Doctrine_Inflector::classify($fieldName), $comment); $setters[] = array($definition['topLevelClassName'], Doctrine_Inflector::classify($fieldName), $phpType, $comment); } if (isset($definition['relations']) && !empty($definition['relations'])) { foreach ($definition['relations'] as $relation) { $type = isset($relation['type']) && $relation['type'] == Doctrine_Relation::MANY ? 'Doctrine_Collection' : $this->_classPrefix . $relation['class']; if ($relation["type"] == Doctrine_Relation::ONE) { $properties[] = array($relation['class'], $relation['alias'], ""); $getters[] = array($relation['class'], $relation['alias'], ""); $setters[] = array($definition['topLevelClassName'], $relation['alias'], $relation['class'], ""); } else { // MANY $properties[] = array($type . "|" . $relation['class'] . "[]", $relation['alias'], ""); $getters[] = array($type . "|" . $relation['class'] . "[]", $relation['alias'], ""); $setters[] = array($definition['topLevelClassName'], $relation["alias"], $type, ""); } } } $maxTypeSize = 0; $maxNameSize = 0; foreach ($properties as $propItem) { $maxTypeSize = max($maxTypeSize, strlen($propItem[0])); $maxNameSize = max($maxNameSize, strlen($propItem[1]) + 1); } foreach ($getters as $getterItem) { $maxTypeSize = max($maxTypeSize, strlen($getterItem[0])); $maxNameSize = max($maxNameSize, strlen($getterItem[1]) + 5); } foreach ($setters as $setterItem) { $maxTypeSize = max($maxTypeSize, strlen($setterItem[0])); $maxNameSize = max($maxNameSize, strlen($setterItem[1]) + strlen($setterItem[2]) + 9); } $maxNameSize += 1; $maxTypeSize += 1; foreach ($properties as $propItem) { $ret[] = sprintf("@property %s \$%s %s", str_pad($propItem[0], $maxTypeSize, " "), str_pad($propItem[1], $maxNameSize - 1, " "), $propItem[2]); } $ret[] = " "; foreach ($getters as $getterItem) { $methodName = sprintf("get%s()", ucfirst($getterItem[1])); $ret[] = sprintf("@method %s %s %s", str_pad($getterItem[0], $maxTypeSize + 2, " "), str_pad($methodName, $maxNameSize, " "), $getterItem[2]); } $ret[] = " "; foreach ($setters as $setterItem) { $methodName = sprintf('set%s(%s $val)', ucfirst($setterItem[1]), $setterItem[2]); $ret[] = sprintf("@method %s %s %s", str_pad($setterItem[0], $maxTypeSize + 2, " "), str_pad($methodName, $maxNameSize, " "), $setterItem[3]); } //$ret = array_merge($ret, $getter, $setter); } $ret[] = " "; $ret[] = '@package ' . $this->_phpDocPackage; $ret[] = '@subpackage ' . $this->_phpDocSubpackage; $ret[] = '@author ' . $this->_phpDocName . ' <' . $this->_phpDocEmail . '>'; $ret[] = '@version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $'; $ret = ' * ' . implode(PHP_EOL . ' * ', $ret); $ret = ' ' . trim($ret); return $ret; }
/** * Prints an index of all the available tasks in the CLI instance * * @return void */ public function printTasks($task = null, $full = false) { $task = Doctrine_Inflector::classify(str_replace('-', '_', $task)); $tasks = $this->getLoadedTasks(); echo $this->_formatter->format("Doctrine Command Line Interface", 'HEADER') . "\n\n"; foreach ($tasks as $taskName) { if ($task != null && strtolower($task) != strtolower($taskName)) { continue; } $className = 'Doctrine_Task_' . $taskName; $taskInstance = new $className(); $taskInstance->taskName = str_replace('_', '-', Doctrine_Inflector::tableize($taskName)); $syntax = $this->_scriptName . ' ' . $taskInstance->getTaskName(); echo $this->_formatter->format($syntax, 'INFO'); if ($full) { echo " - " . $taskInstance->getDescription() . "\n"; $args = null; $requiredArguments = $taskInstance->getRequiredArgumentsDescriptions(); if (!empty($requiredArguments)) { foreach ($requiredArguments as $name => $description) { $args .= $this->_formatter->format($name, "ERROR"); if (isset($this->_config[$name])) { $args .= " - " . $this->_formatter->format($this->_config[$name], 'COMMENT'); } else { $args .= " - " . $description; } $args .= "\n"; } } $optionalArguments = $taskInstance->getOptionalArgumentsDescriptions(); if (!empty($optionalArguments)) { foreach ($optionalArguments as $name => $description) { $args .= $name . ' - ' . $description . "\n"; } } if ($args) { echo "\n" . $this->_formatter->format('Arguments:', 'HEADER') . "\n" . $args; } } echo "\n"; } }
/** * Returns the absolute file path * * @param string $field * @return string * @todo remove sfConfig dependency ? * @todo remove Doctrine_Inflector dependency ? */ protected function getFilePath($field) { $object = $this->getInvoker(); if (null === ($path_method = $this->getOption('path_method', $field))) { return sfConfig::get('sf_upload_dir') . '/' . $this->getInvoker()->get($field); } $method = sprintf($path_method, Doctrine_Inflector::classify($field)); if (!method_exists($object, $method)) { throw new sfException(sprintf('Object of class "%s" does not implement a "%s()" method', get_class($object), $method)); } return $object->{$method}(); }
/** * Perform a single migration step. Executes a single migration class and * processes the changes * * @param string $direction Direction to go, 'up' or 'down' * @param integer $num * @return void */ protected function _doMigrateStep($direction, $num) { try { $migration = $this->getMigrationClass($num); $method = 'pre' . $direction; $migration->$method(); if (method_exists($migration, $direction)) { $migration->$direction(); } else if (method_exists($migration, 'migrate')) { $migration->migrate($direction); } if ($migration->getNumChanges() > 0) { $changes = $migration->getChanges(); if ($direction == 'down' && method_exists($migration, 'migrate')) { $changes = array_reverse($changes); } foreach ($changes as $value) { list($type, $change) = $value; $funcName = 'process' . Doctrine_Inflector::classify($type); if (method_exists($this->_process, $funcName)) { try { $this->_process->$funcName($change); } catch (Exception $e) { $this->addError($e); } } else { throw new Doctrine_Migration_Exception(sprintf('Invalid migration change type: %s', $type)); } } } $method = 'post' . $direction; $migration->$method(); } catch (Exception $e) { $this->addError($e); } }
public function buildFindByWhere($fieldName) { // Get all variations of possible field names $fields = array_merge($this->getFieldNames(), $this->getColumnNames()); $classifyFields = array(); foreach ($fields as $k => $v) { $classifyFields[$k] = Doctrine_Inflector::classify($v); } $fields = array_merge($fields, $classifyFields); $ucfirstFields = array(); foreach ($fields as $k => $v) { $ucfirstFields[$k] = ucfirst($v); } $fields = array_merge($fields, $ucfirstFields); // Sort field names by length - smallest first // and then reverse so that largest is first usort($fields, array($this, 'isGreaterThan')); $fields = array_reverse(array_unique($fields)); // Identify fields and operators preg_match_all('/(' . implode('|', $fields) . ')(Or|And)?/', $fieldName, $matches); $fieldsFound = $matches[1]; $operatorFound = $matches[2]; foreach ($operatorFound as &$v) { $v = strtoupper($v); } // Check if $fieldName has unidentified parts left if (strlen(implode('', $fieldsFound) . implode('', $operatorFound)) !== strlen($fieldName)) { $expression = preg_replace('/(' . implode('|', $fields) . ')(Or|And)?/', '($1)$2', $fieldName); throw new Doctrine_Table_Exception('Invalid expression found: ' . $expression); } // Build result $where = $lastOperator = ''; $bracketOpen = false; foreach ($fieldsFound as $index => $field) { $field = $this->_resolveFindByFieldName($field); if (!$field) { throw new Doctrine_Table_Exception('Invalid field name to find by: ' . $field); } if ($operatorFound[$index] == 'OR' && !$bracketOpen) { $where .= '('; $bracketOpen = true; } $where .= 'dctrn_find.' . $field . ' = ?'; if ($operatorFound[$index] != 'OR' && $lastOperator == 'OR') { $where .= ')'; $bracketOpen = false; } $where .= ' ' . strtoupper($operatorFound[$index]) . ' '; $lastOperator = $operatorFound[$index]; } return trim($where); }
public function getPluralUpper() { return Doctrine_Inflector::classify(Doctrine_Core::getTable($this->getName())->getTableName()) . 's'; }
public function testTest() { $this->assertEqual(Doctrine_Inflector::classify('test_do$llar_sign'), 'TestDollarSign'); }