示例#1
0
 /**
  * Throws an exception if the record is modified while it is 
  * locked. 
  * 
  * @param Doctrine_Event $event 
  * @return void
  */
 public function preSave(Doctrine_Event $event)
 {
     $modelName = Doctrine_Inflector::tableize(get_class($event->getInvoker()));
     $modifiedFields = $event->getInvoker()->getModified();
     $locked = $event->getInvoker()->isLocked;
     $lockModified = array_key_exists('isLocked', $modifiedFields);
     $numModified = count($modifiedFields);
     /**
      * Record fields haven't been modified, nothing to do here. 
      */
     if (!$event->getInvoker()->isModified()) {
         return;
     }
     /**
      * The record is not locked, and the lock isn't being changed, nothing to do here. 
      */
     if (!$locked && !$lockModified) {
         return;
     }
     /**
      * Only the lock is being modified so there's nothing to
      * do here. 
      */
     if ($lockModified && $numModified == 1) {
         return;
     }
     /**
      * The record is locked, throw an exception. 
      */
     if ($locked) {
         throw new Behavior_Lockable_Exception('The record must be unlocked before it can be modified.');
     }
 }
 /**
  * Display comment form incase of validation issues
  *  
  * @param sfWebRequest $request
  */
 public function executeCreate(sfWebRequest $request)
 {
     $this->rating_enabled = $request->hasParameter('rating_enabled') ? $request->getParameter('rating_enabled') : false;
     $form = $this->getForm($this->rating_enabled);
     if ($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT)) {
         $form->bind($request->getParameter($form->getName()));
         if ($form->isValid()) {
             if (sfConfig::get('app_rt_comment_moderation', false)) {
                 $form->save();
                 $this->notifyAdministrator($form->getObject());
             } else {
                 $form->getObject()->setIsActive(true);
                 $form->save();
                 $routes = $this->getContext()->getRouting()->getRoutes();
                 $route_name = Doctrine_Inflector::tableize($form->getObject()->getModel()) . '_show';
                 if (isset($routes[$route_name])) {
                     $target_object = $form->getObject()->getObject();
                     $cache_class = $form->getObject()->getModel() . 'CacheToolkit';
                     if (class_exists($cache_class)) {
                         call_user_func($cache_class . '::clearCache', $target_object);
                     }
                     $this->redirect($this->getContext()->getRouting()->generate($route_name, $target_object));
                 }
             }
             $this->redirect(sprintf('rtComment/saved?model=%s&model_id=%s', $form->getObject()->getModel(), $form->getObject()->getModelId()));
         } else {
             $this->getUser()->setFlash('default_error', true, false);
         }
     }
     $this->form = $form;
 }
 public function getPopularTagsQueryTableProxy($relations = null, $limit = 10, $hydrationMode = Doctrine::HYDRATE_RECORD)
 {
     if (!$relations) {
         $relations = array();
         $allRelations = $this->getInvoker()->getTable()->getRelations();
         foreach ($allRelations as $name => $relation) {
             if ($relation['refTable']) {
                 $relations[] = $name;
             }
         }
     }
     $relations = (array) $relations;
     $q = $this->getInvoker()->getTable()->createQuery('t')->select('t.*');
     $counts = array();
     foreach ($relations as $relation) {
         $countAlias = 'num_' . Doctrine_Inflector::tableize($relation);
         $q->leftJoin('t.' . $relation . ' ' . $relation);
         $q->addSelect('COUNT(DISTINCT ' . $relation . '.id) AS ' . $countAlias);
         $counts[] = 'COUNT(DISTINCT ' . $relation . '.id)';
     }
     $q->addSelect('(' . implode(' + ', $counts) . ') as total_num');
     $q->orderBy('total_num DESC');
     $q->groupBy('t.id');
     $q->addHaving('total_num > 0');
     $q->limit($limit);
     return $q;
 }
 public function testClassifyTableize() {
     $name = "Forum_Category";
     $this->assertEqual(Doctrine_Inflector::tableize($name), "forum__category");
     $this->assertEqual(Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)), $name);
     
     
 }
 public function getPopularTagsQuery($relations = null, $limit = null, dmDoctrineQuery $q = null)
 {
     if (empty($relations)) {
         $this->loadTaggableModels();
         $relations = array_keys($this->getRelationHolder()->getAssociations());
         if (empty($relations)) {
             throw new dmException('There is no taggable model');
         }
     } else {
         $relations = (array) $relations;
     }
     $q = $q ? $q : $this->createQuery('t')->select('t.*');
     $rootAlias = $q->getRootAlias();
     $counts = array();
     foreach ($relations as $relation) {
         $countAlias = 'num_' . Doctrine_Inflector::tableize($relation);
         $q->leftJoin($rootAlias . '.' . $relation . ' ' . $relation);
         $q->addSelect('COUNT(DISTINCT ' . $relation . '.id) AS ' . $countAlias);
         $counts[] = 'COUNT(DISTINCT ' . $relation . '.id)';
     }
     $q->addSelect('(' . implode(' + ', $counts) . ') as total_num');
     //$q->orderBy('total_num DESC');
     $q->groupBy($rootAlias . '.id');
     $q->addHaving('total_num > 0');
     if (null !== $limit) {
         $q->limit($limit);
     }
     return $q;
 }
 public function executeAjaxSearch(sfWebRequest $request)
 {
     if ($request->hasParameter('models')) {
         $query = Doctrine::getTable('rtIndex')->getStandardSearchComponentInQuery($request->getParameter('q', ''), $this->getUser()->getCulture(), Doctrine::getTable('rtIndex')->getModelTypeRestrictionQuery(explode(',', $request->getParameter('models'))));
     } else {
         $query = Doctrine::getTable('rtIndex')->getBasePublicSearchQuery($request->getParameter('q'), $this->getUser()->getCulture());
     }
     $this->logMessage('{testing}' . $request->getParameter('q', ''), 'notice');
     $query->limit(100);
     $rt_indexes = $query->execute();
     $routes = $this->getContext()->getRouting()->getRoutes();
     $items = array();
     foreach ($rt_indexes as $rt_index) {
         $route = Doctrine_Inflector::tableize($rt_index->getCleanModel()) . '_show';
         $url = '';
         if (isset($routes[Doctrine_Inflector::tableize($rt_index->getCleanModel()) . '_show'])) {
             $url = sfContext::getInstance()->getController()->genUrl(array('sf_route' => $route, 'sf_subject' => $rt_index->getObject()));
             $url = str_replace('/frontend_dev.php', '', $url);
         }
         $object = $rt_index->getObject();
         $item = array('title' => $object->getTitle(), 'link' => $url);
         $item['placeholder'] = $object instanceof rtSnippet ? '![' . $object->getTitle() . '](snippet:' . $object->getCollection() . ')' : '';
         $items[] = $item;
     }
     return $this->returnJSONResponse(array('status' => 'success', 'items' => $items), $request);
 }
 /**
  * Set table definition for contactable behavior
  * (borrowed from Sluggable in Doctrine core)
  *
  * @return void
  * @author Brent Shaffer
  */
 public function setTableDefinition()
 {
     foreach ($this->_options['fields'] as $field => $unit) {
         $name = Doctrine_Inflector::tableize($field . '_' . strtolower($unit));
         $this->_options['columns'][$field] = $name;
         $this->hasColumn($name, 'float');
     }
     $this->_table->unshiftFilter(new Doctrine_Record_Filter_Localizable($this->_options));
 }
