Completed
Pull Request — master (#4)
by Alexis
02:37
created

RouteExistsValidator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 7
c 4
b 0
f 0
lcom 1
cbo 5
dl 0
loc 39
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B validate() 0 29 6
1
<?php
2
3
namespace Alpixel\Bundle\MenuBundle\Validator\Constraints;
4
5
use Symfony\Bundle\FrameworkBundle\Routing\Router;
6
use Symfony\Component\Validator\Constraint;
7
use Symfony\Component\Validator\ConstraintValidator;
8
9
class RouteExistsValidator extends ConstraintValidator
10
{
11
    private $router;
12
13
    public function __construct(Router $router)
14
    {
15
        $this->router = $router;
16
    }
17
18
    public function validate($value, Constraint $constraint)
19
    {
20
        $match = false;
21
        if (strpos($value, '/') === 0) {
22
            $context = $this->router->getContext();
23
            $baseUrl = $context->getScheme().'://'.$context->getHost().$context->getBaseUrl();
24
            $value = $baseUrl.$value;
25
        }
26
27
        $handle = curl_init($value);
28
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
29
        curl_setopt($handle, CURLOPT_HEADER, true);
30
        curl_setopt($handle, CURLOPT_NOBODY, true);
31
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 2);
32
        curl_exec($handle);
33
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
34
35
        // $httpCode >= 200 && $httpCode < 300 for all http request accepted
36
        // $httpCode === 401 for page with authentification required
37
        if ($httpCode >= 200 && $httpCode < 300 || $httpCode === 401) {
38
            $match = true;
39
        }
40
41
        if ($match === false) {
42
            $this->context->buildViolation($constraint->message)
43
                ->setParameter('%string%', $value)
44
                ->addViolation();
45
        }
46
    }
47
}
48