-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExistsMethodRepositoryTrait.php
More file actions
58 lines (46 loc) · 1.42 KB
/
ExistsMethodRepositoryTrait.php
File metadata and controls
58 lines (46 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
declare(strict_types=1);
namespace Pfilsx\PostgreSQLDoctrine\ORM\Trait;
use Doctrine\DBAL\Exception;
trait ExistsMethodRepositoryTrait
{
/**
* @param array<string, mixed> $predicates
*
* @throws Exception
*
* @return bool
*/
public function exists(array $predicates): bool
{
$subQb = $this->createQueryBuilder('_sub')->select('1');
$parameters = [];
$idx = 1;
foreach ($predicates as $field => $value) {
if (\is_array($value)) {
$subQb->andWhere($subQb->expr()->in("_sub.$field", $value));
continue;
}
if (\is_null($value)) {
$subQb->andWhere($subQb->expr()->isNull("_sub.$field"));
continue;
}
if (\is_object($value)) {
if (!\method_exists($value, 'getId')) {
throw new \RuntimeException("Unable to cast object predicate value to scalar for key: $field");
}
$value = $value->getId();
}
$subQb->andWhere("_sub.$field = ?$idx");
$parameters[$idx] = $value;
++$idx;
}
return (bool) $this->_em
->getConnection()
->createQueryBuilder()
->select("EXISTS({$subQb->getQuery()->getSQL()})")
->setParameters($parameters)
->fetchOne()
;
}
}