Started to add tests (almost green!)

This commit is contained in:
Kévin Gomez 2013-11-04 00:09:31 +00:00
parent b1217c0e5d
commit 1b19c108ef
14 changed files with 2865 additions and 5 deletions

View file

@ -3,6 +3,7 @@
namespace Propel\PropelBundle\Request\ParamConverter;
use Propel\PropelBundle\Util\PropelInflector;
use Propel\Runtime\ActiveQuery\Criteria;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
@ -102,7 +103,6 @@ class PropelParamConverter implements ParamConverterInterface
$options = $converterOption[$configuration->getName()];
}
}
if (isset($options['mapping'])) {
// We use the mapping for calling findPk or filterBy
foreach ($options['mapping'] as $routeParam => $column) {
@ -115,10 +115,14 @@ class PropelParamConverter implements ParamConverterInterface
}
}
} else {
$this->exclude = isset($options['exclude'])? $options['exclude'] : array();
$this->exclude = isset($options['exclude']) ? $options['exclude'] : array();
$this->filters = $request->attributes->all();
}
if (array_key_exists($configuration->getName(), $this->filters)) {
unset($this->filters[$configuration->getName()]);
}
$this->withs = isset($options['with'])? is_array($options['with'])? $options['with'] : array($options['with']) : array();
// find by Pk
@ -266,11 +270,11 @@ class PropelParamConverter implements ParamConverterInterface
{
switch (trim(str_replace(array('_', 'JOIN'), '', strtoupper($with[1])))) {
case 'LEFT':
return \Criteria::LEFT_JOIN;
return Criteria::LEFT_JOIN;
case 'RIGHT':
return \Criteria::RIGHT_JOIN;
return Criteria::RIGHT_JOIN;
case 'INNER':
return \Criteria::INNER_JOIN;
return Criteria::INNER_JOIN;
}
throw new \Exception(sprintf('ParamConverter : "with" parameter "%s" is invalid,

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,492 @@
<?php
namespace Propel\PropelBundle\Tests\Fixtures\Model\Base;
use \Exception;
use \PDO;
use Propel\PropelBundle\Tests\Fixtures\Model\Book as ChildBook;
use Propel\PropelBundle\Tests\Fixtures\Model\BookQuery as ChildBookQuery;
use Propel\PropelBundle\Tests\Fixtures\Model\Map\BookTableMap;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\ActiveQuery\ModelJoin;
use Propel\Runtime\Collection\Collection;
use Propel\Runtime\Collection\ObjectCollection;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
/**
* Base class that represents a query for the 'book' table.
*
*
*
* @method ChildBookQuery orderById($order = Criteria::ASC) Order by the id column
* @method ChildBookQuery orderByTitle($order = Criteria::ASC) Order by the title column
* @method ChildBookQuery orderByIsbn($order = Criteria::ASC) Order by the ISBN column
* @method ChildBookQuery orderByAuthorId($order = Criteria::ASC) Order by the author_id column
*
* @method ChildBookQuery groupById() Group by the id column
* @method ChildBookQuery groupByTitle() Group by the title column
* @method ChildBookQuery groupByIsbn() Group by the ISBN column
* @method ChildBookQuery groupByAuthorId() Group by the author_id column
*
* @method ChildBookQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
* @method ChildBookQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
* @method ChildBookQuery innerJoin($relation) Adds a INNER JOIN clause to the query
*
* @method ChildBook findOne(ConnectionInterface $con = null) Return the first ChildBook matching the query
* @method ChildBook findOneOrCreate(ConnectionInterface $con = null) Return the first ChildBook matching the query, or a new ChildBook object populated from the query conditions when no match is found
*
* @method ChildBook findOneById(int $id) Return the first ChildBook filtered by the id column
* @method ChildBook findOneByTitle(string $title) Return the first ChildBook filtered by the title column
* @method ChildBook findOneByIsbn(string $ISBN) Return the first ChildBook filtered by the ISBN column
* @method ChildBook findOneByAuthorId(int $author_id) Return the first ChildBook filtered by the author_id column
*
* @method array findById(int $id) Return ChildBook objects filtered by the id column
* @method array findByTitle(string $title) Return ChildBook objects filtered by the title column
* @method array findByIsbn(string $ISBN) Return ChildBook objects filtered by the ISBN column
* @method array findByAuthorId(int $author_id) Return ChildBook objects filtered by the author_id column
*
*/
abstract class BookQuery extends ModelCriteria
{
/**
* Initializes internal state of \Acme\DemoBundle\Model\Base\BookQuery object.
*
* @param string $dbName The database name
* @param string $modelName The phpName of a model, e.g. 'Book'
* @param string $modelAlias The alias for the model in this query, e.g. 'b'
*/
public function __construct($dbName = 'default', $modelName = '\\Propel\\PropelBundle\\Tests\\Fixtures\\Model\\Book', $modelAlias = null)
{
parent::__construct($dbName, $modelName, $modelAlias);
}
/**
* Returns a new ChildBookQuery object.
*
* @param string $modelAlias The alias of a model in the query
* @param Criteria $criteria Optional Criteria to build the query from
*
* @return ChildBookQuery
*/
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof \Propel\PropelBundle\Tests\Fixtures\Model\BookQuery) {
return $criteria;
}
$query = new \Propel\PropelBundle\Tests\Fixtures\Model\BookQuery();
if (null !== $modelAlias) {
$query->setModelAlias($modelAlias);
}
if ($criteria instanceof Criteria) {
$query->mergeWith($criteria);
}
return $query;
}
/**
* Find object by primary key.
* Propel uses the instance pool to skip the database if the object exists.
* Go fast if the query is untouched.
*
* <code>
* $obj = $c->findPk(12, $con);
* </code>
*
* @param mixed $key Primary key to use for the query
* @param ConnectionInterface $con an optional connection object
*
* @return ChildBook|array|mixed the result, formatted by the current formatter
*/
public function findPk($key, $con = null)
{
if ($key === null) {
return null;
}
if ((null !== ($obj = BookTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) {
// the object is already in the instance pool
return $obj;
}
if ($con === null) {
$con = Propel::getServiceContainer()->getReadConnection(BookTableMap::DATABASE_NAME);
}
$this->basePreSelect($con);
if ($this->formatter || $this->modelAlias || $this->with || $this->select
|| $this->selectColumns || $this->asColumns || $this->selectModifiers
|| $this->map || $this->having || $this->joins) {
return $this->findPkComplex($key, $con);
} else {
return $this->findPkSimple($key, $con);
}
}
/**
* Find object by primary key using raw SQL to go fast.
* Bypass doSelect() and the object formatter by using generated code.
*
* @param mixed $key Primary key to use for the query
* @param ConnectionInterface $con A connection object
*
* @return ChildBook A model object, or null if the key is not found
*/
protected function findPkSimple($key, $con)
{
$sql = 'SELECT ID, TITLE, ISBN, AUTHOR_ID FROM book WHERE ID = :p0';
try {
$stmt = $con->prepare($sql);
$stmt->bindValue(':p0', $key, PDO::PARAM_INT);
$stmt->execute();
} catch (Exception $e) {
Propel::log($e->getMessage(), Propel::LOG_ERR);
throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e);
}
$obj = null;
if ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
$obj = new ChildBook();
$obj->hydrate($row);
BookTableMap::addInstanceToPool($obj, (string) $key);
}
$stmt->closeCursor();
return $obj;
}
/**
* Find object by primary key.
*
* @param mixed $key Primary key to use for the query
* @param ConnectionInterface $con A connection object
*
* @return ChildBook|array|mixed the result, formatted by the current formatter
*/
protected function findPkComplex($key, $con)
{
// As the query uses a PK condition, no limit(1) is necessary.
$criteria = $this->isKeepQuery() ? clone $this : $this;
$dataFetcher = $criteria
->filterByPrimaryKey($key)
->doSelect($con);
return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher);
}
/**
* Find objects by primary key
* <code>
* $objs = $c->findPks(array(12, 56, 832), $con);
* </code>
* @param array $keys Primary keys to use for the query
* @param ConnectionInterface $con an optional connection object
*
* @return ObjectCollection|array|mixed the list of results, formatted by the current formatter
*/
public function findPks($keys, $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getReadConnection($this->getDbName());
}
$this->basePreSelect($con);
$criteria = $this->isKeepQuery() ? clone $this : $this;
$dataFetcher = $criteria
->filterByPrimaryKeys($keys)
->doSelect($con);
return $criteria->getFormatter()->init($criteria)->format($dataFetcher);
}
/**
* Filter the query by primary key
*
* @param mixed $key Primary key to use for the query
*
* @return ChildBookQuery The current query, for fluid interface
*/
public function filterByPrimaryKey($key)
{
return $this->addUsingAlias(BookTableMap::ID, $key, Criteria::EQUAL);
}
/**
* Filter the query by a list of primary keys
*
* @param array $keys The list of primary key to use for the query
*
* @return ChildBookQuery The current query, for fluid interface
*/
public function filterByPrimaryKeys($keys)
{
return $this->addUsingAlias(BookTableMap::ID, $keys, Criteria::IN);
}
/**
* Filter the query on the id column
*
* Example usage:
* <code>
* $query->filterById(1234); // WHERE id = 1234
* $query->filterById(array(12, 34)); // WHERE id IN (12, 34)
* $query->filterById(array('min' => 12)); // WHERE id > 12
* </code>
*
* @param mixed $id The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return ChildBookQuery The current query, for fluid interface
*/
public function filterById($id = null, $comparison = null)
{
if (is_array($id)) {
$useMinMax = false;
if (isset($id['min'])) {
$this->addUsingAlias(BookTableMap::ID, $id['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($id['max'])) {
$this->addUsingAlias(BookTableMap::ID, $id['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BookTableMap::ID, $id, $comparison);
}
/**
* Filter the query on the title column
*
* Example usage:
* <code>
* $query->filterByTitle('fooValue'); // WHERE title = 'fooValue'
* $query->filterByTitle('%fooValue%'); // WHERE title LIKE '%fooValue%'
* </code>
*
* @param string $title The value to use as filter.
* Accepts wildcards (* and % trigger a LIKE)
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return ChildBookQuery The current query, for fluid interface
*/
public function filterByTitle($title = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($title)) {
$comparison = Criteria::IN;
} elseif (preg_match('/[\%\*]/', $title)) {
$title = str_replace('*', '%', $title);
$comparison = Criteria::LIKE;
}
}
return $this->addUsingAlias(BookTableMap::TITLE, $title, $comparison);
}
/**
* Filter the query on the ISBN column
*
* Example usage:
* <code>
* $query->filterByIsbn('fooValue'); // WHERE ISBN = 'fooValue'
* $query->filterByIsbn('%fooValue%'); // WHERE ISBN LIKE '%fooValue%'
* </code>
*
* @param string $isbn The value to use as filter.
* Accepts wildcards (* and % trigger a LIKE)
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return ChildBookQuery The current query, for fluid interface
*/
public function filterByIsbn($isbn = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($isbn)) {
$comparison = Criteria::IN;
} elseif (preg_match('/[\%\*]/', $isbn)) {
$isbn = str_replace('*', '%', $isbn);
$comparison = Criteria::LIKE;
}
}
return $this->addUsingAlias(BookTableMap::ISBN, $isbn, $comparison);
}
/**
* Filter the query on the author_id column
*
* Example usage:
* <code>
* $query->filterByAuthorId(1234); // WHERE author_id = 1234
* $query->filterByAuthorId(array(12, 34)); // WHERE author_id IN (12, 34)
* $query->filterByAuthorId(array('min' => 12)); // WHERE author_id > 12
* </code>
*
* @see filterByAuthor()
*
* @param mixed $authorId The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return ChildBookQuery The current query, for fluid interface
*/
public function filterByAuthorId($authorId = null, $comparison = null)
{
if (is_array($authorId)) {
$useMinMax = false;
if (isset($authorId['min'])) {
$this->addUsingAlias(BookTableMap::AUTHOR_ID, $authorId['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($authorId['max'])) {
$this->addUsingAlias(BookTableMap::AUTHOR_ID, $authorId['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(BookTableMap::AUTHOR_ID, $authorId, $comparison);
}
/**
* Adds a JOIN clause to the query using the Author relation
*
* @param string $relationAlias optional alias for the relation
* @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
*
* @return ChildBookQuery The current query, for fluid interface
*/
public function joinAuthor($relationAlias = null, $joinType = Criteria::LEFT_JOIN)
{
$tableMap = $this->getTableMap();
$relationMap = $tableMap->getRelation('Author');
// create a ModelJoin object for this join
$join = new ModelJoin();
$join->setJoinType($joinType);
$join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias);
if ($previousJoin = $this->getPreviousJoin()) {
$join->setPreviousJoin($previousJoin);
}
// add the ModelJoin to the current object
if ($relationAlias) {
$this->addAlias($relationAlias, $relationMap->getRightTable()->getName());
$this->addJoinObject($join, $relationAlias);
} else {
$this->addJoinObject($join, 'Author');
}
return $this;
}
/**
* Exclude object from result
*
* @param ChildBook $book Object to remove from the list of results
*
* @return ChildBookQuery The current query, for fluid interface
*/
public function prune($book = null)
{
if ($book) {
$this->addUsingAlias(BookTableMap::ID, $book->getId(), Criteria::NOT_EQUAL);
}
return $this;
}
/**
* Deletes all rows from the book table.
*
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver).
*/
public function doDeleteAll(ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(BookTableMap::DATABASE_NAME);
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->beginTransaction();
$affectedRows += parent::doDeleteAll($con);
// Because this db requires some delete cascade/set null emulation, we have to
// clear the cached instance *after* the emulation has happened (since
// instances get re-added by the select statement contained therein).
BookTableMap::clearInstancePool();
BookTableMap::clearRelatedInstancePool();
$con->commit();
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
return $affectedRows;
}
/**
* Performs a DELETE on the database, given a ChildBook or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or ChildBook object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public function delete(ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(BookTableMap::DATABASE_NAME);
}
$criteria = $this;
// Set the correct dbName
$criteria->setDbName(BookTableMap::DATABASE_NAME);
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->beginTransaction();
BookTableMap::removeInstanceFromPool($criteria);
$affectedRows += ModelCriteria::delete($con);
BookTableMap::clearRelatedInstancePool();
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
} // BookQuery

View file

@ -0,0 +1,10 @@
<?php
namespace Propel\PropelBundle\Tests\Fixtures\Model;
use Propel\PropelBundle\Tests\Fixtures\Model\Base\Book as BaseBook;
class Book extends BaseBook
{
}

View file

@ -0,0 +1,95 @@
<?php
namespace Propel\PropelBundle\Tests\Fixtures\Model;
use Propel\PropelBundle\Tests\Fixtures\Model\Base\BookQuery as BaseBookQuery;
use Propel\PropelBundle\Tests\Fixtures\Model\Book;
/**
* Skeleton subclass for performing query and update operations on the 'book' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
*/
class BookQuery extends BaseBookQuery
{
private $bySlug = false;
private $byAuthorSlug = false;
/**
* fake for test
*/
public function findPk($key, $con = null)
{
if (1 === $key) {
$book = new Book();
$book->setId(1);
return $book;
}
return null;
}
/**
* fake for test
*/
public function filterByAuthorSlug($slug = null, $comparison = null)
{
if ('my-author' === $slug) {
$this->byAuthorSlug = true;
}
return $this;
}
/**
* fake for test
*/
public function filterBySlug($slug = null, $comparison = null)
{
if ('my-book' == $slug) {
$this->bySlug = true;
}
return $this;
}
/**
* fake for test
*/
public function filterByName($name = null, $comparison = null)
{
throw new \Exception('Test should never call this method');
}
/**
* fake for test
*/
public function findOne($con = null)
{
if (true === $this->bySlug) {
$book = new Book();
$book->setId(1);
$book->setName('My Book');
$book->setSlug('my-book');
return $book;
} elseif (true === $this->byAuthorSlug) {
$book = new Book();
$book->setId(2);
$book->setName('My Kewl Book');
$book->setSlug('my-kewl-book');
return $book;
}
return null;
}
} // BookQuery

View file

@ -0,0 +1,433 @@
<?php
namespace Propel\PropelBundle\Tests\Fixtures\Model\Map;
use Acme\DemoBundle\Model\Book;
use Acme\DemoBundle\Model\BookQuery;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\InstancePoolTrait;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Map\RelationMap;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Map\TableMapTrait;
/**
* This class defines the structure of the 'book' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
*/
class BookTableMap extends TableMap
{
use InstancePoolTrait;
use TableMapTrait;
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'src.Acme.DemoBundle.Model.Map.BookTableMap';
/**
* The default database name for this class
*/
const DATABASE_NAME = 'default';
/**
* The table name for this class
*/
const TABLE_NAME = 'book';
/**
* The related Propel class for this table
*/
const OM_CLASS = '\\Propel\\PropelBundle\\Tests\\Fixtures\\Model\\Book';
/**
* A class that can be returned by this tableMap
*/
const CLASS_DEFAULT = 'src.Acme.DemoBundle.Model.Book';
/**
* The total number of columns
*/
const NUM_COLUMNS = 5;
/**
* The number of lazy-loaded columns
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS)
*/
const NUM_HYDRATE_COLUMNS = 5;
/**
* the column name for the ID field
*/
const ID = 'book.ID';
/**
* the column name for the NAME field
*/
const NAME = 'book.NAME';
/**
* the column name for the SLUG field
*/
const SLUG = 'book.SLUG';
/**
* the column name for the ISBN field
*/
const ISBN = 'book.ISBN';
/**
* the column name for the AUTHOR_ID field
*/
const AUTHOR_ID = 'book.AUTHOR_ID';
/**
* The default string format for model objects of the related table
*/
const DEFAULT_STRING_FORMAT = 'YAML';
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
self::TYPE_PHPNAME => array('Id', 'Name', 'Slug', 'Isbn', 'AuthorId', ),
self::TYPE_STUDLYPHPNAME => array('id', 'name', 'slug', 'isbn', 'authorId', ),
self::TYPE_COLNAME => array(BookTableMap::ID, BookTableMap::NAME, BookTableMap::SLUG, BookTableMap::ISBN, BookTableMap::AUTHOR_ID, ),
self::TYPE_RAW_COLNAME => array('ID', 'NAME', 'SLUG', 'ISBN', 'AUTHOR_ID', ),
self::TYPE_FIELDNAME => array('id', 'name', 'slug', 'ISBN', 'author_id', ),
self::TYPE_NUM => array(0, 1, 2, 3, 4, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0
*/
protected static $fieldKeys = array (
self::TYPE_PHPNAME => array('Id' => 0, 'Name' => 1, 'Slug' => 2, 'Isbn' => 3, 'AuthorId' => 4, ),
self::TYPE_STUDLYPHPNAME => array('id' => 0, 'name' => 1, 'slug' => 2, 'isbn' => 3, 'authorId' => 4, ),
self::TYPE_COLNAME => array(BookTableMap::ID => 0, BookTableMap::NAME => 1, BookTableMap::SLUG => 2, BookTableMap::ISBN => 3, BookTableMap::AUTHOR_ID => 4, ),
self::TYPE_RAW_COLNAME => array('ID' => 0, 'NAME' => 1, 'SLUG' => 2, 'ISBN' => 3, 'AUTHOR_ID' => 4, ),
self::TYPE_FIELDNAME => array('id' => 0, 'name' => 1, 'slug' => 2, 'ISBN' => 3, 'author_id' => 4, ),
self::TYPE_NUM => array(0, 1, 2, 3, 4, )
);
/**
* Initialize the table attributes and columns
* Relations are not initialized by this method since they are lazy loaded
*
* @return void
* @throws PropelException
*/
public function initialize()
{
// attributes
$this->setName('book');
$this->setPhpName('Book');
$this->setClassName('\\Propel\\PropelBundle\\Tests\\Fixtures\\Model\\Book');
$this->setPackage('src.Acme.DemoBundle.Model');
$this->setUseIdGenerator(true);
// columns
$this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null);
$this->addColumn('NAME', 'Name', 'VARCHAR', false, 100, null);
$this->addColumn('SLUG', 'Slug', 'VARCHAR', false, 100, null);
$this->getColumn('NAME', false)->setPrimaryString(true);
$this->addColumn('ISBN', 'Isbn', 'VARCHAR', false, 20, null);
} // initialize()
/**
* Build the RelationMap objects for this table relationships
*/
public function buildRelations()
{
} // buildRelations()
/**
* Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
*
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, a serialize()d version of the primary key will be returned.
*
* @param array $row resultset row.
* @param int $offset The 0-based offset for reading from the resultset row.
* @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME
* TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM
*/
public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
{
// If the PK cannot be derived from the row, return NULL.
if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) {
return null;
}
return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)];
}
/**
* Retrieves the primary key from the DB resultset row
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, an array of the primary key columns will be returned.
*
* @param array $row resultset row.
* @param int $offset The 0-based offset for reading from the resultset row.
* @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME
* TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM
*
* @return mixed The primary key of the row
*/
public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
{
return (int) $row[
$indexType == TableMap::TYPE_NUM
? 0 + $offset
: self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)
];
}
/**
* The class that the tableMap will make instances of.
*
* If $withPrefix is true, the returned path
* uses a dot-path notation which is translated into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @param boolean $withPrefix Whether or not to return the path with the class name
* @return string path.to.ClassName
*/
public static function getOMClass($withPrefix = true)
{
return $withPrefix ? BookTableMap::CLASS_DEFAULT : BookTableMap::OM_CLASS;
}
/**
* Populates an object of the default type or an object that inherit from the default.
*
* @param array $row row returned by DataFetcher->fetch().
* @param int $offset The 0-based offset for reading from the resultset row.
* @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType().
One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME
* TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return array (Book object, last column rank)
*/
public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
{
$key = BookTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType);
if (null !== ($obj = BookTableMap::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj->hydrate($row, $offset, true); // rehydrate
$col = $offset + BookTableMap::NUM_HYDRATE_COLUMNS;
} else {
$cls = BookTableMap::OM_CLASS;
$obj = new $cls();
$col = $obj->hydrate($row, $offset, false, $indexType);
BookTableMap::addInstanceToPool($obj, $key);
}
return array($obj, $col);
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @param DataFetcherInterface $dataFetcher
* @return array
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(DataFetcherInterface $dataFetcher)
{
$results = array();
// set the class once to avoid overhead in the loop
$cls = static::getOMClass(false);
// populate the object(s)
while ($row = $dataFetcher->fetch()) {
$key = BookTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType());
if (null !== ($obj = BookTableMap::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj->hydrate($row, 0, true); // rehydrate
$results[] = $obj;
} else {
$obj = new $cls();
$obj->hydrate($row);
$results[] = $obj;
BookTableMap::addInstanceToPool($obj, $key);
} // if key exists
}
return $results;
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param Criteria $criteria object containing the columns to add.
* @param string $alias optional table alias
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria, $alias = null)
{
if (null === $alias) {
$criteria->addSelectColumn(BookTableMap::ID);
$criteria->addSelectColumn(BookTableMap::NAME);
$criteria->addSelectColumn(BookTableMap::SLUG);
$criteria->addSelectColumn(BookTableMap::ISBN);
$criteria->addSelectColumn(BookTableMap::AUTHOR_ID);
} else {
$criteria->addSelectColumn($alias . '.ID');
$criteria->addSelectColumn($alias . '.NAME');
$criteria->addSelectColumn($alias . '.SLUG');
$criteria->addSelectColumn($alias . '.ISBN');
$criteria->addSelectColumn($alias . '.AUTHOR_ID');
}
}
/**
* Returns the TableMap related to this object.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getServiceContainer()->getDatabaseMap(BookTableMap::DATABASE_NAME)->getTable(BookTableMap::TABLE_NAME);
}
/**
* Add a TableMap instance to the database for this tableMap class.
*/
public static function buildTableMap()
{
$dbMap = Propel::getServiceContainer()->getDatabaseMap(BookTableMap::DATABASE_NAME);
if (!$dbMap->hasTable(BookTableMap::TABLE_NAME)) {
$dbMap->addTableObject(new BookTableMap());
}
}
/**
* Performs a DELETE on the database, given a Book or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or Book object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(BookTableMap::DATABASE_NAME);
}
if ($values instanceof Criteria) {
// rename for clarity
$criteria = $values;
} elseif ($values instanceof \Acme\DemoBundle\Model\Book) { // it's a model object
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(BookTableMap::DATABASE_NAME);
$criteria->add(BookTableMap::ID, (array) $values, Criteria::IN);
}
$query = BookQuery::create()->mergeWith($criteria);
if ($values instanceof Criteria) { BookTableMap::clearInstancePool();
} elseif (!is_object($values)) { // it's a primary key, or an array of pks
foreach ((array) $values as $singleval) { BookTableMap::removeInstanceFromPool($singleval);
}
}
return $query->delete($con);
}
/**
* Deletes all rows from the book table.
*
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll(ConnectionInterface $con = null)
{
return BookQuery::create()->doDeleteAll($con);
}
/**
* Performs an INSERT on the database, given a Book or Criteria object.
*
* @param mixed $criteria Criteria or Book object containing data that is used to create the INSERT statement.
* @param ConnectionInterface $con the ConnectionInterface connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($criteria, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(BookTableMap::DATABASE_NAME);
}
if ($criteria instanceof Criteria) {
$criteria = clone $criteria; // rename for clarity
} else {
$criteria = $criteria->buildCriteria(); // build Criteria from Book object
}
if ($criteria->containsKey(BookTableMap::ID) && $criteria->keyContainsValue(BookTableMap::ID) ) {
throw new PropelException('Cannot insert a value for auto-increment primary key ('.BookTableMap::ID.')');
}
// Set the correct dbName
$query = BookQuery::create()->mergeWith($criteria);
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->beginTransaction();
$pk = $query->doInsert($con);
$con->commit();
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
return $pk;
}
} // BookTableMap
// This is the static code needed to register the TableMap for this table with the main Propel class.
//
BookTableMap::buildTableMap();

21
Tests/Fixtures/schema.xml Normal file
View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<database name="bookstore" defaultIdMethod="native">
<table name="book" description="Book Table">
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Book Id" />
<column name="title" type="VARCHAR" required="true" description="Book Title" primaryString="true" />
<column name="isbn" required="true" type="VARCHAR" size="24" phpName="ISBN" description="ISBN Number" primaryString="false" />
<column name="price" required="false" type="FLOAT" description="Price of the book." />
<column name="publisher_id" required="false" type="INTEGER" description="Foreign Key Publisher" />
<column name="author_id" required="false" type="INTEGER" description="Foreign Key Author" />
<validator column="title" translate="none">
<rule name="unique" message="Book title already in database." />
<rule name="minLength" value="10" message="Book title must be more than ${value} characters long." />
<rule name="maxLength" value="255" message="Book title must not be longer than ${value} characters." />
</validator>
<validator column="isbn" translate="none">
<rule name="class" class="bookstore.validator.ISBNValidator" message="ISBN does not validate!"/>
</validator>
</table>
</database>

View file

@ -0,0 +1 @@
This is a schema.xml

View file

@ -0,0 +1,389 @@
<?php
namespace Propel\PropelBundle\Tests\Request\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Propel\PropelBundle\Request\ParamConverter\PropelParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Propel\Runtime\Propel;
use Propel\PropelBundle\Tests\TestCase;
use Propel\Generator\Util\QuickBuilder;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class PropelParamConverterTest extends TestCase
{
protected $con;
public function setUp()
{
parent::setUp();
if (!interface_exists('Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface')) {
$this->markTestSkipped('SensioFrameworkExtraBundle is not available.');
}
Propel::disableInstancePooling();
}
public function tearDown()
{
Propel::enableInstancePooling();
if ($this->con) {
$this->con->useDebug(false);
}
}
public function testParamConverterSupport()
{
$paramConverter = new PropelParamConverter();
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book'));
$this->assertTrue($paramConverter->supports($configuration), 'param converter should support propel class');
$configuration = new ParamConverter(array('class' =>'fakeClass'));
$this->assertFalse($paramConverter->supports($configuration), 'param converter should not support wrong class');
$configuration = new ParamConverter(array('class' =>'Propel\PropelBundle\Tests\TestCase'));
$this->assertFalse($paramConverter->supports($configuration), 'param converter should not support wrong class');
}
public function testParamConverterFindPk()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('id' => 1, 'book' => null));
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book'));
$paramConverter->apply($request, $configuration);
$this->assertInstanceOf(
'Propel\PropelBundle\Tests\Fixtures\Model\Book', $request->attributes->get('book'),
'param "book" should be an instance of "Propel\PropelBundle\Tests\Fixtures\Model\Book"'
);
}
/**
* @expectedException Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testParamConverterFindPkNotFound()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('id' => 2, 'book' => null));
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book'));
$paramConverter->apply($request, $configuration);
}
public function testParamConverterFindSlug()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('slug' => 'my-book', 'book' => null));
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book'));
$paramConverter->apply($request, $configuration);
$this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\Model\Book', $request->attributes->get('book'),
'param "book" should be an instance of "Propel\PropelBundle\Tests\Fixtures\Model\Book"');
}
public function testParamConverterFindCamelCasedSlug()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('author_slug' => 'my-author', 'slug' => 'my-kewl-book', 'book' => null));
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book'));
$paramConverter->apply($request, $configuration);
$this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\Model\Book',$request->attributes->get('book'),
'param "book" should be an instance of "Propel\PropelBundle\Tests\Fixtures\Model\Book"');
}
/**
* @expectedException Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testParamConverterFindSlugNotFound()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('slug' => 'my-foo', 'book' => null));
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book'));
$paramConverter->apply($request, $configuration);
}
public function testParamConverterFindBySlugNotByName()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('slug' => 'my-book', 'name' => 'foo', 'book' => null));
$configuration = new ParamConverter(array(
'class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book',
'options' => array('exclude' => array('name'))));
$paramConverter->apply($request, $configuration);
$this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\Model\Book',$request->attributes->get('book'),
'param "book" should be an instance of "Propel\PropelBundle\Tests\Fixtures\Model\Book"');
}
/**
* @expectedException LogicException
*/
public function testParamConverterFindByAllParamExcluded()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('slug' => 'my-book', 'name' => 'foo', 'book' => null));
$configuration = new ParamConverter(array(
'class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book',
'options' => array('exclude' => array('name', 'slug'))));
$paramConverter->apply($request, $configuration);
$this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\Model\Book',$request->attributes->get('book'),
'param "book" should be an instance of "Propel\PropelBundle\Tests\Fixtures\Model\Book"');
}
/**
* @expectedException LogicException
*/
public function testParamConverterFindByIdExcluded()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('id' => '1234', 'book' => null));
$configuration = new ParamConverter(array(
'class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book',
'options' => array('exclude' => array('id'))));
$paramConverter->apply($request, $configuration);
$this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\Model\Book',$request->attributes->get('book'),
'param "book" should be an instance of "Propel\PropelBundle\Tests\Fixtures\Model\Book"');
}
/**
* @expectedException LogicException
*/
public function testParamConverterFindLogicError()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('book' => null));
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book'));
$paramConverter->apply($request, $configuration);
}
public function testParamConverterFindWithOptionalParam()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('book' => null));
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book', 'name' => 'book'));
$configuration->setIsOptional(true);
$paramConverter->apply($request, $configuration);
$this->assertNull($request->attributes->get('book'),
'param "book" should be null if book is not found and the parameter is optional');
}
public function testParamConverterFindWithMapping()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('toto' => 1, 'book' => null));
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book',
'name' => 'book',
'options' => array('mapping' => array('toto' => 'id'))
));
$paramConverter->apply($request, $configuration);
$this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\Model\Book',$request->attributes->get('book'),
'param "book" should be an instance of "Propel\PropelBundle\Tests\Fixtures\Model\Book"');
}
public function testParamConverterFindSlugWithMapping()
{
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('slugParam_special' => 'my-book', 'book' => null));
$configuration = new ParamConverter(array('class' => 'Propel\PropelBundle\Tests\Fixtures\Model\Book',
'name' => 'book',
'options' => array('mapping' => array('slugParam_special' => 'slug'))
));
$paramConverter->apply($request, $configuration);
$this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\Model\Book',$request->attributes->get('book'),
'param "book" should be an instance of "Propel\PropelBundle\Tests\Fixtures\Model\Book"');
}
public function testParamConvertWithOptionWith()
{
$this->loadFixtures();
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('id' => 1, 'book' => null));
$configuration = new ParamConverter(array(
'class' => 'Propel\PropelBundle\Tests\Request\ParamConverter\MyBook',
'name' => 'book',
'options' => array(
'with' => 'MyAuthor'
)
));
$nb = $this->con->getQueryCount();
$paramConverter->apply($request, $configuration);
$book = $request->attributes->get('book');
$this->assertInstanceOf('Propel\PropelBundle\Tests\Request\ParamConverter\MyBook', $book,
'param "book" should be an instance of "Propel\PropelBundle\Tests\Request\ParamConverter\MyBook"');
$this->assertEquals($nb +1, $this->con->getQueryCount(), 'only one query to get the book');
$this->assertInstanceOf('Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor', $book->getMyAuthor(),
'param "book" should be an instance of "Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor"');
$this->assertEquals($nb +1, $this->con->getQueryCount(), 'no new query to get the author');
Propel::enableInstancePooling();
}
public function testParamConvertWithOptionWithLeftJoin()
{
$this->loadFixtures();
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('param1' => 10, 'author' => null));
$configuration = new ParamConverter(array(
'class' => 'Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor',
'name' => 'author',
'options' => array(
'with' => array(array('MyBook', 'left join')),
'mapping' => array('param1' => 'id'),
)
));
$nb = $this->con->getQueryCount();
$paramConverter->apply($request, $configuration);
$author = $request->attributes->get('author');
$this->assertInstanceOf('Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor', $author,
'param "author" should be an instance of "Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor"');
$this->assertEquals($nb + 1, $this->con->getQueryCount(), 'only one query to get the book');
$books = $author->getMyBooks();
$this->assertInstanceOf('\Propel\Runtime\Collection\ObjectCollection', $books);
$this->assertCount(2, $books, 'Author should have two books');
$this->assertEquals($nb + 1, $this->con->getQueryCount(), 'no new query to get the books');
}
public function testParamConvertWithOptionWithFindPk()
{
$this->loadFixtures();
$paramConverter = new PropelParamConverter();
$request = new Request(array(), array(), array('id' => 10, 'author' => null));
$configuration = new ParamConverter(array(
'class' => 'Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor',
'name' => 'author',
'options' => array(
'with' => array(array('MyBook', 'left join')),
)
));
$nb = $this->con->getQueryCount();
$paramConverter->apply($request, $configuration);
$author = $request->attributes->get('author');
$this->assertInstanceOf('Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor', $author,
'param "author" should be an instance of "Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor"');
$this->assertEquals($nb + 1, $this->con->getQueryCount(), 'only one query to get the book');
$books = $author->getMyBooks();
$this->assertInstanceOf('\Propel\Runtime\Collection\ObjectCollection', $books);
$this->assertCount(2, $books, 'Author should have two books');
$this->assertEquals($nb + 1, $this->con->getQueryCount(), 'no new query to get the books');
}
public function testConfigurationReadFromRouteOptionsIfEmpty()
{
$this->loadFixtures();
$routes = new RouteCollection();
$routes->add('test_route', new Route('/test/{authorId}', array(), array(), array(
'propel_converter' => array(
'author' => array(
'mapping' => array(
'authorId' => 'id',
),
),
),
)));
$router = $this->getMock('Symfony\Bundle\FrameworkBundle\Routing\Router', array(), array(), '', false);
$router
->expects($this->once())
->method('getRouteCollection')
->will($this->returnValue($routes))
;
$paramConverter = new PropelParamConverter();
$paramConverter->setRouter($router);
$request = new Request();
$request->attributes->add(array(
'_route' => 'test_route',
'id' => 10,
'author' => null,
));
$configuration = new ParamConverter(array(
'class' => 'Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor',
'name' => 'author',
'options' => array(),
));
$paramConverter->apply($request, $configuration);
$author = $request->attributes->get('author');
$this->assertInstanceOf('Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor', $author,
'param "author" should be an instance of "Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor"');
}
protected function loadFixtures()
{
$schema = <<<XML
<database name="default" package="vendor.bundles.Propel.PropelBundle.Tests.Request.DataFixtures.Loader"
namespace="Propel\PropelBundle\Tests\Request\ParamConverter" defaultIdMethod="native">
<table name="my_book">
<column name="id" type="integer" primaryKey="true" />
<column name="name" type="varchar" size="255" />
<column name="my_author_id" type="integer" required="true" />
<foreign-key foreignTable="my_author" onDelete="CASCADE" onUpdate="CASCADE">
<reference local="my_author_id" foreign="id" />
</foreign-key>
</table>
<table name="my_author">
<column name="id" type="integer" primaryKey="true" />
<column name="name" type="varchar" size="255" />
</table>
</database>
XML;
$builder = new QuickBuilder();
$builder->setSchema($schema);
$classTargets = null;
if (class_exists('Propel\PropelBundle\Tests\Request\ParamConverter\MyAuthor')) {
$classTargets = array();
}
$this->con = $builder->build($dsn = null, $user = null, $pass = null, $adapter = null, $classTargets);
$this->con->useDebug(true);
MyBookQuery::create()->deleteAll($this->con);
MyAuthorQuery::create()->deleteAll($this->con);
$author = new MyAuthor();
$author->setId(10);
$author->setName('Will');
$book = new MyBook();
$book->setId(1);
$book->setName('PropelBook');
$book->setMyAuthor($author);
$book2 = new MyBook();
$book2->setId(2);
$book2->setName('sf2lBook');
$book2->setMyAuthor($author);
$author->save($this->con);
}
}

