Completed
Push — master ( b800f8...5894ab )
by Greg
05:57
created

BrowserMob::__setProxyCapabilities()   C

Complexity

Conditions 14
Paths 38

Size

Total Lines 47
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 47
rs 5.0622
cc 14
eloc 35
nc 38
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
10
class BrowserMob extends Module
11
{
12
13
    protected $config = ['host', 'port', 'autostart', 'blacklist', 'whitelist', 'limits', 'timeouts', 'redirect', 'retry', 'basicAuth'];
14
15
    protected $requiredFields = ['host'];
16
17
    protected $lastResponse;
18
19
    private $bmp;
20
21
    /**
22
     * @codeCoverageIgnore
23
     * @ignore Codeception specific
24
     */
25
    public function _initialize()
26
    {
27
        $host = $this->config['host'];
28
        if (isset($this->config['port'])) {
29
            $host = $host.':'.$this->config['port'];
30
        }
31
32
        // test if proxy is available
33
        if (static::__pingProxy($host)) {
34
            $this->bmp = new BMP($host);
35
        } else {
36
            throw new ModuleConfigException(__CLASS__, "Proxy '{$host}' cannot be reached");
37
        }
38
39
        // start a new BrowserMobProxy session
40
        if (isset($this->config['autostart'])) {
41
            if (true === (bool)$this->config['autostart']) {
42
                $this->openProxy();
43
            }
44
        }
45
    }
46
47
    protected static function __pingProxy($url)
48
    {
49
        try {
50
            $response = Requests::get('http://'.$url.'/proxy/');
51
        } catch(\Exception $e) {
52
            throw new ModuleException(__CLASS__, $e->getMessage());
53
        }
54
55
        return $response->success;
56
    }
57
58
    protected function __setProxyCapabilities($capabilities)
59
    {
60
        $response = null;
61
62
        foreach ($capabilities as $config => $data) {
63
            try {
64
                if (false === empty($data)) {
65
                    switch ($config) {
66
                        case 0: // fix a weird PHP behaviour: when $config === 0 then go in 'blacklist'
67
                            break;
68
                        case 'blacklist':
69
                            $response = $this-_blacklist($data);
70
                            break;
71
                        case 'whitelist':
72
                            $response = $this->_whitelist($data);
0 ignored issues
show
Documentation Bug introduced by
The method _whitelist does not exist on object<Codeception\Extension\BrowserMob>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
73
                            break;
74
                        case 'limits':
75
                            $response = $this->_limits($data);
0 ignored issues
show
Documentation Bug introduced by
The method _limits does not exist on object<Codeception\Extension\BrowserMob>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
76
                            break;
77
                        case 'timeouts':
78
                            $response = $this->_timeouts($data);
0 ignored issues
show
Documentation Bug introduced by
The method _timeouts does not exist on object<Codeception\Extension\BrowserMob>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
79
                            break;
80
                        case 'redirect':
81
                            $response = $this->_remapHosts($data);
0 ignored issues
show
Documentation Bug introduced by
The method _remapHosts does not exist on object<Codeception\Extension\BrowserMob>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
82
                            break;
83
                        case 'retry':
84
                            $response = $this->_retry($data);
0 ignored issues
show
Documentation Bug introduced by
The method _retry does not exist on object<Codeception\Extension\BrowserMob>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
85
                            break;
86
                        case 'basicAuth':
87
                            $response = $this->_basicAuth($data);
0 ignored issues
show
Documentation Bug introduced by
The method _basicAuth does not exist on object<Codeception\Extension\BrowserMob>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
88
                            break;
89
                        default:
90
                            // do nothing
91
                    }
92
                }
93
            } catch(\Exception $e) {
94
                throw new ModuleConfigException(__CLASS__, $e->getMessage());
95
            }
96
97
            if (get_class($response) === 'Request')
98
            {
99
                if (false === $response->success) {
100
                    throw new ModuleConfigException(__CLASS__, "Proxy response error '{$reponse->status_code}' {$respone->body}");
101
                }
102
            }
103
        }
104
    }
105
106
    public function openProxy($capabilities = null)
107
    {
108
        try {
109
            $this->bmp->open();
110
            if (empty($capabilities)) {
111
                $capabilities = $this->config;
112
            }
113
            $this->__setProxyCapabilities($capabilities);
114
        } catch(\Exception $e) {
115
            throw new ModuleException(__CLASS__, $e->getMessage());
116
        }
117
    }
118
119
    public function closeProxy()
120
    {
121
        try {
122
            $this->bmp->close();
123
        } catch(\Exception $e) {
124
            throw new ModuleException(__CLASS__, $e->getMessage());
125
        }
126
    }
127
128 View Code Duplication
    public function startHar()
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
    {
130
        try {
131
            $response = $this->bmp->newHar();
132
        } catch(\Exception $e) {
133
            throw new ModuleException(__CLASS__, $e->getMessage());
134
        }
135
        return $response->success;
136
    }
137
138 View Code Duplication
    public function startPage()
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
139
    {
140
        try {
141
            $response = $this->bmp->newPage();
142
        } catch(\Exception $e) {
143
            throw new ModuleException(__CLASS__, $e->getMessage());
144
        }
145
        return $response->success;
146
    }
147
148
    public function getHar()
149
    {
150
        try {
151
            return $this->bmp->har;
152
        } catch(\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) { ..._, $e->getMessage()); } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
153
            throw new ModuleException(__CLASS__, $e->getMessage());
154
        }
155
    }
156
157
    public function getLimit()
158
    {
159
        try {
160
            $har = $this->bmp->getLimit();
0 ignored issues
show
Bug introduced by
The method getLimit() does not seem to exist on object<PHPBrowserMobProxy_Client>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Unused Code introduced by
$har is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
161
        } catch(\Exception $e) {
162
            throw new ModuleException(__CLASS__, $e->getMessage());
163
        }
164
    }
165
166
    // magic function giving direct access to BrowserMobProxy class methods
167
    public function __call($method, $args)
168
    {
169
        // check if is a command call
170
        if (preg_match('/^_[A-z]+$/', $method)) {
171
            // extract standard method name
172
            $method = preg_filter('/_/', '', $method);
173
            // set call array for calling method
174
            $call = array($this, $method);
175
            // check if method is callable
176
            if (is_callable($call)) {
177
                call_user_func_array($call, $args);
178
            } else {
179
                throw new RuntimeException("Method ${method} does not exist or is not callable");
180
            }
181
        } else {
182
            throw new RuntimeException("Method ${method} does not exist or is not callable");
183
        }
184
    }
185
186
}
187