Passed
Push — master ( 109ec6...6813ed )
by Rougin
02:24
created

Client::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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