-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch.php
More file actions
55 lines (44 loc) · 1.55 KB
/
Search.php
File metadata and controls
55 lines (44 loc) · 1.55 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
<?php
namespace App\Repository\Trait;
use Doctrine\ORM\QueryBuilder;
trait Search
{
private function createSearchQueryBuilder( array $search, array $criteria = null, array $orderBy = null, $limit = null, $offset = null ): QueryBuilder
{
$queryBuilder = $this->createQueryBuilder( 'd' );
foreach ( $search as $key => $value ) {
$queryBuilder->andWhere( 'd.' . $key . ' LIKE :search_' . $key );
$queryBuilder->setParameter( 'search_' . $key, '%' . $value . '%' );
}
if ( $criteria ) {
foreach ( $criteria as $key => $value ) {
if ( is_array( $value ) ) {
$queryBuilder->andWhere( 'd.' . $key . ' IN (:val_' . $key . ')' );
} else {
$queryBuilder->andWhere( 'd.' . $key . ' = :val_' . $key );
}
$queryBuilder->setParameter( 'val_' . $key, $value );
}
}
if ( $orderBy ) {
foreach ( $orderBy as $sort => $order ) {
$queryBuilder->orderBy( $sort, $order );
}
}
if ( $limit ) {
$queryBuilder->setMaxResults( $limit );
}
if ( $offset ) {
$queryBuilder->setFirstResult( $offset );
}
return $queryBuilder;
}
public function searchBy( array $search, array $criteria = null, array $orderBy = null, $limit = null, $offset = null ): array
{
return $this->createSearchQueryBuilder( $search, $criteria, $orderBy, $limit, $offset )->getQuery()->getResult();
}
public function searchOneBy( array $search, array $criteria = null, array $orderBy = null, $offset = null ): mixed
{
return $this->createSearchQueryBuilder( $search, $criteria, $orderBy, 1, $offset )->getQuery()->getOneOrNullResult();
}
}