Skip to content

Commit

Permalink
Add Criteria::fromFindCriteria
Browse files Browse the repository at this point in the history
The goals is to be able to quick reproduce a criteria looking like parameters given to ORM find methods.
  • Loading branch information
soullivaneuh committed Jun 26, 2017
1 parent f4b7fca commit 78461f5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/Doctrine/Common/Collections/Criteria.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,26 @@ public static function create()
return new static();
}

/**
* Creates an instance with same behaviour as criteria parameters passed on ORM find methods.
*
* @param mixed[] $findCriteria Array of different keys and values. Gets the same format as argument expected on
* Doctrine\Common\Persistence\ObjectRepository::findBy and
* Doctrine\Common\Persistence\ObjectRepository::findOneBy methods.
*
* @return Criteria
*/
public static function fromFindCriteria(array $findCriteria)
{
$criteria = static::create();

foreach ($findCriteria as $key => $value) {
$criteria->andWhere(static::expr()->eq($key, $value));
}

return $criteria;
}

/**
* Returns the expression builder.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Doctrine/Tests/Common/Collections/CriteriaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,18 @@ public function testCreate() : void
$this->assertInstanceOf(Criteria::class, $criteria);
}

public function testFromFindCriteria()
{
$criteria = Criteria::fromFindCriteria(array('name' => 'test', 'foo' => 42));

/** @var CompositeExpression $where */
$where = $criteria->getWhereExpression();
$this->assertInstanceOf('Doctrine\Common\Collections\Expr\CompositeExpression', $where);

$this->assertSame(CompositeExpression::TYPE_AND, $where->getType());
$this->assertCount(2, $where->getExpressionList());
}

public function testConstructor() : void
{
$expr = new Comparison("field", "=", "value");
Expand Down

0 comments on commit 78461f5

Please sign in to comment.