protected function setUp()
 {
     parent::setUp();
     BookstoreDataPopulator::populate($this->con);
     Propel::disableInstancePooling();
     $this->books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)->find();
 }
Exemplo n.º 2
0
 public function execute()
 {
     $writer = new CsvWriter($this->getCsvWriterOptions());
     $writer->createTempStream();
     if ($this->getHeader()) {
         $writer->writeRow($this->getHeader());
     }
     $results = $this->query->find();
     foreach ($results as $result) {
         $writer->writeRow($this->getRow($result));
     }
     $this->content = $writer->getFileContent();
     $writer->close();
     return $this;
 }
 /**
  * Returns the choices associated to the model.
  *
  * @return array An array of choices
  */
 public function getChoices()
 {
     $choices = array();
     if (false !== $this->getOption('add_empty')) {
         $choices[''] = true === $this->getOption('add_empty') ? '' : $this->getOption('add_empty');
     }
     $criteria = PropelQuery::from($this->getOption('model'));
     if ($this->getOption('criteria')) {
         $criteria->mergeWith($this->getOption('criteria'));
     }
     foreach ($this->getOption('query_methods') as $methodName => $methodParams) {
         if (is_array($methodParams)) {
             call_user_func_array(array($criteria, $methodName), $methodParams);
         } else {
             $criteria->{$methodParams}();
         }
     }
     if ($order = $this->getOption('order_by')) {
         $criteria->orderBy($order[0], $order[1]);
     }
     $objects = $criteria->find($this->getOption('connection'));
     $methodKey = $this->getOption('key_method');
     if (!method_exists($this->getOption('model'), $methodKey)) {
         throw new RuntimeException(sprintf('Class "%s" must implement a "%s" method to be rendered in a "%s" widget', $this->getOption('model'), $methodKey, __CLASS__));
     }
     $methodValue = $this->getOption('method');
     if (!method_exists($this->getOption('model'), $methodValue)) {
         throw new RuntimeException(sprintf('Class "%s" must implement a "%s" method to be rendered in a "%s" widget', $this->getOption('model'), $methodValue, __CLASS__));
     }
     foreach ($objects as $object) {
         $choices[$object->{$methodKey}()] = $object->{$methodValue}();
     }
     return $choices;
 }
 /**
  * testFilterById
  *
  * Various test for filterById functions
  * Id's are autoincrement so we have to use a Select to get current ID's
  *
  */
 public function testFilterById()
 {
     // find by single id
     $book = PropelQuery::from('Book b')->where('b.Title like ?', 'Don%')->orderBy('b.ISBN', 'desc')->findOne();
     $c = BookQuery::create()->filterById($book->getId());
     $book2 = $c->findOne();
     $this->assertTrue($book2 instanceof Book);
     $this->assertEquals('Don Juan', $book2->getTitle());
     //find range
     $booksAll = PropelQuery::from('Book b')->orderBy('b.ID', 'asc')->find();
     $booksIn = BookQuery::create()->filterById(array($booksAll[1]->getId(), $booksAll[2]->getId()))->find();
     $this->assertTrue($booksIn[0] == $booksAll[1]);
     $this->assertTrue($booksIn[1] == $booksAll[2]);
     // filter by min value with greater equal
     $booksIn = null;
     $booksIn = BookQuery::create()->filterById(array('min' => $booksAll[2]->getId()))->find();
     $this->assertTrue($booksIn[1] == $booksAll[3]);
     // filter by max value with less equal
     $booksIn = null;
     $booksIn = BookQuery::create()->filterById(array('max' => $booksAll[1]->getId()))->find();
     $this->assertTrue($booksIn[1] == $booksAll[1]);
     // check backwards compatibility:
     // SELECT  FROM `book` WHERE book.id IN (:p1,:p2)
     // must be the same as
     // SELECT  FROM `book` WHERE (book.id>=:p1 AND book.id<=:p2)
     $minMax = BookQuery::create()->filterById(array('min' => $booksAll[1]->getId(), 'max' => $booksAll[2]->getId()))->find();
     $In = BookQuery::create()->filterById(array($booksAll[1]->getId(), $booksAll[2]->getId()))->find();
     $this->assertTrue($minMax[0] === $In[0]);
     $this->assertTrue(count($minMax->getData()) === count($In->getData()));
 }
 /**
  * @see sfValidatorBase
  */
 protected function doClean($value)
 {
     $criteria = PropelQuery::from($this->getOption('model'));
     if ($this->getOption('criteria')) {
         $criteria->mergeWith($this->getOption('criteria'));
     }
     foreach ($this->getOption('query_methods') as $method) {
         $criteria->{$method}();
     }
     if ($this->getOption('multiple')) {
         if (!is_array($value)) {
             $value = array($value);
         }
         $count = count($value);
         if ($this->hasOption('min') && $count < $this->getOption('min')) {
             throw new sfValidatorError($this, 'min', array('count' => $count, 'min' => $this->getOption('min')));
         }
         if ($this->hasOption('max') && $count > $this->getOption('max')) {
             throw new sfValidatorError($this, 'max', array('count' => $count, 'max' => $this->getOption('max')));
         }
         $criteria->addAnd($this->getColumn(), $value, Criteria::IN);
         $dbcount = $criteria->count($this->getOption('connection'));
         if ($dbcount != $count) {
             throw new sfValidatorError($this, 'invalid', array('value' => $value));
         }
     } else {
         $criteria->addAnd($this->getColumn(), $value);
         $dbcount = $criteria->count($this->getOption('connection'));
         if (0 === $dbcount) {
             throw new sfValidatorError($this, 'invalid', array('value' => $value));
         }
     }
     return $value;
 }
