Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Criteria::fromFindCriteria #89

Open
wants to merge 1 commit into
base: 2.0.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions lib/Doctrine/Common/Collections/Criteria.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,31 @@ 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(!is_array($value)
? static::expr()->eq($key, $value)
: new CompositeExpression(CompositeExpression::TYPE_OR, \array_map(function ($v) use ($key) {
return static::expr()->eq($key, $v);
}, $value))
);
}

return $criteria;
}

/**
* Returns the expression builder.
*
Expand Down
15 changes: 15 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,21 @@ public function testCreate() : void
$this->assertInstanceOf(Criteria::class, $criteria);
}

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

/** @var CompositeExpression $where */
$where = $criteria->getWhereExpression();
$this->assertInstanceOf(CompositeExpression::class, $where);

$this->assertSame(CompositeExpression::TYPE_AND, $where->getType());
$this->assertCount(2, $where->getExpressionList());
$this->assertInstanceOf(Comparison::class, $where->getExpressionList()[0]);
$this->assertInstanceOf(CompositeExpression::class, $where->getExpressionList()[1]);
$this->assertSame(CompositeExpression::TYPE_OR, $where->getExpressionList()[1]->getType());
}

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