Passed
Push — up-php7 ( a2fe11...4e1c1e )
by Erik
05:48
created

UrlValidator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 48
ccs 0
cts 15
cp 0
rs 10
c 1
b 0
f 1
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 8 3
A getHeader() 0 6 2
A getStatusCode() 0 9 3
1
<?php
2
/**
3
 * @author Muhammed Akbulut <[email protected]>
4
 * @copyright Zicht Online <http://www.zicht.nl>
5
 */
6
7
namespace Zicht\Bundle\UrlBundle\Service;
8
9
use GuzzleHttp\Client;
10
use GuzzleHttp\Exception\ConnectException;
11
use GuzzleHttp\Exception\RequestException;
12
13
/**
14
 * Class UrlValidator
15
 *
16
 * @package Zicht\Bundle\UrlBundle\Util
17
 */
18
class UrlValidator
19
{
20
    /**
21
     * Returns true when url does not return error codes or not found.
22
     *
23
     * @param string $url
24
     * @return boolean
25
     */
26
    public function validate($url)
27
    {
28
        if (null !== ($headers = $this->getHeader($url))) {
29
            $statusCode = $this->getStatusCode($headers);
30
            // see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
31
            return ($statusCode >= 200 && $statusCode < 300);
32
        }
33
        return false;
34
    }
35
36
    /**
37
     * Fetch a url with a HEAD request because we just want to check status code.
38
     *
39
     * @param string $url
40
     * @return array|null
41
     */
42
    protected function getHeader($url)
43
    {
44
        if (false !== @file_get_contents($url, false, stream_context_create(['http' => ['method' => 'HEAD']]))) {
0 ignored issues
show
introduced by
The condition false !== @file_get_cont...('method' => 'HEAD')))) can never be false.
Loading history...
45
            return $http_response_header;
46
        } else {
47
            return null;
48
        }
49
    }
50
51
    /**
52
     * Parse the headers array and search for the status pattern
53
     *
54
     * @param array $headers
55
     * @return int
56
     */
57
    protected function getStatusCode(array $headers)
58
    {
59
        $status = 0;
60
        foreach ($headers as $header) {
61
            if (preg_match('#^HTTP/(?:[^\s]+)\s(?P<code>\d+)\s#', $header, $match)) {
62
                $status = (int)$match['code'];
63
            }
64
        }
65
        return $status;
66
    }
67
}
68