示例#8
0
 static function getDetails($id, $categoryId)
 {
     $categoryName = RelationshipCategoryTable::$categoryNames[$categoryId];
     $db = Doctrine_Manager::connection();
     $sql = 'SELECT * FROM ' . Doctrine_Inflector::tableize($categoryName) . ' WHERE relationship_id = ?';
     $stmt = $db->execute($sql, array($id));
     $ret = $stmt->fetch(PDO::FETCH_ASSOC);
     unset($ret['id'], $ret['relationship_id']);
     return $ret;
 }
示例#9
0
 /**
  * Returns the name of the task the specified class _would_ implement
  * 
  * N.B. This method does not check if the specified class is actually a Doctrine Task
  * 
  * This is public so we can easily test its reactions to fully-qualified class names, without having to add
  * PHP 5.3-specific test code
  * 
  * @param string $className
  * @return string|bool
  */
 public static function deriveTaskName($className)
 {
     $nameParts = explode('\\', $className);
     foreach ($nameParts as &$namePart) {
         $prefix = __CLASS__ . '_';
         $baseName = strpos($namePart, $prefix) === 0 ? substr($namePart, strlen($prefix)) : $namePart;
         $namePart = str_replace('_', '-', Doctrine_Inflector::tableize($baseName));
     }
     return implode('-', $nameParts);
 }
 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));
     }
 }
