diff --git a/lib/Doctrine/Common/Collections/Criteria.php b/lib/Doctrine/Common/Collections/Criteria.php index 748a08474..64fd32e1f 100644 --- a/lib/Doctrine/Common/Collections/Criteria.php +++ b/lib/Doctrine/Common/Collections/Criteria.php @@ -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. * diff --git a/tests/Doctrine/Tests/Common/Collections/CriteriaTest.php b/tests/Doctrine/Tests/Common/Collections/CriteriaTest.php index 548dbfecc..94f147731 100644 --- a/tests/Doctrine/Tests/Common/Collections/CriteriaTest.php +++ b/tests/Doctrine/Tests/Common/Collections/CriteriaTest.php @@ -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");