Passed
Push — master ( 86479e...2843a8 )
by Marcus
02:54
created

Curl::fetchSingleUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Mahw17\Weather;
4
5
// use Anax\Commons\ContainerInjectableInterface;
6
// use Anax\Commons\ContainerInjectableTrait;
7
8
/**
9
 * cUrl methods to fetch information
10
 */
11
class Curl //implements ContainerInjectableInterface
12
{
13
    // use ContainerInjectableTrait;
14
15
    /**
16
     * Fetch information from single url
17
     *
18
     *
19
     * @param string $url that should be curled.
20
     *
21
     * @return string as the response.
22
     */
23 4
    public function fetchSingleUrl($url)
24
    {
25 4
        $chandle = curl_init();
26
27 4
        curl_setopt($chandle, CURLOPT_URL, $url);
28 4
        curl_setopt($chandle, CURLOPT_HEADER, 0);
29 4
        curl_setopt($chandle, CURLOPT_RETURNTRANSFER, 1);
30
31 4
        $result = curl_exec($chandle);
32 4
        curl_close($chandle);
33
34 4
        return $result;
35
    }
36
37
    /**
38
     * Fetch information from multiple url:s parallell
39
     *
40
     *
41
     * @param array $urlArray array with all urls that should be curled.
42
     *
43
     * @return array as the response.
44
     */
45 3
    public function fetchMultiUrl($urlArray)
46
    {
47
        // array of curl handles
48 3
        $multiCurl = array();
49
50
        // data to be returned
51 3
        $result = array();
52
53
        // multi handle
54 3
        $mhandle = curl_multi_init();
55
56 3
        $i = 0; //counter
57 3
        foreach ($urlArray as $url) {
58 3
            $multiCurl[$i] = curl_init();
59 3
            curl_setopt($multiCurl[$i], CURLOPT_URL, $url);
60 3
            curl_setopt($multiCurl[$i], CURLOPT_HEADER, 0);
61 3
            curl_setopt($multiCurl[$i], CURLOPT_RETURNTRANSFER, 1);
62 3
            curl_multi_add_handle($mhandle, $multiCurl[$i]);
63
64 3
            $i++;
65
        }
66
67 3
        $index = null;
68
69
        do {
70 3
            curl_multi_exec($mhandle, $index);
71 3
        } while ($index > 0);
72
73
        // get content and remove handles
74 3
        foreach ($multiCurl as $k => $chandle) {
75 3
            $result[$k] = json_decode(curl_multi_getcontent($chandle));
76 3
            curl_multi_remove_handle($mhandle, $chandle);
77
        }
78
        // close
79 3
        curl_multi_close($mhandle);
80
        //
81
        // foreach ($result as $res) {
82
        //     $res = json_decode($res);
83
        //     echo $res->latitude . "<br>";
84
        // }
85 3
        return $result;
86
    }
87
}
88