示例#11
0
 static function getDetails($id)
 {
     $entity = array();
     $db = Doctrine_Manager::connection();
     $sql = 'SELECT ed.name FROM extension_definition ed ' . 'LEFT JOIN extension_record er ON (er.definition_id = ed.id) ' . 'WHERE er.entity_id = ?';
     $stmt = $db->execute($sql, array($id));
     $extAry = $stmt->fetchAll(PDO::FETCH_COLUMN);
     $entity['types'] = implode(',', $extAry);
     $extsWithFields = array_intersect($extAry, ExtensionDefinitionTable::$extensionNamesWithFields);
     //get fields and values for each extension
     foreach ($extsWithFields as $ext) {
         $sql = 'SELECT * FROM ' . Doctrine_Inflector::tableize($ext) . ' WHERE entity_id = ?';
         $stmt = $db->execute($sql, array($id));
         $extData = $stmt->fetch(PDO::FETCH_ASSOC);
         unset($extData['id'], $extData['entity_id']);
         $entity = array_merge($entity, $extData);
     }
     return $entity;
 }
示例#12
0
文件: Schema.php 项目: sensorsix/app
 /**
  * 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;
 }
示例#13
0
 /**
  * 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;
     }
 }
示例#14
0
            <?php 
            if (rtSiteToolkit::isMultiSiteEnabled()) {
                ?>
            <?php 
                include_partial('rtAdmin/site_reference_key', array('id' => $rt_index->getSiteId()));
                ?>
            <?php 
            }
            ?>
          </h2>
          <p>
            <?php 
            echo $rt_index->getObject()->getDescription();
            ?>
 ... <?php 
            echo link_to_if(isset($routes[Doctrine_Inflector::tableize($rt_index->getCleanModel()) . '_show']), __('read more'), Doctrine_Inflector::tableize($rt_index->getCleanModel()) . '_show', $rt_index->getObject());
            ?>
          </p>
        </li>
      <?php 
            $i++;
        }
        ?>
      </ul>
    <?php 
    } else {
        ?>
    <p><?php 
        echo __('Nothing found, please try again.');
        ?>
</p>
示例#15
0
 /**
  * __construct
  *
  * Since this is an abstract classes that extend this must follow a patter of Doctrine_Task_{TASK_NAME}
  * This is what determines the task name for executing it.
  *
  * @return void
  */
 public function __construct($dispatcher = null)
 {
     $this->dispatcher = $dispatcher;
     $this->taskName = str_replace('_', '-', Doctrine_Inflector::tableize(str_replace('Doctrine_Task_', '', get_class($this))));
 }
    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());
    }
示例#17
0
 /**
  * __call
  *
  * Adds support for magic finders.
  * findByColumnName, findByRelationAlias
  * findById, findByContactId, etc.
  *
  * @return void
  */
 public function __call($method, $arguments)
 {
     if (substr($method, 0, 6) == 'findBy') {
         $by = substr($method, 6, strlen($method));
         $method = 'findBy';
     } else {
         if (substr($method, 0, 9) == 'findOneBy') {
             $by = substr($method, 9, strlen($method));
             $method = 'findOneBy';
         }
     }
     if (isset($by)) {
         if (!isset($arguments[0])) {
             throw new Doctrine_Table_Exception('You must specify the value to findBy');
         }
         $fieldName = Doctrine_Inflector::tableize($by);
         $hydrationMode = isset($arguments[1]) ? $arguments[1] : null;
         if ($this->hasColumn($this->getColumnName($fieldName))) {
             return $this->{$method}($fieldName, $arguments[0], $hydrationMode);
         } else {
             if ($this->hasRelation($by)) {
                 $relation = $this->getRelation($by);
                 if ($relation['type'] === Doctrine_Relation::MANY) {
                     throw new Doctrine_Table_Exception('Cannot findBy many relationship.');
                 }
                 return $this->{$method}($relation['local'], $arguments[0], $hydrationMode);
             } else {
                 throw new Doctrine_Table_Exception('Cannot find by: ' . $by . '. Invalid column or relationship alias.');
             }
         }
     }
     throw new Doctrine_Table_Exception(sprintf('Unknown method %s::%s', get_class($this), $method));
 }
示例#18
0
<?php

