-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathPostRepository.php
106 lines (91 loc) · 2.94 KB
/
PostRepository.php
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Repository;
use App\Entity\Post;
use App\Entity\Tag;
use App\Pagination\Paginator;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use function Symfony\Component\String\u;
/**
* This custom Doctrine repository contains some methods which are useful when
* querying for blog post information.
*
* See https://symfony.com/doc/current/doctrine.html#querying-for-objects-the-repository
*
* @author Ryan Weaver <[email protected]>
* @author Javier Eguiluz <[email protected]>
* @author Yonel Ceruto <[email protected]>
*
* @method Post|null findOneByTitle(string $postTitle)
*
* @template-extends ServiceEntityRepository<Post>
*/
class PostRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Post::class);
}
public function findLatest(int $page = 1, ?Tag $tag = null): Paginator
{
$qb = $this->createQueryBuilder('p')
->addSelect('a', 't')
->innerJoin('p.author', 'a')
->leftJoin('p.tags', 't')
->where('p.publishedAt <= :now')
->orderBy('p.publishedAt', 'DESC')
->setParameter('now', new \DateTimeImmutable())
;
if (null !== $tag) {
$qb->andWhere(':tag MEMBER OF p.tags')
->setParameter('tag', $tag);
}
return (new Paginator($qb))->paginate($page);
}
/**
* @return Post[]
*/
public function findBySearchQuery(string $query, int $limit = Paginator::PAGE_SIZE): array
{
$searchTerms = $this->extractSearchTerms($query);
if (0 === \count($searchTerms)) {
return [];
}
$queryBuilder = $this->createQueryBuilder('p');
foreach ($searchTerms as $key => $term) {
$queryBuilder
->orWhere('p.title LIKE :t_'.$key)
->setParameter('t_'.$key, '%'.$term.'%')
;
}
/** @var Post[] $result */
$result = $queryBuilder
->orderBy('p.publishedAt', 'DESC')
->setMaxResults($limit)
->getQuery()
->getResult()
;
return $result;
}
/**
* Transforms the search string into an array of search terms.
*
* @return string[]
*/
private function extractSearchTerms(string $searchQuery): array
{
$terms = array_unique(u($searchQuery)->replaceMatches('/[[:space:]]+/', ' ')->trim()->split(' '));
// ignore the search terms that are too short
return array_filter($terms, static function ($term) {
return 2 <= $term->length();
});
}
}