Curl::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.7938

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 1
dl 0
loc 19
ccs 5
cts 12
cp 0.4167
crap 2.7938
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
namespace Anax\Curl;
4
5
class Curl
6
{
7
    private $cache;
8
9 1
    public function __construct($cache)
10
    {
11 1
        $this->cache = $cache;
12 1
    }
13
14
15 1
    public function get(string $url)
16
    {
17 1
        $cache = $this->cache;
18
19 1
        $cleanUrl = preg_replace('/[^A-Za-z0-9\-]/', '', $url);
20
21 1
        if ($cache->get($cleanUrl)) {
22 1
            return json_decode($cache->get($cleanUrl));
23
        }
24
25
        $ch = curl_init();
26
        curl_setopt($ch, CURLOPT_URL, $url);
27
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
28
        $res = curl_exec($ch);
29
        curl_close($ch);
30
31
        $cache->set($cleanUrl, $res);
32
33
        return json_decode($res);
34
    }
35
36
    public function getMulti(array $urls)
37
    {
38
        $res = [];
39
        $mh = curl_multi_init();
40
41
        foreach ($urls as $key => $value) {
42
            $multiCurl[$key] = curl_init();
43
            curl_setopt($multiCurl[$key], CURLOPT_URL, $urls[$key]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $multiCurl seems to be defined later in this foreach loop on line 42. Are you sure it is defined here?
Loading history...
44
            curl_setopt($multiCurl[$key], CURLOPT_RETURNTRANSFER, 1);
45
            curl_multi_add_handle($mh, $multiCurl[$key]);
46
        }
47
48
        $index = null;
49
        do {
50
            curl_multi_exec($mh, $index);
51
        } while ($index > 0);
52
53
        foreach ($multiCurl as $k => $ch) {
54
            $res[$k] = json_decode(curl_multi_getcontent($ch));
55
            curl_multi_remove_handle($mh, $ch);
56
        }
57
58
        curl_multi_close($mh);
59
60
        return $res;
61
    }
62
}
63