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

URLChecker::__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\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
}