Completed
Push — master ( e09e40...2564b7 )
by Nils
02:09
created

Retriever::createRequest()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 4
nop 1
1
<?php
2
3
namespace whm\Smoke\Extensions\SmokeResponseRetriever\Retriever\ListRetriever;
4
5
use Ivory\HttpAdapter\HttpAdapterInterface;
6
use Ivory\HttpAdapter\MultiHttpAdapterException;
7
use Psr\Http\Message\UriInterface;
8
use whm\Crawler\Http\RequestFactory;
9
use whm\Html\Uri;
10
use whm\Smoke\Extensions\SmokeResponseRetriever\Retriever\Retriever as SmokeRetriever;
11
use whm\Smoke\Scanner\SessionContainer;
12
13
class Retriever implements SmokeRetriever
14
{
15
    private $urls = [];
16
    private $httpClient;
17
    private $urlStack = [];
18
19
    private $redirects = array();
20
21
    /**
22
     * @var SessionContainer
23
     */
24
    private $sessionContainer;
25
26
    public function init($urls)
27
    {
28
        if (is_array($urls)) {
29
            foreach ($urls as $key => $urlList) {
30
                foreach ($urlList as $url) {
31
                    if (is_array($url)) {
32
                        $uri = new Uri($url['url']);
33
                        if (array_key_exists('cookies', $url)) {
34
                            foreach ($url['cookies'] as $cookie) {
35
                                foreach ($cookie as $key => $value) {
36
                                    $uri->addCookie($key, $value);
0 ignored issues
show
Bug introduced by
The method addCookie() does not seem to exist on object<whm\Html\Uri>.

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...
37
                                }
38
                            }
39
                        }
40
                        if (array_key_exists('session', $url)) {
41
                            $sessionName = $url['session'];
42
                            $uri->setSessionIdentifier($sessionName);
0 ignored issues
show
Bug introduced by
The method setSessionIdentifier() does not seem to exist on object<whm\Html\Uri>.

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...
43
                        }
44
                        $this->urls[$url['url']] = ['url' => $uri, 'system' => $key];
45
                    } else {
46
                        $this->urls[$url] = ['url' => new Uri($url), 'system' => $key];
47
                    }
48
                }
49
            }
50
            $this->urlStack = $this->urls;
51
        }
52
    }
53
54
    /**
55
     * @param Uri $uri
56
     *
57
     * @return \Ivory\HttpAdapter\Message\Request
58
     */
59
    private function createRequest(Uri $uri)
60
    {
61
        $headers = ['Accept-Encoding' => 'gzip', 'Connection' => 'keep-alive'];
62
63
        if ($uri->getSessionIdentifier()) {
0 ignored issues
show
Bug introduced by
The method getSessionIdentifier() does not seem to exist on object<whm\Html\Uri>.

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...
64
            $session = $this->sessionContainer->getSession($uri->getSessionIdentifier());
0 ignored issues
show
Bug introduced by
The method getSessionIdentifier() does not seem to exist on object<whm\Html\Uri>.

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...
65
            foreach ($session->getCookies() as $key => $value) {
66
                $uri->addCookie($key, $value);
0 ignored issues
show
Bug introduced by
The method addCookie() does not seem to exist on object<whm\Html\Uri>.

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...
67
            }
68
        }
69
70
        if ($uri->hasCookies()) {
0 ignored issues
show
Bug introduced by
The method hasCookies() does not seem to exist on object<whm\Html\Uri>.

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...
71
            $headers['Cookie'] = $uri->getCookieString();
0 ignored issues
show
Bug introduced by
The method getCookieString() does not seem to exist on object<whm\Html\Uri>.

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...
72
        }
73
74
        $request = RequestFactory::getRequest($uri, 'GET', 'php://memory', $headers);
75
76
        return $request;
77
    }
78
79
    public function next()
80
    {
81
        if (empty($this->urlStack)) {
82
            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 whm\Smoke\Http\Response.

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