public function testClassifyTableize() {
     $name = "Forum_Category";
     $this->assertEqual(Doctrine_Inflector::tableize($name), "forum__category");
     $this->assertEqual(Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)), $name);
     
     
 }
Example #2
0
 public function analyze($text, $encoding = null)
 {
     static $stopwords;
     if (!isset($stopwords)) {
         $stopwords = array_flip(self::$_stopwords);
     }
     $text = preg_replace('/[\'`´"]/', '', $text);
     $text = Doctrine_Inflector::unaccent($text);
     $text = preg_replace('/[^A-Za-z0-9]/', ' ', $text);
     $text = str_replace('  ', ' ', $text);
     $terms = explode(' ', $text);
     $ret = array();
     if (!empty($terms)) {
         foreach ($terms as $i => $term) {
             if (empty($term)) {
                 continue;
             }
             $lower = strtolower(trim($term));
             if (isset($stopwords[$lower])) {
                 continue;
             }
             $ret[$i] = $lower;
         }
     }
     return $ret;
 }
 /**
  * Convert any passed string to a url friendly string. Converts 'My first blog post' to 'my-first-blog-post'
  *
  * @param  string $text  Text to urlize
  * @return string $text  Urlized text
  */
 public static function doctrine_urlize($text)
 {
     // Transliteration
     $text = self::transliterate($text);
     // Urlize
     return Doctrine_Inflector::urlize($text);
 }
Example #4
0
 public static function slugify($text)
 {
     $text = Doctrine_Inflector::unaccent($text);
     // replace all non letters or digits by -
     $text = preg_replace('/\\W+/', '-', $text);
     // trim and lowercase
     $text = strtolower(trim($text, '-'));
     return $text;
     /**********************
     
         // Remove all non url friendly characters with the unaccent function
         $text = Doctrine_Inflector::unaccent($this->get('title'));
     
         if (function_exists('mb_strtolower')) {
           $text = mb_strtolower($text);
         } else {
           $text = strtolower($text);
         }
     
         // Remove all none word characters
         $text = preg_replace('/\W/', ' ', $text);
     
         // More stripping. Get rid of all non-alphanumeric.
         $text = strtolower(preg_replace('/[^A-Z^a-z^0-9^\/]+/', '', $text));
     
         return trim($text, '-');
     */
 }
 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;
 }
Example #6
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 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);
 }
Example #9
0
 public function executeAddDocument(sfWebRequest $request)
 {
     $this->forward404Unless($request->isMethod(sfRequest::PUT));
     $document = $request->getParameter('document');
     $this->transaction = TransactionTable::getInstance()->find($document['transaction_id']);
     $asso = AssoTable::getInstance()->find($document['asso_id']);
     $this->checkAuthorisation($asso);
     $form = new DocumentForm();
     $files = $request->getFiles($form->getName());
     $form->bind($request->getParameter($form->getName()), $files);
     $infos = new finfo(FILEINFO_MIME_TYPE);
     if ($form->isValid() and $infos->file($files['fichier']['tmp_name']) == 'application/pdf') {
         $fichier = $this->transaction->getPrimaryKey() . '-' . date('Y-m-d-H-i-s') . '-' . Doctrine_Inflector::urlize($files['fichier']['name']);
         if (substr($fichier, -4) == '-pdf') {
             $fichier = substr($fichier, 0, -4);
         }
         $fichier .= '.pdf';
         $form->setValue('fichier', $fichier);
         $form->setValue('auteur', $this->getUser()->getGuardUser()->getPrimaryKey());
         $doc = $form->save();
         $path = $doc->getPath();
         $dir = substr($path, 0, -strlen($fichier));
         if (!is_dir($dir)) {
             mkdir($dir);
         }
         move_uploaded_file($files['fichier']['tmp_name'], $path);
         $this->redirect('transaction_show', $this->transaction);
     } else {
         $this->form = $form;
         $this->setTemplate('show', $this->transaction);
         $this->getResponse()->setSlot('current_asso', $asso);
     }
 }
 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;
 }
Example #11
0
 public static function sortString($a, $b)
 {
     if ($a[0] == $b[0]) {
         return 0;
     }
     return Doctrine_Inflector::urlize($a[0]) < Doctrine_Inflector::urlize($b[0]) ? -1 : 1;
 }
 /**
  * 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);
 }
Example #13
0
 /**
  * @param  $_query
  * @return Kebab_Controller_Helper_Search
  */
 public function setQuery($_query)
 {
     $_query = strtolower(Doctrine_Inflector::unaccent($_query));
     if ($_query !== false && is_string($_query)) {
         $this->_query = '*' . $_query . '*';
     }
     return $this;
 }
 /**
  * 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));
 }
 public function postUp()
 {
     $records = Projects_Model_ProjectTable::getInstance()->findAll();
     foreach ($records as $record) {
         if (empty($record->name_slug)) {
             $record->name_slug = Doctrine_Inflector::urlize($record->name);
             $record->save();
         }
     }
 }
 public function testGermanCharactersAreConvertedCorrectly()
 {
     $this->assertEqual(Doctrine_Inflector::urlize('Ästhetik'), 'aesthetik');
     $this->assertEqual(Doctrine_Inflector::urlize('ästhetisch'), 'aesthetisch');
     $this->assertEqual(Doctrine_Inflector::urlize('Übung'), 'uebung');
     $this->assertEqual(Doctrine_Inflector::urlize('über'), 'ueber');
     $this->assertEqual(Doctrine_Inflector::urlize('Öl'), 'oel');
     $this->assertEqual(Doctrine_Inflector::urlize('ölig'), 'oelig');
     $this->assertEqual(Doctrine_Inflector::urlize('Fuß'), 'fuss');
 }
Example #17
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);
 }
Example #18
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;
 }
 /**
  * Return a string with html tags, special charecters and puctuation removed.
  *
  * @param  string $string
  * @return string
  */
 public static function getCleanedString($string)
 {
     $string = strip_tags($string);
     $string = preg_replace('/[\'`�"]/', '', $string);
     $string = Doctrine_Inflector::unaccent($string);
     $string = preg_replace('/[^A-Za-z0-9]/', ' ', $string);
     $string = preg_replace('/\\s\\s+/', ' ', trim($string));
     $string = strtolower($string);
     return $string;
 }
 public function postUp()
 {
     $table = Doctrine::getTable('News_Model_News');
     $records = $table->findAll();
     foreach ($records as $record) {
         if (empty($record->title_slug)) {
             $record->title_slug = Doctrine_Inflector::urlize($record->title);
             $record->save();
         }
     }
 }
