URLService   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 16
c 2
b 0
f 0
dl 0
loc 40
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A isCanonical() 0 10 3
A isRefererFromCurrentHost() 0 7 2
A generateCanonical() 0 7 1
A __construct() 0 3 1
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