Exemplo n.º 6
0
 /**
  * @return \BaseObject|null
  * @throws \PropelException
  */
 public function getSelection()
 {
     $pk = isset($this['id']) ? json_decode($this['id'], true) : null;
     if ($pk && $this->parent instanceof AbstractBackend) {
         return \PropelQuery::from($this->parent->getModelClass())->findPk($pk);
     }
     return null;
 }
 public function testQuery()
 {
     BookstoreDataPopulator::depopulate();
     BookstoreDataPopulator::populate();
     $book = PropelQuery::from('Book b')->where('b.Title like ?', 'Don%')->orderBy('b.ISBN', 'desc')->findOne();
     $this->assertTrue($book instanceof Book);
     $this->assertEquals('Don Juan', $book->getTitle());
 }
 public static function createIndex($class)
 {
   $index = self::getLuceneIndex($class);
   $objects = PropelQuery::from($class)->find();
   foreach ($objects as $object)
   {
     $object->updateLuceneIndex($index);
   }
 }
 public function __construct($className, array $options = array(), \ModelCriteria $query = null)
 {
     $this->className = $className;
     $this->options = array_replace_recursive($this->options, $options);
     if (!$query) {
         $query = \PropelQuery::from($this->className);
     }
     $this->query = $query;
 }
 /**
  * @see sfValidatorBase
  */
 protected function doClean($values)
 {
     if (!is_array($values)) {
         throw new InvalidArgumentException('You must pass an array parameter to the clean() method (this validator can only be used as a post validator).');
     }
     if (!is_array($this->getOption('column'))) {
         $this->setOption('column', array($this->getOption('column')));
     }
     if (!is_array($field = $this->getOption('field'))) {
         $this->setOption('field', $field ? array($field) : array());
     }
     $fields = $this->getOption('field');
     $criteria = PropelQuery::from($this->getOption('model'));
     foreach ((array) $this->getOption('query_methods') as $methodName => $methodParams) {
         if (is_array($methodParams)) {
             $criteria = call_user_func_array(array($criteria, $methodName), $methodParams);
         } else {
             $criteria = $criteria->{$methodParams}();
         }
     }
     if ($this->getOption('allow_null_uniques')) {
         $tableMap = call_user_func(array($this->getOption('model') . 'Peer', 'getTableMap'));
         $nullColsCount = 0;
     }
     foreach ($this->getOption('column') as $i => $column) {
         $name = isset($fields[$i]) ? $fields[$i] : $column;
         if (!array_key_exists($name, $values)) {
             // one of the column has been removed from the form
             return $values;
         }
         $colName = call_user_func(array(constant($this->getOption('model') . '::PEER'), 'translateFieldName'), $column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
         // handle null unique indexes
         if ($this->getOption('allow_null_uniques') && null === $values[$name] && !$tableMap->getColumn($colName)->isNotNull()) {
             $nullColsCount++;
             continue;
         }
         $criteria->add($colName, $values[$name]);
     }
     if ($this->getOption('allow_null_uniques') && $nullColsCount == count($this->getOption('column'))) {
         // all columns for checking were both empty and null unique
         $object = null;
     } else {
         // perform query for normal unique check
         $object = $criteria->findOne($this->getOption('connection'));
     }
     // if no object or if we're updating the object, it's ok
     if (null === $object || $this->isUpdate($object, $values)) {
         return $values;
     }
     $error = new sfValidatorError($this, 'invalid', array('column' => implode(', ', $this->getOption('column'))));
     if ($this->getOption('throw_global_error')) {
         throw $error;
     }
     $columns = $this->getOption('column');
     throw new sfValidatorErrorSchema($this, array($columns[0] => $error));
 }
Exemplo n.º 11
0
 public function render(Curry_Backend $backend, array $params)
 {
     $modelClass = $this->modelForm->getModelClass();
     $item = $this->getSelection($params);
     if (!isset($item)) {
         $item = new $modelClass();
         $relatedItem = $this->getParentSelection($params);
         if ($relatedItem) {
             $relations = PropelQuery::from($modelClass)->getTableMap()->getRelations();
             foreach ($relations as $relation) {
                 if ($relation->getRightTable()->getPhpName() == get_class($relatedItem) && in_array($relation->getType(), array(RelationMap::MANY_TO_ONE))) {
                     $item->{'set' . $relation->getName()}($relatedItem);
                 }
             }
         }
     }
     $form = clone $this->modelForm;
     $form->setOptions(array('method' => 'post', 'action' => (string) url('', $params)));
     $buttons = array('save');
     $form->addElement('submit', 'save', array('label' => 'Save'));
     if (!$item->isNew() && $this->parentView instanceof Curry_ModelView_List && $this->parentView->hasAction('delete')) {
         $form->addElement('submit', 'delete', array('label' => 'Delete', 'class' => 'btn btn-danger', 'onclick' => "return confirm('Do you really want to delete this item? This cannot be undone.');"));
         $buttons[] = 'delete';
     }
     $form->addDisplayGroup($buttons, 'save_group', array('class' => 'horizontal-group'));
     $form->fillForm($item);
     if (isPost() && $form->isValid($_POST)) {
         if ($form->delete && $form->delete->isChecked()) {
             $backend->createModelUpdateEvent($modelClass, $item->getPrimaryKey(), 'delete');
             $item->delete();
             if ($item instanceof Curry_ISearchable) {
                 Curry_Backend_Indexer::removeItem($item);
             }
             $backend->addMainContent('<p>The item has been deleted.</p>');
             return;
         }
         $form->fillModel($item);
         $this->triggerCallback($this->preSave, $item, $form);
         $item->save();
         $this->triggerCallback($this->postSave, $item, $form);
         $form->fillForm($item);
         $backend->createModelUpdateEvent($modelClass, $item->getPrimaryKey(), 'update');
         if ($item instanceof Curry_ISearchable) {
             Curry_Backend_Indexer::updateItem($item);
         }
         if (isAjax()) {
             return '';
         }
     }
     $this->triggerCallback($this->preRender, $item, $form);
     $backend->addMainContent($form);
 }
Exemplo n.º 12
0
 public function show(Request $request)
 {
     $modelClass = $this->modelForm->getModelClass();
     $item = $this->getSelection();
     if (!isset($item) || !$item instanceof $modelClass) {
         $item = new $modelClass();
         $relatedItem = $this->parent instanceof AbstractBackend ? $this->parent->getSelection() : null;
         if ($relatedItem) {
             $relations = \PropelQuery::from($modelClass)->getTableMap()->getRelations();
             foreach ($relations as $relation) {
                 if ($relation->getRightTable()->getPhpName() == get_class($relatedItem) && in_array($relation->getType(), array(\RelationMap::MANY_TO_ONE))) {
                     $item->{'set' . $relation->getName()}($relatedItem);
                 }
             }
         }
     }
     $form = clone $this->modelForm;
     $buttons = array('save');
     $form->addField('save', array('type' => 'submit', 'label' => 'Save', 'class' => 'btn btn-primary'));
     if (!$item->isNew() && $this->parent instanceof ListView && $this->parent->hasAction('delete')) {
         $form->addField('delete', array('type' => 'submit', 'label' => 'Delete', 'class' => 'btn btn-danger', 'onclick' => "return confirm('Do you really want to delete this item? This cannot be undone.');"));
         $buttons[] = 'delete';
     }
     //$form->addDisplayGroup($buttons, 'save_group', array('class' => 'horizontal-group'));
     $form->fillForm($item);
     if ($request->isMethod('POST') && $form->isValid($request->request->all())) {
         if ($form->delete && $form->delete->isChecked()) {
             //$this->createModelUpdateEvent($modelClass, $item->getPrimaryKey(), 'delete');
             $item->delete();
             if ($item instanceof \Curry_ISearchable) {
                 \Curry_Backend_Indexer::removeItem($item);
             }
             $this->addMainContent('<p>The item has been deleted.</p>');
             return parent::render();
         }
         $form->fillModel($item);
         $this->triggerCallback($this->preSave, $item, $form);
         $item->save();
         $this->triggerCallback($this->postSave, $item, $form);
         $form->fillForm($item);
         //$this->createModelUpdateEvent($modelClass, $item->getPrimaryKey(), 'update');
         if ($item instanceof \Curry_ISearchable) {
             \Curry_Backend_Indexer::updateItem($item);
         }
         if ($request->isXmlHttpRequest()) {
             return \Symfony\Component\HttpFoundation\Response::create('');
         }
     }
     $this->triggerCallback($this->preRender, $item, $form);
     $this->addMainContent($form);
     return parent::render();
 }
Exemplo n.º 13
0
 public function testInstancePoolingReenabled()
 {
     Propel::enableInstancePooling();
     $books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)->find($this->con);
     foreach ($books as $book) {
     }
     $this->assertTrue(Propel::isInstancePoolingEnabled());
     Propel::disableInstancePooling();
     $books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)->find($this->con);
     foreach ($books as $book) {
     }
     $this->assertFalse(Propel::isInstancePoolingEnabled());
     Propel::enableInstancePooling();
 }