Example #21
0
 static function urlize($text)
 {
     // Remove all non url friendly characters with the unaccent function
     $text = Doctrine_Inflector::unaccent($text);
     $text = str_replace("'", "", $text);
     // Remove all none word characters
     $text = preg_replace('/\\W/', ' ', $text);
     // More stripping. Replace spaces with dashes
     $text = preg_replace('/[^A-Z^a-z^0-9^\\/]+/', '-', preg_replace('/([a-z\\d])([A-Z])/', '\\1_\\2', preg_replace('/([A-Z]+)([A-Z][a-z])/', '\\1_\\2', preg_replace('/::/', '/', $text))));
     return trim($text, '-');
 }
Example #22
0
 protected function buildSlug($record)
 {
     if (empty($this->_options['fields'])) {
         $value = (string) $record;
     } else {
         $value = '';
         foreach ($this->_options['fields'] as $field) {
             $value = $record->{$field} . ' ';
         }
     }
     return Doctrine_Inflector::urlize($value);
 }
 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'))));
     }
 }
 /**
  * Generates a non-random-filename
  *
  * @return string A non-random name to represent the current file
  */
 public function generateFilename()
 {
     $filename = $this->getOriginalName();
     $ext = filter_var($this->getExtension($this->getOriginalExtension()), FILTER_SANITIZE_URL);
     $name = substr($this->getOriginalName(), 0, -strlen($ext));
     $i = 1;
     while (file_exists($this->getPath() . '/' . $filename)) {
         $filename = Doctrine_Inflector::urlize($name) . '-' . $i . $ext;
         $i++;
     }
     return $filename;
 }
 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));
     }
 }
 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));
 }
Example #27
0
 public function getSlugize()
 {
     // Remove all non url friendly characters with the unaccent function
     $text = Doctrine_Inflector::unaccent($this->get('title'));
     if (function_exists('mb_strtolower')) {
         $text = mb_strtolower($text);
     } else {
         $text = strtolower($text);
     }
     // Remove all none word characters
     $text = preg_replace('/\\W/', ' ', $text);
     // More stripping. Get rid of all non-alphanumeric.
     $text = strtolower(preg_replace('/[^A-Z^a-z^0-9^\\/]+/', '', $text));
     return trim($text, '-');
 }
Example #28
0
 public function executeExport(sfWebRequest $request)
 {
     $budget = $this->getRoute()->getObject();
     $asso = $budget->getAsso();
     $this->checkAuthorisation($budget->getAsso());
     $categories = $budget->getCategoriesWithEntry()->execute();
     $nom = $budget->getPrimaryKey() . '-' . date('Y-m-d-H-i-s') . '-' . Doctrine_Inflector::urlize($budget->getNom());
     $html = $this->getPartial('budget/pdf', compact(array('categories', 'asso', 'budget', 'transactions')));
     $doc = new Document();
     $doc->setNom('Export du budget prévisionnel');
     $doc->setAsso($asso);
     $doc->setUser($this->getUser()->getGuardUser());
     $doc->setTypeFromSlug('budgets');
     $path = $doc->generatePDF('Budget Prévisionnel', $nom, $html);
     header('Content-type: application/pdf');
     readfile($path);
     return sfView::NONE;
 }
 public function beforeSave($event)
 {
     if (true !== $this->update && $this->owner->slug) {
         return parent::beforeSave($event);
     }
     if (!is_array($this->columns)) {
         throw new CException('Columns have to be in array format.');
     }
     $availableColumns = array_keys($this->owner->tableSchema->columns);
     // Try to guess the right columns
     if (0 === count($this->columns)) {
         $this->columns = array_intersect($this->_defaultColumnsToCheck, $availableColumns);
     } else {
         // Unknown columns on board?
         foreach ($this->columns as $col) {
             if (!in_array($col, $availableColumns)) {
                 throw new CException('Unable to build slug, column ' . $col . ' not found.');
             }
         }
     }
     // No columns to build a slug?
     if (0 === count($this->columns)) {
         throw new CException('You must define "columns" to your sluggable behavior.');
     }
     // Fetch values
     $values = array();
     foreach ($this->columns as $col) {
         $values[] = $this->owner->{$col};
     }
     // First version of slug
     $slug = $checkslug = Doctrine_Inflector::urlize(implode('-', $values));
     // Check if slug has to be unique
     if (false === $this->unique) {
         $this->owner->slug = $slug;
     } else {
         $counter = 0;
         while ($this->owner->findByAttributes(array('slug' => $checkslug))) {
             $checkslug = sprintf('%s-%d', $slug, ++$counter);
         }
         $this->owner->slug = $counter > 0 ? $checkslug : $slug;
     }
     return parent::beforeSave($event);
 }
Example #30
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;
 }