Completed
Push — master ( 857c7b...99b751 )
by Nils
01:45
created

Retriever::next()   C

Complexity

Conditions 9
Paths 15

Size

Total Lines 58
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 0
Metric Value
c 3
b 2
f 0
dl 0
loc 58
rs 6.9928
cc 9
eloc 34
nc 15
nop 0

How to fix   Long Method   

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
3
namespace whm\Smoke\Extensions\SmokeResponseRetriever\Retriever\ListRetriever;
4
5
use GuzzleHttp\Psr7\Request;
6
use phm\HttpWebdriverClient\Http\Client\HttpClient;
7
use phm\HttpWebdriverClient\Http\MultiRequestsException;
8
use Psr\Http\Message\UriInterface;
9
use whm\Crawler\Http\RequestFactory;
10
use whm\Html\Uri;
11
use whm\Smoke\Extensions\SmokeResponseRetriever\Retriever\Retriever as SmokeRetriever;
12
use whm\Smoke\Scanner\SessionContainer;
13
14
class Retriever implements SmokeRetriever
15
{
16
    private $urls = [];
17
18
    /**
19
     * @var HttpClient
20
     */
21
    private $httpClient;
22
    private $urlStack = [];
23
24
    private $redirects = array();
25
26
    /**
27
     * @var SessionContainer
28
     */
29
    private $sessionContainer;
30
31
    public function init($urls)
32
    {
33
        if (is_array($urls)) {
34
            foreach ($urls as $key => $urlList) {
35
                foreach ($urlList as $url) {
36
                    if (is_array($url)) {
37
                        $uri = new Uri($url['url']);
38
                        if (array_key_exists('cookies', $url)) {
39
                            foreach ($url['cookies'] as $cookie) {
40
                                foreach ($cookie as $key => $value) {
41
                                    $uri->addCookie($key, $value);
42
                                }
43
                            }
44
                        }
45
                        if (array_key_exists('session', $url)) {
46
                            $sessionName = $url['session'];
47
                            $uri->setSessionIdentifier($sessionName);
48
                        }
49
                        $this->urls[$url['url']] = ['url' => $uri, 'system' => $key];
50
                    } else {
51
                        $this->urls[$url] = ['url' => new Uri($url), 'system' => $key];
52
                    }
53
                }
54
            }
55
            $this->urlStack = $this->urls;
56
        }
57
    }
58
59
    /**
60
     * @param Uri $uri
61
     *
62
     * @return Request
63
     */
64
    private function createRequest(Uri $uri)
65
    {
66
        $headers = ['Accept-Encoding' => 'gzip', 'Connection' => 'keep-alive'];
67
68
        if ($uri->getSessionIdentifier()) {
69
            $session = $this->sessionContainer->getSession($uri->getSessionIdentifier());
70
71
            foreach ($session->getCookies() as $key => $value) {
72
                $uri->addCookie($key, $value);
73
            }
74
        }
75
76
        $request = RequestFactory::getRequest($uri, 'GET', 'php://memory', $headers);
77
78
        return $request;
79
    }
80
81
    public function next()
82
    {
83
        if (empty($this->urlStack)) {
84
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface whm\Smoke\Extensions\Smo...triever\Retriever::next of type Psr\Http\Message\ResponseInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
85
        }
86
87
        $url = array_pop($this->urlStack);
88
89
        if ($url['url'] instanceof UriInterface) {
90
            $urlObject = $url['url'];
91
        } else {
92
            $urlObject = new Uri($url['url']);
93
        }
94
95
        $request = $this->createRequest($urlObject);
96
97
        try {
98
            $responses = $this->httpClient->sendRequests(array($request));
99
        } catch (MultiRequestsException $e) {
100
            $exceptions = $e->getExceptions();
101
            /* @var \Exception[] $exceptions */
102
103
            $errorMessages = '';
104
            foreach ($exceptions as $exception) {
105
                // @fixme this must be part of the http client
106
                $message = $exception->getMessage();
107
                if (strpos($message, 'An error occurred when fetching the URI') === 0) {
108
                    $corruptUrl = substr($message, '41', strpos($message, '"', 41) - 41);
109
                    if (strpos($corruptUrl, '/') === 0) {
110
111
                        $mainUri = $request->getUri();
112
                        $this->redirects[(string)$mainUri->getScheme() . '://' . $mainUri->getHost() . $corruptUrl] = (string)$mainUri;
113
114
                        $this->urls[] = ['url' => $mainUri->getScheme() . '://' . $mainUri->getHost() . $corruptUrl, 'system' => $url['system']];
115
                        $this->urlStack[] = ['url' => $mainUri->getScheme() . '://' . $mainUri->getHost() . $corruptUrl, 'system' => $url['system']];
116
117
                        return $this->next();
118
                    }
119
120
                    // the error handling should be done withing the calling class
121
                    echo "\n   " . $exception->getMessage() . "\n";
122
123
                    return $this->next();
124
                } else {
125
                    $errorMessages .= $exception->getMessage() . "\n";
126
                }
127
            }
128
            if ($errorMessages !== '') {
129
                throw new \RuntimeException($errorMessages);
130
            }
131
        }
132
133
        if (empty($responses)) {
134
            return $this->next();
135
        } else {
136
            return $responses[0];
137
        }
138
    }
139
140 View Code Duplication
    public function getOriginUri(UriInterface $uri)
141
    {
142
        if (array_key_exists((string)$uri, $this->redirects)) {
143
            return $this->urls[$this->redirects[(string)$uri]]['url'];
144
        }
145
146
        return $uri;
147
    }
148
149
    public function getComingFrom(UriInterface $uri)
150
    {
151
        return $uri;
152
    }
153
154 View Code Duplication
    public function getSystem(UriInterface $uri)
155
    {
156
        if (array_key_exists((string)$uri, $this->redirects)) {
157
            return $this->urls[$this->redirects[(string)$uri]]['system'];
158
        }
159
160
        return $this->urls[(string)$uri]['system'];
161
    }
162
163
    public function getSystems()
164
    {
165
        $systems = [];
166
        foreach ($this->urls as $key => $url) {
167
            $systems[] = $url['system'];
168
        }
169
170
        return $systems;
171
    }
172
173
    public function setHttpClient(HttpClient $httpClient)
174
    {
175
        $this->httpClient = $httpClient;
176
    }
177
178
    public function setSessionContainer(SessionContainer $sessionContainer)
179
    {
180
        $this->sessionContainer = $sessionContainer;
181
    }
182
}
183