Completed
Push — master ( 6e1ad5...f4dd1a )
by Greg
02:16
created

BrowserMob::redirectUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
namespace Codeception\Extension;
3
4
use Codeception\Module;
5
use Codeception\Exception\ModuleException;
6
use Codeception\Exception\ModuleConfigException;
7
use \PHPBrowserMobProxy_Client as BMP;
8
use \Requests;
9
use \RuntimeException;
10
11
/**
12
 * @method void _open()
13
 * @method void _close()
14
 * @method string _newHar(string $label='')
15
 * @method string _newPage(string $label='')
16
 * @method string _blacklist(string $regexp, integer $status_code)
17
 * @method string _whitelist(string $regexp, integer $status_code)
18
 * @method string _basicAuth(string $domain, string[] $options)
19
 * @method string _headers(string[] $options)
20
 * @method string _responseInterceptor(string $js)
21
 * @method string _requestInterceptor(string $js)
22
 * @method Requests_Response _limits(string[] $options)
23
 * @method Requests_Response _timeouts(string[] $options)
24
 * @method string _remapHosts(string $address, string $ip_address)
25
 * @method string _waitForTrafficToStop(integer $quiet_period, integer $timeout)
26
 * @method string _clearDnsCache()
27
 * @method string _rewriteUrl(string $match, string $replace)
28
 * @method string _retry(integer $retry_count)
29
 */
30
class BrowserMob extends Module
31
{
32
33
    protected $config = ['host', 'port', 'autostart', 'blacklist', 'whitelist', 'limits', 'timeouts', 'dns', 'retry', 'basicAuth', 'littleproxy'];
34
35
    protected $requiredFields = ['host'];
36
37
    protected $response;
38
39
    private $bmp;
40
41
    /**
42
     * @codeCoverageIgnore
43
     * @ignore Codeception specific
44
     */
45
    public function _initialize()
46
    {
47
        $host = $this->config['host'];
48
        if (isset($this->config['port'])) {
49
            $host = $host.':'.$this->config['port'];
50
        }
51
52
        // test if proxy is available
53
        if (static::__pingProxy($host)) {
54
            $this->bmp = new BMP($host);
55
        } else {
56
            throw new ModuleConfigException(__CLASS__, "Proxy '{$host}' cannot be reached");
57
        }
58
59
        // start a new BrowserMobProxy session
60
        if (isset($this->config['autostart'])) {
61
            if (true === (bool) $this->config['autostart']) {
62
                $this->openProxy();
63
            }
64
        }
65
    }
66
67
    protected static function __pingProxy($url)
68
    {
69
        try {
70
            $response = Requests::get('http://'.$url.'/proxy/');
71
        } catch (\Exception $e) {
72
            throw new ModuleException(__CLASS__, $e->getMessage());
73
        }
74
75
        return $response->success;
76
    }
77
78
    protected function __setProxyCapabilities($options)
79
    {
80
        foreach ($options as $config => $data) {
81
            if (false === empty($data)) {
82
                switch ((string) $config) {
83
                    case 'blacklist':
84
                        foreach ($data['patterns'] as $pattern) {
85
                            $this->_blacklist($pattern, $data['code']);
86
                            if (false === $this->response->success) {
87
                                break;
88
                            }
89
                        }
90
                        break;
91
                    case 'whitelist':
92
                        $patterns = implode(',', $data['patterns']);
93
                        $this->_whitelist($patterns, $data['code']);
94
                        break;
95
                    case 'limits':
96
                        $this->_limits($data);
97
                        break;
98
                    case 'timeouts':
99
                        $this->_timeouts($data);
100
                        break;
101
                    case 'redirect':
102
                        foreach ($data as $entry) {
103
                            $this->_remapHosts($entry['domain'], $entry['ip']);
104
                            if (false === $this->response->success) {
105
                                break;
106
                            }
107
                        }
108
                        break;
109
                    case 'retry':
110
                        $this->_retry($data);
111
                        break;
112
                    case 'basicAuth':
113
                        foreach ($data as $entry) {
114
                            $this->_basicAuth($entry['domain'], $entry['options']);
115
                            if (false === $this->response->success) {
116
                                break;
117
                            }
118
                        }
119
                        break;
120
                    default:
121
                        // do nothing
122
                }
123
            }
124
        }
125
    }
126
127
    public function getProxyPort()
128
    {
129
        return $this->bmp->port;
130
    }
131
132
    public function openProxy($capabilities = null)
133
    {
134
        $this->_open();
135
        if (empty($capabilities)) {
136
            $capabilities = $this->config;
1 ignored issue
show
Coding Style introduced by
Consider using a different name than the parameter $capabilities. This often makes code more readable.
Loading history...
137
        }
138
        $this->__setProxyCapabilities($capabilities);
139
        return $this->getProxyPort();
140
    }
141
142
    public function closeProxy()
143
    {
144
        $this->_close();
145
    }
146
147
    public function startHar()
148
    {
149
        $this->_newHar();
150
        return $this->response->success;
151
    }
152
153
    public function startPage()
154
    {
155
        $this->_newPage();
156
        return $this->response->success;
157
    }
158
159
    public function getHar()
160
    {
161
        return $this->bmp->har;
162
    }
163
164
    public function setHeaders($headers)
165
    {
166
        $this->_headers($headers);
167
        return $this->response->success;
168
    }
169
170
    public function redirectUrl($match, $replace)
171
    {
172
        $this->_rewriteUrl($match, $replace);
173
        return $this->response->success;
174
    }
175
176
    // magic function that exposes BrowserMobProxy API pulic methods
177
    public function __call($name, $args)
178
    {
179
        // check if is a command call
180
        if (preg_match('/^_[A-z]+$/', $name)) {
181
            // extract standard method name
182
            $name = preg_filter('/_/', '', $name);
183
            // set call array for calling method
184
            $call = array($this->bmp, $name);
185
            // check if method is callable
186
            if (is_callable($call)) {
187
                $ret = call_user_func_array($call, $args);
188
                if (get_class($ret) === 'Requests_Response') {
189
                    $this->response = $ret;
190
                    if (false === $ret->success) {
191
                        throw new ModuleConfigException(__CLASS__, "Proxy response error '{$ret->status_code}' {$ret->body}");
192
                    }
193
                }
194
            } else {
195
                throw new RuntimeException("Method ${name} does not exist or is not callable");
196
            }
197
        } else {
198
            throw new RuntimeException("Method ${method} does not exist or is not callable");
199
        }
200
        $ret = (isset($ret)) ? $ret : null;
201
        return $ret;
202
    }
203
204
}
205