URLChecker::check()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
c 0
b 0
f 0
rs 8.439
cc 6
eloc 17
nc 6
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
 */
10
class URLChecker
11
{
12
    const URL_VALID = 0;
13
    const URL_NOT_FOUND = 1;
14
    const URL_PROBLEM = 2;
15
16
    protected $router;
17
18
    public function __construct(Router $router)
19
    {
20
        $this->router = $router;
21
    }
22
23
    public function check($url)
24
    {
25
        if (strpos($url, '/') === 0) {
26
            $context = $this->router->getContext();
27
            $baseUrl = $context->getScheme().'://'.$context->getHost().$context->getBaseUrl();
28
            $url = $baseUrl.$url;
29
        }
30
31
        $handle = curl_init($url);
32
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
33
        curl_setopt($handle, CURLOPT_HEADER, true);
34
        curl_setopt($handle, CURLOPT_NOBODY, true);
35
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 2);
36
        curl_exec($handle);
37
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
38
39
        // $httpCode (success) >= 200 && $httpCode (redirect) < 310 for all http request accepted
40
        if ($httpCode >= 200 && $httpCode < 310) {
41
            return self::URL_VALID;
42
        } elseif ($httpCode === 404 || $httpCode === 0) {
43
            return self::URL_NOT_FOUND;
44
        }
45
46
        return self::URL_PROBLEM;
47
    }
48
}
49