Exemplo n.º 14
0
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     self::$fixturesDirectory = realpath(dirname(dirname(__DIR__)) . '/fixtures');
     \Curry_Core::init(array('curry' => array('name' => 'Curry Unit Tests', 'adminEmail' => '*****@*****.**', 'autoBackup' => false, 'projectPath' => self::$fixturesDirectory, 'migrationVersion' => \Curry_Core::MIGRATION_VERSION, 'template' => array('root' => self::$fixturesDirectory . '/templates', 'options' => array('cache' => false)), 'propel' => array('conf' => self::$fixturesDirectory . '/propel/build/conf/curry-conf.php', 'projectClassPath' => self::$fixturesDirectory . '/propel/build/classes'))));
     // Empty database
     $con = \Propel::getConnection();
     $con->beginTransaction();
     try {
         foreach (\Curry_Propel::getModels(false) as $model) {
             \PropelQuery::from($model)->deleteAll();
         }
         $con->commit();
     } catch (Exception $e) {
         $con->rollBack();
         throw $e;
     }
     $setup = new \Curry_Backend_Setup();
     $setup->saveConfiguration(array('template' => 'empty', 'admin' => array('username' => 'admin', 'password' => 'admin'), 'user' => array('username' => 'user', 'password' => 'user')));
 }