18
Tests/TestCase.php Normal file
View file

@ -0,0 +1,18 @@
<?php
/**
* This file is part of the PropelBundle package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Propel\PropelBundle\Tests;
/**
* TestCase
*/
class TestCase extends \PHPUnit_Framework_TestCase
{
}

View file

@ -0,0 +1,46 @@
<?php
/**
* This file is part of the PropelBundle package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Propel\PropelBundle\Tests\Util;
use Propel\PropelBundle\Tests\TestCase;
use Propel\PropelBundle\Util\PropelInflector;
/**
* @author William Durand <william.durand1@gmail.com>
*/
class PropelInflectorTest extends TestCase
{
/**
* @dataProvider dataProviderForTestCamelize
*/
public function testCamelize($word, $expected)
{
$this->assertEquals($expected, PropelInflector::camelize($word));
}
public static function dataProviderForTestCamelize()
{
return array(
array('', ''),
array(null, null),
array('foo', 'foo'),
array('Foo', 'foo'),
array('fooBar', 'fooBar'),
array('FooBar', 'fooBar'),
array('Foo_bar', 'fooBar'),
array('Foo_Bar', 'fooBar'),
array('Foo Bar', 'fooBar'),
array('Foo bar Baz', 'fooBarBaz'),
array('Foo_Bar_Baz', 'fooBarBaz'),
array('foo_bar_baz', 'fooBarBaz'),
);
}
}

3
Tests/bootstrap.php Normal file
View file

@ -0,0 +1,3 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';

View file

@ -14,6 +14,7 @@
},
"require-dev": {
"sensio/framework-extra-bundle": "~2.3",
"phpunit/phpunit": "3.7.*",
"fzaninotto/faker": "~1.1"
},
"autoload": {