URLService::isCanonical()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 2
b 0
f 0
nc 2
nop 2
dl 0
loc 10
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Service;
6
7
use App\Entity\Property;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
10
use Symfony\Component\Routing\RouterInterface;
11
12
final class URLService
13
{
14
    private RouterInterface $router;
15
16
    public function __construct(RouterInterface $router)
17
    {
18
        $this->router = $router;
19
    }
20
21
    // Check slugs.
22
    public function isCanonical(Property $property, Request $request): bool
23
    {
24
        $citySlug = $request->attributes->get('citySlug', '');
25
        $slug = $request->attributes->get('slug', '');
26
27
        if ($property->getCity()->getSlug() !== $citySlug || $property->getSlug() !== $slug) {
28
            return false;
29
        }
30
31
        return true;
32
    }
33
34
    // Generate correct canonical URL.
35
    public function generateCanonical(Property $property): string
36
    {
37
        return $this->router->generate('property_show', [
38
            'id' => $property->getId(),
39
            'citySlug' => $property->getCity()->getSlug(),
40
            'slug' => $property->getSlug(),
41
        ], UrlGeneratorInterface::ABSOLUTE_URL);
42
    }
43
44
    // Check referer host.
45
    public function isRefererFromCurrentHost(Request $request): bool
46
    {
47
        if (preg_match('/'.$request->getHost().'/', ($request->server->getHeaders()['REFERER']) ?? '')) {
48
            return true;
49
        }
50
51
        return false;
52
    }
53
}
54