From d07dedfc173308723aebf7497f97de9308f6eb90 Mon Sep 17 00:00:00 2001 From: David Matejka Date: Wed, 5 Oct 2016 18:56:26 +0200 Subject: [PATCH] add SelectOneQuery --- src/SelectOneQuery.php | 74 +++++++++++++++++++++++++++ tests/src/SelectOneQueryTestCase.phpt | 50 ++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 src/SelectOneQuery.php create mode 100644 tests/src/SelectOneQueryTestCase.phpt diff --git a/src/SelectOneQuery.php b/src/SelectOneQuery.php new file mode 100644 index 0000000..8cbfec1 --- /dev/null +++ b/src/SelectOneQuery.php @@ -0,0 +1,74 @@ +entityClass = $entityClass; + $this->filters = array_map(NULL, array_keys($filters), $filters); + } + + + /** + * @param string|\Closure + * @param string|array|null|mixed + * @return self + */ + public function filterBy($field, $value = NULL) + { + $this->filters[] = [$field, $value]; + + return $this; + } + + + /** + * @param string + * @param string + * @return self + */ + public function orderBy($field, $direction = 'ASC') + { + $this->orderBy[$field] = $direction; + + return $this; + } + + + protected function doFetch(Queryable $queryable) + { + $qb = $queryable->createQueryBuilder($this->entityClass, 'e'); + foreach ($this->filters as $filter) { + list ($field, $value) = $filter; + if ($value === NULL && $field instanceof \Closure) { + $field($qb, 'e'); + } else { + $qb->whereCriteria([$field => $value]); + } + } + foreach ($this->orderBy as $field => $direction) { + $qb->autoJoinOrderBy($field, $direction); + } + $qb->setMaxResults(1); + + return $qb->getQuery()->getOneOrNullResult(); + } + +} diff --git a/tests/src/SelectOneQueryTestCase.phpt b/tests/src/SelectOneQueryTestCase.phpt new file mode 100644 index 0000000..f31dcbc --- /dev/null +++ b/tests/src/SelectOneQueryTestCase.phpt @@ -0,0 +1,50 @@ +createMemoryManager(); + $queryHandler = new QueryHandler(new Queryable($em, \Mockery::mock(IQueryHandlerAccessor::class))); + $em->persist($john = new User('John')); + $em->persist($jack = new User('Jack')); + $em->flush(); + $query = new SelectOneQuery(User::class, ['name' => 'John']); + Assert::same($john, $queryHandler->fetch($query)); + $query = new SelectOneQuery(User::class, ['name' => 'Jack']); + Assert::same($jack, $queryHandler->fetch($query)); + $query = new SelectOneQuery(User::class, ['name' => 'Jane']); + Assert::null($queryHandler->fetch($query)); + } + +} + + +\run(new SelectOneQueryTestCase());