Completed
Pull Request — master (#4)
by Alexis
19:47
created

RouteExistsValidator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B validate() 0 26 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_exec($handle);
30
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
31
32
        // $httpCode >= 200 && $httpCode < 300 for all http request accepted
33
        // $httpCode === 401 for page with authentification required
34
        if ($httpCode >= 200 && $httpCode < 300 || $httpCode === 401) {
35
            $match = true;
36
        }
37
38
        if ($match === false) {
39
            $this->context->buildViolation($constraint->message)
40
                ->setParameter('%string%', $value)
41
                ->addViolation();
42
        }
43
    }
44
}
45