Tools::curl()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 1
1
<?php
2
3
namespace cvweiss\projectbase;
4
5
class Tools
6
{
7
    public static function forkMe($numChildrenPerSecond = 1, $duration = 60):bool
8
    {
9
        $usleep = max(1, floor(1000000 / $numChildrenPerSecond));
10
        $doneAt = microtime() + ($duration * 1000000);
11
        $childrenCount = 0;
12
        $maxChildren = $numChildrenPerSecond * $duration;
13
14
        $lastRun = microtime();
15
16
        while (microtime() < $doneAt && $childrenCount < $maxChildren) {
17
            if (pcntl_fork()) return true;
18
            $sleep = floor(($lastRun + $usleep) - microtime());
19
            usleep($sleep);
20
            $childrenCount++;
21
        }
22
        return false;
23
    }
24
25
    public static function fetchJSON($url)
26
    {
27
        $response = self::curl($url);
28
        $raw = $response['result'];
29
        $json = json_decode($raw, true);
30
        return $json;
31
    }
32
33
    public static function curl($url)
34
    {
35
        $ch = curl_init();
36
        curl_setopt($ch, CURLOPT_URL, $url);
37
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
38
        curl_setopt($ch, CURLOPT_USERAGENT, "cvweiss\\projectbase Curl Fetcher");
39
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
40
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
41
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
42
        $body = curl_exec($ch);
43
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
44
45
        return ['result' => $body, 'httpCode' => $httpCode];
46
    }
47
48
    public static function output($text)
49
    {
50
        echo date('Y-m-d H:i:s')." > $text\n";
51
    }
52
}
53