From a4f6055baa3f4c07b5c9850c58868a0c177be518 Mon Sep 17 00:00:00 2001 From: Sullivan SENECHAL Date: Thu, 16 Jun 2016 14:13:03 +0200 Subject: [PATCH] Add Criteria::fromFindCriteria The goals is to be able to quick reproduce a criteria looking like parameters given to ORM find methods. --- lib/Doctrine/Common/Collections/Criteria.php | 20 +++++++++++++++++++ .../Tests/Common/Collections/CriteriaTest.php | 12 +++++++++++ 2 files changed, 32 insertions(+) diff --git a/lib/Doctrine/Common/Collections/Criteria.php b/lib/Doctrine/Common/Collections/Criteria.php index 748a08474..109285ed3 100644 --- a/lib/Doctrine/Common/Collections/Criteria.php +++ b/lib/Doctrine/Common/Collections/Criteria.php @@ -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. * diff --git a/tests/Doctrine/Tests/Common/Collections/CriteriaTest.php b/tests/Doctrine/Tests/Common/Collections/CriteriaTest.php index 548dbfecc..1a02b4b21 100644 --- a/tests/Doctrine/Tests/Common/Collections/CriteriaTest.php +++ b/tests/Doctrine/Tests/Common/Collections/CriteriaTest.php @@ -16,6 +16,18 @@ public function testCreate() : void $this->assertInstanceOf(Criteria::class, $criteria); } + public function testFromFindCriteria() + { + $criteria = Criteria::fromFindCriteria(['name' => 'test', 'foo' => 42]); + + /** @var CompositeExpression $where */ + $where = $criteria->getWhereExpression(); + $this->assertInstanceOf(CompositeExpression::class, $where); + + $this->assertSame(CompositeExpression::TYPE_AND, $where->getType()); + $this->assertCount(2, $where->getExpressionList()); + } + public function testConstructor() : void { $expr = new Comparison("field", "=", "value");