Test Failed
Branch master (e769ca)
by Stone
05:52
created

TrickRepository::findBySearchQuery()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 13
nc 3
nop 1
dl 0
loc 22
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace App\Repository;
4
5
use App\Entity\Trick;
6
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
7
use Symfony\Bridge\Doctrine\RegistryInterface;
8
9
/**
10
 * @method Trick|null find($id, $lockMode = null, $lockVersion = null)
11
 * @method Trick|null findOneBy(array $criteria, array $orderBy = null)
12
 * @method Trick[]    findAll()
13
 * @method Trick[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
14
 */
15
class TrickRepository extends ServiceEntityRepository
16
{
17
    public function __construct(RegistryInterface $registry)
18
    {
19
        parent::__construct($registry, Trick::class);
20
    }
21
22
    /**
23
     * @return Trick[] Returns an array of Trick objects
24
     */
25
    public function findLatestEdited($limit = Trick::NUMBER_OF_DISPLAYED_TRICKS)
26
    {
27
        return $this->createQueryBuilder('t')
28
            ->orderBy('t.editedAt', 'DESC')
29
            ->setMaxResults($limit)
30
            ->getQuery()
31
            ->getResult();
32
    }
33
34
35
    /**
36
     * @param string $query
37
     * @return array
38
     */
39
    public function findBySearchQuery(string $query): array
40
    {
41
        $query = $this->sanitizeSearchQuery($query);
42
        $searchTerms = $this->extractSearchTerms($query);
43
44
        if (\count($searchTerms) === 0) {
45
            return [];
46
        }
47
48
        $queryBuilder = $this->createQueryBuilder('p');
49
50
        foreach ($searchTerms as $key => $term) {
51
            $queryBuilder
52
                ->orWhere('p.name LIKE :term_' . $key)
53
                ->setParameter('term_' . $key, '%' . $term . '%');
54
55
        }
56
57
        return $queryBuilder
58
            ->orderBy('p.createdAt', 'DESC')
59
            ->getQuery()
60
            ->getResult();
61
62
    }
63
64
    /**
65
     * @param string $query
66
     * @return string
67
     * Removes all non alphanum characters except whitespace
68
     */
69
    private function sanitizeSearchQuery(string $query): string
70
    {
71
        return trim(preg_replace('/[[:space:]]+/', ' ', $query));
72
    }
73
74
    /**
75
     * Splits the search query into terms and removes the ones which are irrelevant.
76
     */
77
    private function extractSearchTerms(string $searchQuery): array
78
    {
79
        $terms = array_unique(explode(' ', $searchQuery));
80
        return array_filter($terms, function ($term) {
81
            return 2 <= mb_strlen($term);
82
        });
83
    }
84
}
85