SimilarRepository::findSimilarProperties()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 10
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 21
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Repository;
6
7
use App\Entity\Property;
8
9
final class SimilarRepository extends PropertyRepository
10
{
11
    public const NUM_ITEMS = 6;
12
13
    public function findSimilarProperties(Property $property): array
14
    {
15
        if (!$this->isModuleEnabled()) {
16
            return [];
17
        }
18
19
        if ($property->getNeighborhood()) {
20
            // Find in a small area
21
            $result = $this->findByArea($property, 'neighborhood');
22
23
            if (empty($result) && $property->getDistrict()) {
24
                // Find in a larger area
25
                $result = $this->findByArea($property);
26
            }
27
28
            return $result;
29
        } elseif ($property->getDistrict()) {
30
            return $this->findByArea($property);
31
        }
32
33
        return [];
34
    }
35
36
    private function findByArea(Property $property, string $area = 'district'): array
37
    {
38
        $qb = $this->createQueryBuilder('p')
39
            ->where("p.state = 'published'")
40
            ->andWhere('p.id != '.(int) ($property->getId()))
41
            ->andWhere('p.deal_type = '.(int) ($property->getDealType()->getId()))
42
            ->andWhere('p.category = '.(int) ($property->getCategory()->getId()));
43
44
        if ('neighborhood' === $area) {
45
            $qb->andWhere('p.neighborhood = '.(int) ($property->getNeighborhood()->getId()));
46
        } else {
47
            $qb->andWhere('p.district = '.(int) ($property->getDistrict()->getId()));
48
        }
49
50
        return $qb->getQuery()->setMaxResults(self::NUM_ITEMS)->getResult();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $qb->getQuery()->...NUM_ITEMS)->getResult() could return the type integer which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
51
    }
52
53
    private function isModuleEnabled(): bool
54
    {
55
        $repository = $this->getEntityManager()->getRepository('App:Settings');
56
        $state = $repository->findOneBy(['setting_name' => 'show_similar_properties']);
57
58
        return '1' === $state->getSettingValue();
59
    }
60
}
61