Completed
Push — master ( 4a7c7e...b71ec0 )
by Benjamin
02:32
created

URLChecker   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 39
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B check() 0 25 5
1
<?php
2
3
namespace Alpixel\Bundle\MenuBundle\Utils;
4
5
use Symfony\Bundle\FrameworkBundle\Routing\Router;
6
7
/**
8
 * Class URLChecker
9
 * @package Alpixel\Bundle\MenuBundle\Utils
10
 */
11
class URLChecker
12
{
13
    const URL_VALID     = 0;
14
    const URL_NOT_FOUND = 1;
15
    const URL_PROBLEM   = 2;
16
17
    protected $router;
18
19
    public function __construct(Router $router)
20
    {
21
        $this->router = $router;
22
    }
23
24
    public function check($url)
25
    {
26
        if (strpos($url, '/') === 0) {
27
            $context = $this->router->getContext();
28
            $baseUrl = $context->getScheme().'://'.$context->getHost().$context->getBaseUrl();
29
            $url = $baseUrl.$url;
30
        }
31
32
        $handle = curl_init($url);
33
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
34
        curl_setopt($handle, CURLOPT_HEADER, true);
35
        curl_setopt($handle, CURLOPT_NOBODY, true);
36
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 2);
37
        curl_exec($handle);
38
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
39
40
        // $httpCode (success) >= 200 && $httpCode (redirect) < 310 for all http request accepted
41
        if ($httpCode >= 200 && $httpCode < 310) {
42
            return self::URL_VALID;
43
        } else if ($httpCode === 404) {
44
            return self::URL_NOT_FOUND;
45
        }
46
47
        return self::URL_PROBLEM;
48
    }
49
}