use_helper('I18N');
$routes = $sf_context->getRouting()->getRoutes();
$route_name = Doctrine_Inflector::tableize($model) . '_show';
slot('rt-title', __('Thanks for the comment'));
?>
<p><?php 
echo __('Your comment has been added and is awaiting approval.');
?>
</p>
<p><?php 
echo link_to_if(isset($routes[$route_name]), __('Go back'), $route_name, $object);
?>
</p>
示例#19
0
 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;
 }
 public function getSingularLower()
 {
     return Doctrine_Inflector::tableize(Doctrine_Core::getTable($this->getName())->getOption('name'));
 }
示例#21
0
文件: Diff.php 项目: szelpe/cukorka
 /**
  * Clean the produced model information of any potential prefix text
  *
  * @param  mixed $info  Either array or string to clean of prefixes
  * @return mixed $info  Cleaned value which is either an array or string
  */
 protected function _cleanModelInformation($info)
 {
     if (is_array($info)) {
         foreach ($info as $key => $value) {
             unset($info[$key]);
             $key = $this->_cleanModelInformation($key);
             $info[$key] = $this->_cleanModelInformation($value);
         }
         return $info;
     } else {
         $find = array(self::$_toPrefix, self::$_fromPrefix, Doctrine_Inflector::tableize(self::$_toPrefix) . '_', Doctrine_Inflector::tableize(self::$_fromPrefix) . '_', Doctrine_Inflector::tableize(self::$_toPrefix), Doctrine_Inflector::tableize(self::$_fromPrefix));
         return str_replace($find, null, $info);
     }
 }
示例#22
0
 /**
  * tableize
  *
  * returns table name from class name
  *
  * @param string $classname
  * @return string
  */
 public static function tableize($className)
 {
     return Doctrine_Inflector::tableize($className);
 }
示例#23
0
 /**
  * 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;
 }
示例#24
0
 public function getRatedObjectFk()
 {
     return $this->_options['user'] ? 'id' : Doctrine_Inflector::tableize($this->_options['table']->getComponentName()) . '_id';
 }
示例#25
0
文件: Import.php 项目: adnanali/munch
 /**
  * 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;
 }
示例#26
0
 /**
  * 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";
     }
 }
示例#27
0
文件: Table.php 项目: mediasadc/alba
 /**
  * Resolve the passed find by field name to the appropriate field name
  * regardless of whether the user passes a column name, field name, or a Doctrine_Inflector::classified()
  * version of their column name. It will be inflected with Doctrine_Inflector::tableize() 
  * to get the column or field name
  *
  * @param string $name 
  * @return string $fieldName
  */
 protected function _resolveFindByFieldName($name)
 {
     $fieldName = Doctrine_Inflector::tableize($name);
     if ($this->hasColumn($name) || $this->hasField($name)) {
         return $this->getFieldName($this->getColumnName($name));
     } else {
         if ($this->hasColumn($fieldName) || $this->hasField($fieldName)) {
             return $this->getFieldName($this->getColumnName($fieldName));
         } else {
             return false;
         }
     }
 }
示例#28
0
 static function getRelationships($ids, $options)
 {
     $db = Doctrine_Manager::connection();
     $sql = 'SELECT ' . LsApi::generateSelectQuery(array('r' => 'Relationship')) . ' FROM relationship r WHERE r.id IN (' . implode(',', $ids) . ')';
     $stmt = $db->execute($sql);
     if (@$options['details']) {
         $rels = array();
         if ($catId = @$options['cat_id']) {
             //make Relationships accessible by id
             foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $rel) {
                 $rels[$rel['id']] = $rel;
             }
             //get category data
             $categoryName = RelationshipCategoryTable::$categoryNames[$catId];
             $db = Doctrine_Manager::connection();
             $sql = 'SELECT * FROM ' . Doctrine_Inflector::tableize($categoryName) . ' WHERE relationship_id IN (' . implode(',', $ids) . ')';
             $stmt = $db->execute($sql, array($id));
             //merge category data with relationship data
             foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                 $relId = $row['relationship_id'];
                 unset($row['id'], $row['relationship_id']);
                 $rels[$relId] = array_merge($rels[$relId], $row);
             }
             return array_values($rels);
         } else {
             foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $rel) {
                 $rels[] = array_merge($rel, RelationshipApi::getDetails($rel['id'], $rel['category_id']));
             }
             return $rels;
         }
     } else {
         return $stmt->fetchAll(PDO::FETCH_ASSOC);
     }
 }