Passed
Push — master ( 6813ed...1e9096 )
by Rougin
01:30
created

Client::request()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.1821

Importance

Changes 0
Metric Value
cc 2
eloc 12
nc 2
nop 1
dl 0
loc 25
ccs 9
cts 14
cp 0.6429
crap 2.1821
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
namespace Pilipinews\Website\Sunstar;
4
5
use Nacmartin\PhpExecJs\PhpExecJs as Executor;
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 Executor($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
        $cert = __DIR__ . '/../cacert.pem';
47
48 33
        $self->set(CURLOPT_SSL_VERIFYPEER, 1);
49
50 33
        $self->set(CURLOPT_CAINFO, $cert);
51
52 33
        $self->url($url);
53
54 33
        $result = $self->execute(false);
55
56 33
        if ($self->redirected($result)) {
57
            $pattern = '/<script>(.*?)<\/script>/i';
58
59
            preg_match($pattern, $result, $matches);
60
61
            $cookie = $self->cookie($matches[1]);
62
63
            $self->set(CURLOPT_COOKIE, $cookie);
64
        }
65
66 33
        return $self->execute();
67
    }
68
69
    /**
70
     * Returns the cookie value based on given script.
71
     *
72
     * @param  string $result
73
     * @return string
74
     */
75
    protected function cookie($result)
76
    {
77
        $script = str_replace('e(r);', 'r', $result);
78
79
        $eval = $this->executor->evalJs($script);
80
81
        $search = array('document.cookie=', 'location.reload()');
82
83
        $script = str_replace($search, array('x=', 'x'), $eval);
84
85
        return $this->executor->evalJs($script);
86
    }
87
88
    /**
89
     * Checks if the result is being redirected.
90
     *
91
     * @param  string $result
92
     * @return boolean
93
     */
94 33
    protected function redirected($result)
95
    {
96 33
        return strpos($result, 'You are being redirected') !== false;
97
    }
98
}
99