Passed
Push — master ( 2ed8eb...49bf97 )
by Rougin
02:18
created

Client::request()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.7536

Importance

Changes 0
Metric Value
cc 3
eloc 14
nc 4
nop 1
dl 0
loc 27
ccs 9
cts 16
cp 0.5625
crap 3.7536
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
namespace Pilipinews\Website\Sunstar;
4
5
use Nacmartin\PhpExecJs\PhpExecJs;
6
use Nacmartin\PhpExecJs\Runtime\ExternalRuntime;
7
use Pilipinews\Common\Client as CurlClient;
8
9
class Client extends CurlClient
10
{
11
    /**
12
     * @var \Nacmartin\PhpExecJs\PhpExecJs
13
     */
14
    protected $executor;
15
16
    /**
17
     * Initializes the cURL session.
18
     */
19 33
    public function __construct()
20
    {
21 33
        $binaries = array('node', 'nodejs');
22
23 33
        $runtime = new ExternalRuntime(null, $binaries);
24
25 33
        parent::__construct();
26
27 33
        $this->executor = new PhpExecJs($runtime);
28 33
    }
29
30
    /**
31
     * Performs the HTTP request based on the given URL.
32
     *
33
     * @param  string $url
34
     * @return string
35
     */
36 33
    public static function request($url)
37
    {
38 33
        $self = new static;
39
40 33
        $self->url($url);
41
42 33
        $result = $self->execute(false);
43
44 33
        if ($result === false) {
45 33
            echo curl_error($self->curl) . PHP_EOL;
46 22
        } else {
47
            echo json_encode($result) . PHP_EOL;
48
        }
49
50 33
        if ($self->redirected($result)) {
51
            $pattern = '/<script>(.*?)<\/script>/i';
52
53
            preg_match($pattern, $result, $matches);
54
55
            echo json_encode($matches) . PHP_EOL;
56
57
            $cookie = $self->cookie($matches[1]);
58
59
            $self->set(CURLOPT_COOKIE, $cookie);
60
        }
61
62 33
        return $self->execute();
63
    }
64
65
    /**
66
     * Returns the cookie value based on given script.
67
     *
68
     * @param  string $result
69
     * @return string
70
     */
71
    protected function cookie($result)
72
    {
73
        $script = str_replace('e(r);', 'r', $result);
74
75
        $eval = $this->executor->evalJs((string) $script);
76
77
        $search = array('document.cookie=', 'location.reload()');
78
79
        $script = str_replace($search, array('x=', 'x'), $eval);
80
81
        return $this->executor->evalJs((string) $script);
82
    }
83
84
    /**
85
     * Checks if the result is being redirected.
86
     *
87
     * @param  string $result
88
     * @return boolean
89
     */
90 33
    protected function redirected($result)
91
    {
92 33
        return strpos($result, 'You are being redirected') !== false;
93
    }
94
}
95