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

RouteExistsValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
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