Completed
Push — master ( 88c9bf...623e12 )
by Mike
117:44 queued 102:47
created

HostTrait::checkWhetherHostIsLive()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 37
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3.0026

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 37
ccs 14
cts 15
cp 0.9333
rs 9.6666
cc 3
nc 3
nop 1
crap 3.0026
1
<?php
2
3
namespace Mediadevs\Validator\Traits;
4
5
trait HostTrait
6
{
7
    /**
8
     * Pinging the hostname to see if it is live / an actual working hostname.
9
     *
10
     * @param string $host
11
     *
12
     * @return bool
13
     */
14 2
    protected function checkWhetherHostIsLive(string $host): bool
15
    {
16
        $statuses = array(
17 2
            200,
18
            301,
19
            302,
20
        );
21
22
        // Initializing curl
23 2
        $curlHandle = curl_init($host);
24
25
        // Validating whether the curl handle can reach the host, else returning false.
26 2
        if ($curlHandle) {
0 ignored issues
show
introduced by
$curlHandle is of type false|resource, thus it always evaluated to false.
Loading history...
27
            // Calling the host for a response
28 2
            curl_setopt_array($curlHandle, array(
29 2
                CURLOPT_HEADER          => true,
30 2
                CURLOPT_NOBODY          => true,
31 2
                CURLOPT_RETURNTRANSFER  => true,
32 2
                CURLOPT_TIMEOUT         => 10,
33 2
                CURLOPT_USERAGENT       => 'page-check/1.0',
34
            ));
35
36
            // Executing request
37 2
            curl_exec($curlHandle);
38
39
            // Collecting the status code and casting it to an integer
40 2
            $status = (int) curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
41
42
            // Closing curl
43 2
            curl_close($curlHandle);
44
45
        } else {
46
            return false;
47
        }
48
49
        // Validating whether the http status is inside the allowed statuses array (Whether the page is live or not)
50 2
        return in_array($status, $statuses) ? true : false;
51
    }
52
}
53