Exemplo n.º 15
0
 public function show(Request $request)
 {
     $modelClass = $this->modelClass;
     $items = array();
     if ($this['id'] === ':id' && $request->query->has('item')) {
         $pks = array_map(function ($i) {
             return json_decode($i, true);
         }, $request->query->get('item', array()));
         if ($pks && $this->parent instanceof AbstractBackend) {
             $items = \PropelQuery::from($this->parent->getModelClass())->findPks($pks)->getArrayCopy();
         }
     } else {
         $items = array($this->getSelection());
     }
     $items = array_filter($items, function ($item) use($modelClass) {
         return $item instanceof $modelClass;
     });
     if (!count($items)) {
         throw new \Exception('No item to delete');
     }
     $names = array_map(function ($item) {
         return method_exists($item, '__toString') ? '`' . htmlspecialchars((string) $item) . '`' : 'this item';
     }, $items);
     if ($request->isMethod('POST') && $request->request->get('do_delete')) {
         foreach ($items as $i => $item) {
             $pk = $item->getPrimaryKey();
             $item->delete();
             // Trigger update event
             //$this->createModelUpdateEvent($this->modelClass, $pk, 'delete');
             if ($item instanceof \Curry_ISearchable) {
                 \Curry_Backend_Indexer::removeItem($item);
             }
         }
         $this->addMainContent('<p>' . $names[$i] . ' has been deleted.</p>');
     } else {
         $this->addMainContent('<form method="post">' . '<input type="hidden" name="do_delete" value="1" />' . '<p>Do you really want to delete ' . join(', ', $names) . '?</p>' . '<button type="submit" class="btn btn-danger">Delete</button>' . '</form>');
     }
     return parent::render();
 }
 public function testToArray()
 {
     $books = PropelQuery::from('Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find();
     $booksArray = $books->toArray();
     $this->assertEquals(4, count($booksArray));
     $bookObjects = PropelQuery::from('Book')->find();
     foreach ($booksArray as $key => $book) {
         $this->assertEquals($bookObjects[$key]->toArray(), $book);
     }
     $booksArray = $books->toArray();
     $keys = array(0, 1, 2, 3);
     $this->assertEquals($keys, array_keys($booksArray));
     $booksArray = $books->toArray(null, true);
     $keys = array('Book_0', 'Book_1', 'Book_2', 'Book_3');
     $this->assertEquals($keys, array_keys($booksArray));
     $booksArray = $books->toArray('Title');
     $keys = array('Harry Potter and the Order of the Phoenix', 'Quicksilver', 'Don Juan', 'The Tin Drum');
     $this->assertEquals($keys, array_keys($booksArray));
     $booksArray = $books->toArray('Title', true);
     $keys = array('Book_Harry Potter and the Order of the Phoenix', 'Book_Quicksilver', 'Book_Don Juan', 'Book_The Tin Drum');
     $this->assertEquals($keys, array_keys($booksArray));
 }
Exemplo n.º 17
0
 /**
  * @see sfValidatorBase
  */
 protected function doClean($values)
 {
     if (!is_array($values)) {
         throw new InvalidArgumentException('You must pass an array parameter to the clean() method (this validator can only be used as a post validator).');
     }
     if (!is_array($this->getOption('column'))) {
         $this->setOption('column', array($this->getOption('column')));
     }
     if (!is_array($field = $this->getOption('field'))) {
         $this->setOption('field', $field ? array($field) : array());
     }
     $fields = $this->getOption('field');
     $criteria = PropelQuery::from($this->getOption('model'));
     foreach ($this->getOption('query_methods') as $method) {
         $criteria->{$method}();
     }
     foreach ($this->getOption('column') as $i => $column) {
         $name = isset($fields[$i]) ? $fields[$i] : $column;
         if (!array_key_exists($name, $values)) {
             // one of the column has been removed from the form
             return $values;
         }
         $colName = call_user_func(array(constant($this->getOption('model') . '::PEER'), 'translateFieldName'), $column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
         $criteria->add($colName, $values[$name]);
     }
     $object = $criteria->findOne($this->getOption('connection'));
     // if no object or if we're updating the object, it's ok
     if (null === $object || $this->isUpdate($object, $values)) {
         return $values;
     }
     $error = new sfValidatorError($this, 'invalid', array('column' => implode(', ', $this->getOption('column'))));
     if ($this->getOption('throw_global_error')) {
         throw $error;
     }
     $columns = $this->getOption('column');
     throw new sfValidatorErrorSchema($this, array($columns[0] => $error));
 }
  /**
   * Sends messages using the given transport instance.
   *
   * @param Swift_Transport $transport         A transport instance
   * @param string[]        &$failedRecipients An array of failures by-reference
   *
   * @return int The number of sent emails
   */
  public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
  {
    $queryMethod = $this->method;
    $model = constant($this->model.'::PEER');
    $modelQuery = PropelQuery::from($this->model);
    $objects = $modelQuery->$queryMethod()->limit($this->getMessageLimit())->find();
    
    if (!$transport->isStarted())
    {
      $transport->start();
    }

    $method = 'get'.call_user_func(array($model, 'translateFieldName'), $this->column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
    $count = 0;
    $time = time();
    foreach ($objects as $object)
    {
      $message = unserialize($object->$method());
      try
      {
        $count += $transport->send($message, $failedRecipients);
        $object->mailSent();
      }
      catch (Exception $e)
      {
        $object->mailUnsent();
      }

      if ($this->getTimeLimit() && (time() - $time) >= $this->getTimeLimit())
      {
        break;
      }
    }

    return $count;
  }
Exemplo n.º 19
0
 /**
  * Initializes a secondary ModelCriteria object, to be later merged with the current object
  *
  * @see       ModelCriteria::endUse()
  * @param string $relationName        Relation name or alias
  * @param string $secondCriteriaClass Classname for the ModelCriteria to be used
  *
  * @return ModelCriteria The secondary criteria object
  *
  * @throws PropelException
  */
 public function useQuery($relationName, $secondaryCriteriaClass = null)
 {
     if (!isset($this->joins[$relationName])) {
         throw new PropelException('Unknown class or alias ' . $relationName);
     }
     $className = $this->joins[$relationName]->getTableMap()->getPhpName();
     if (null === $secondaryCriteriaClass) {
         $secondaryCriteria = PropelQuery::from($className);
     } else {
         $secondaryCriteria = new $secondaryCriteriaClass();
     }
     if ($className != $relationName) {
         $secondaryCriteria->setModelAlias($relationName, $relationName == $this->joins[$relationName]->getRelationMap()->getName() ? false : true);
     }
     $secondaryCriteria->setPrimaryCriteria($this, $this->joins[$relationName]);
     return $secondaryCriteria;
 }
Exemplo n.º 20
0
 /**
  * Add or update propel model item in search index.
  *
  * @param BaseObject $item
  * @param Zend_Search_Lucene_Interface $index
  * @param bool $removeOld
  * @return bool
  */
 public static function updateItem(BaseObject $item, Zend_Search_Lucene_Interface $index = null, $removeOld = true)
 {
     $model = get_class($item);
     try {
         if (!$index) {
             $index = \Curry\App::getInstance()->index;
         }
         if ($removeOld) {
             self::removeItem($item, $index);
         }
         $hasI18n = in_array('i18n', array_keys(PropelQuery::from($model)->getTableMap()->getBehaviors()));
         if ($hasI18n) {
             $translations = $item->{"get{$model}I18ns"}();
             foreach ($translations as $translation) {
                 $item->setLocale($translation->getLocale());
                 self::addSearchDocument($index, $item->getSearchDocument(), $item, $translation->getLocale());
             }
         } else {
             self::addSearchDocument($index, $item->getSearchDocument(), $item);
         }
         return true;
     } catch (Exception $e) {
         \Curry\App::getInstance()->logger->error($model . '(' . (string) $item . '): ' . $e->getMessage());
         return false;
     }
 }
Exemplo n.º 21
0
 /**
  * Get json response.
  *
  * @return mixed
  */
 public function getJson()
 {
     if (isPost() && isset($_POST['action'])) {
         return $this->runAction($_POST['action']);
     }
     if (!isset($_GET['key'])) {
         $root = \PropelQuery::from($this->model)->findRoot();
         return $root ? array($this->_objectToJson($root)) : array();
     } else {
         $parent = \PropelQuery::from($this->model)->findPk($_GET['key']);
         if (!$parent) {
             return array();
         }
         $p = $this->_objectToJson($parent);
         return $p['children'];
     }
 }
 public function testToKeyValue()
 {
     $books = PropelQuery::from('Book')->find();
     $expected = array();
     foreach ($books as $book) {
         $expected[$book->getTitle()] = $book->getISBN();
     }
     $booksArray = $books->toKeyValue('Title', 'ISBN');
     $this->assertEquals(4, count($booksArray));
     $this->assertEquals($expected, $booksArray, 'toKeyValue() turns the collection to an associative array');
     $expected = array();
     foreach ($books as $book) {
         $expected[$book->getISBN()] = $book->getTitle();
     }
     $booksArray = $books->toKeyValue('ISBN');
     $this->assertEquals($expected, $booksArray, 'toKeyValue() uses __toString() for the value if no second field name is passed');
     $expected = array();
     foreach ($books as $book) {
         $expected[$book->getId()] = $book->getTitle();
     }
     $booksArray = $books->toKeyValue();
     $this->assertEquals($expected, $booksArray, 'toKeyValue() uses primary key for the key and __toString() for the value if no field name is passed');
 }
 protected function prepareQuery($model, $columnMaps, $file)
 {
     $peerClass = "{$model}Peer";
     $tableMap = $peerClass::getTableMap();
     $q = PropelQuery::from($tableMap->getPhpName());
     $index = 0;
     foreach ($columnMaps as $column) {
         if ($index) {
             $q->_or();
         }
         if ($column->getType() == 'VARCHAR') {
             $q->where("{$tableMap->getPhpName()}.{$column->getPhpName()} = ?", $file);
         } else {
             $q->where("{$tableMap->getPhpName()}.{$column->getPhpName()} LIKE ?", '%' . $file . '%');
         }
         ++$index;
     }
     return $q;
 }
Exemplo n.º 24
0
 protected function createConsumerQuery()
 {
     return \PropelQuery::from($this->getConsumerClass());
 }
Exemplo n.º 25
0
 /**
  * Create the propel query class corresponding to your queryclass
  *
  * @return \ModelCriteria the queryClass
  */
 protected function createQuery()
 {
     return \PropelQuery::from($this->class);
 }
 /**
  * Makes an additional query to populate the objects related to the collection objects
  * by a certain relation
  *
  * @param     string    $relation Relation name (e.g. 'Book')
  * @param     Criteria  $criteria Optional Criteria object to filter the related object collection
  * @param     PropelPDO $con      Optional connection object
  *
  * @return    PropelObjectCollection the list of related objects
  */
 public function populateRelation($relation, $criteria = null, $con = null)
 {
     if (!Propel::isInstancePoolingEnabled()) {
         throw new PropelException('populateRelation() needs instance pooling to be enabled prior to populating the collection');
     }
     $relationMap = $this->getFormatter()->getTableMap()->getRelation($relation);
     $symRelationMap = $relationMap->getSymmetricalRelation();
     // query the db for the related objects
     $useMethod = 'use' . $symRelationMap->getName() . 'Query';
     $query = PropelQuery::from($relationMap->getRightTable()->getPhpName());
     if (null !== $criteria) {
         $query->mergeWith($criteria);
     }
     $relatedObjects = $query->{$useMethod}()->filterByPrimaryKeys($this->getPrimaryKeys())->endUse()->find($con);
     // associate the related objects to the main objects
     if ($relationMap->getType() == RelationMap::ONE_TO_MANY) {
         $getMethod = 'get' . $symRelationMap->getName();
         $addMethod = 'add' . $relationMap->getName();
         foreach ($relatedObjects as $object) {
             $mainObj = $object->{$getMethod}();
             // instance pool is used here to avoid a query
             $mainObj->{$addMethod}($object);
         }
     } elseif ($relationMap->getType() == RelationMap::MANY_TO_ONE) {
         // nothing to do; the instance pool will catch all calls to getRelatedObject()
         // and return the object in memory
     } else {
         throw new PropelException('populateRelation() does not support this relation type');
     }
     return $relatedObjects;
 }
 /**
  * Builds a Propel Criteria with processed values.
  *
  * Overload this method instead of {@link buildCriteria()} to avoid running
  * {@link processValues()} multiple times.
  *
  * @param  array $values
  *
  * @return Criteria
  */
 protected function doBuildCriteria(array $values)
 {
     $criteria = PropelQuery::from($this->getModelName());
     $peer = $criteria->getModelPeerName();
     $fields = $this->getFields();
     // add those fields that are not represented in getFields() with a null type
     $names = array_merge($fields, array_diff(array_keys($this->validatorSchema->getFields()), array_keys($fields)));
     $fields = array_merge($fields, array_combine($names, array_fill(0, count($names), null)));
     foreach ($fields as $field => $type) {
         if (!isset($values[$field]) || null === $values[$field] || '' === $values[$field]) {
             continue;
         }
         try {
             $ucField = call_user_func(array($peer, 'translateFieldName'), $field, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
             $isReal = true;
         } catch (Exception $e) {
             $ucField = self::camelize($field);
             $isReal = false;
         }
         if (method_exists($this, $method = sprintf('add%sColumnCriteria', $ucField))) {
             // FormFilter::add[ColumnName]Criteria
             $this->{$method}($criteria, $field, $values[$field]);
         } elseif ($isReal && method_exists($this, $method = sprintf('add%sCriteria', $type))) {
             // FormFilter::add[ColumnType]Criteria
             $this->{$method}($criteria, $field, $values[$field]);
         } elseif (method_exists($criteria, $method = sprintf('filterBy%s', $ucField))) {
             // ModelCriteria::filterBy[ColumnName]
             $criteria->{$method}($values[$field]);
         } else {
             $processed = false;
             try {
                 // is it an embedded flter ?
                 $form = $this->getEmbeddedForm($field);
                 $criteria->mergeWith($form->buildCriteria($values[$field]));
                 $processed = true;
             } catch (InvalidArgumentException $e) {
             }
             if (!$processed) {
                 // try with merged
                 foreach ($this->getMergedForms() as $form) {
                     if (array_key_exists($field, $form->getFields())) {
                         $criteria->mergeWith($form->buildCriteria(array($field => $values[$field])));
                         $processed = true;
                     }
                 }
             }
             if (!$processed) {
                 throw new LogicException(sprintf('You must define a "%s" method in the %s class to be able to filter with the "%s" field.', sprintf('filterBy%s', $ucField), get_class($criteria), $field));
             }
         }
     }
     return $criteria;
 }
Exemplo n.º 28
0
 /**
  * Show edit model form.
  *
  * @param string $modelClass
  */
 public function editModel($modelClass)
 {
     $pks = \PropelQuery::from($modelClass)->getTableMap()->getPrimaryKeys();
     $idParam = strtolower(reset($pks)->getName());
     $instance = isset($_GET[$idParam]) ? \PropelQuery::from($modelClass)->findPk($_GET[$idParam]) : null;
     if (!$instance) {
         $instance = new $modelClass();
     }
     $form = $this->getEditForm($modelClass, $instance);
     if (isPost() && $form->isValid($_POST)) {
         try {
             $this->fillObjectFromForm($form, $instance);
             $instance->save();
             if (isAjax()) {
                 self::returnPartial('');
             }
         } catch (\PropelException $e) {
             self::returnPartial($form->render() . '<p>' . $e->getMessage() . '</p>');
         }
     }
     if (isAjax()) {
         self::returnPartial($form);
     } else {
         $this->addMainContent($form);
     }
 }
Exemplo n.º 29
0
 /**
  * Makes an additional query to populate the objects related to the collection objects
  * by a certain relation
  *
  * @param string    $relation Relation name (e.g. 'Book')
  * @param Criteria  $criteria Optional Criteria object to filter the related object collection
  * @param PropelPDO $con      Optional connection object
  *
  * @return PropelObjectCollection The list of related objects
  *
  * @throws PropelException
  */
 public function populateRelation($relation, $criteria = null, $con = null)
 {
     if (!Propel::isInstancePoolingEnabled()) {
         throw new PropelException('populateRelation() needs instance pooling to be enabled prior to populating the collection');
     }
     $relationMap = $this->getFormatter()->getTableMap()->getRelation($relation);
     if ($this->isEmpty()) {
         // save a useless query and return an empty collection
         $coll = new PropelObjectCollection();
         $coll->setModel($relationMap->getRightTable()->getClassname());
         return $coll;
     }
     $symRelationMap = $relationMap->getSymmetricalRelation();
     $query = PropelQuery::from($relationMap->getRightTable()->getClassname());
     if (null !== $criteria) {
         $query->mergeWith($criteria);
     }
     // query the db for the related objects
     $filterMethod = 'filterBy' . $symRelationMap->getName();
     $relatedObjects = $query->{$filterMethod}($this)->find($con);
     if ($relationMap->getType() == RelationMap::ONE_TO_MANY) {
         // initialize the embedded collections of the main objects
         $relationName = $relationMap->getName();
         foreach ($this as $mainObj) {
             $mainObj->initRelation($relationName);
         }
         // associate the related objects to the main objects
         $getMethod = 'get' . $symRelationMap->getName();
         $addMethod = 'add' . $relationName;
         foreach ($relatedObjects as $object) {
             $mainObj = $object->{$getMethod}();
             // instance pool is used here to avoid a query
             $mainObj->{$addMethod}($object);
         }
         $relatedObjects->clearIterator();
     } elseif ($relationMap->getType() == RelationMap::MANY_TO_ONE) {
         // nothing to do; the instance pool will catch all calls to getRelatedObject()
         // and return the object in memory
     } else {
         throw new PropelException('populateRelation() does not support this relation type');
     }
     return $relatedObjects;
 }
Exemplo n.º 30
0
 /**
  * Run flexigrid commands.
  */
 protected function runCommands()
 {
     // execute commands before we return the list
     if (!isset($_POST['cmd'])) {
         return;
     }
     switch ($_POST['cmd']) {
         case 'delete':
             if (isset($_POST['id'])) {
                 $id = $_POST['id'];
                 PropelQuery::from($this->modelClass)->findPks(is_array($id) ? $id : array($id))->delete();
             }
             break;
         case 'reorder':
             if (isset($_POST['reorder'])) {
                 $reorder = array();
                 parse_str($_POST['reorder'], $reorder);
                 if (isset($this->columns['sort_index'])) {
                     // OLD SORTING METHOD
                     // get objects
                     $objs = array();
                     foreach ($reorder['row'] as $rowId) {
                         $objs[] = call_user_func(array($this->modelClass . 'Peer', 'retrieveByPk'), $rowId);
                     }
                     // get sort indices
                     $sortIndices = array();
                     foreach ($objs as $obj) {
                         $sortIndices[] = $obj->getSortIndex();
                     }
                     // sort our indices
                     sort($sortIndices);
                     // set new sort indices
                     $i = 0;
                     foreach ($objs as $obj) {
                         $obj->setSortIndex($sortIndices[$i++]);
                         $obj->save();
                     }
                 } else {
                     // get ranks
                     $objs = PropelQuery::from($this->modelClass)->findPks($reorder['row']);
                     // move all objs with null rank to the bottom
                     $ranks = array();
                     foreach ($objs as $obj) {
                         if ($obj->getRank() === null) {
                             $obj->insertAtBottom();
                             $obj->save();
                         }
                         $ranks[] = $obj->getRank();
                     }
                     // check for duplicate ranks
                     $dups = array_filter(array_count_values($ranks), create_function('$a', 'return $a > 1;'));
                     if ($dups) {
                         // Duplicate indices, move to bottom
                         $tmp = $this->tableMap->getBehaviors();
                         $scope = null;
                         if (strtolower($tmp['sortable']['use_scope']) == 'true') {
                             // need scope, find from one object
                             $scope = PropelQuery::from($this->modelClass)->findPk(reset($reorder['row']))->getScopeValue();
                         }
                         foreach ($dups as $rank => $f) {
                             $objs = PropelQuery::from($this->modelClass)->filterByRank($rank, $scope)->offset(1)->find();
                             foreach ($objs as $obj) {
                                 $obj->insertAtBottom();
                                 $obj->save();
                             }
                         }
                         $ranks = Curry_Array::objectsToArray($objs, null, 'getRank');
                     }
                     // sort our indices
                     sort($ranks);
                     // reorder
                     PropelQuery::from($this->modelClass)->reorder(array_combine($reorder['row'], $ranks));
                 }
             }
             break;
     }
 }