1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace whm\Smoke\Rules\Http; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Psr7\Request; |
6
|
|
|
use phm\HttpWebdriverClient\Http\Client\Guzzle\GuzzleClient; |
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use Psr\Http\Message\UriInterface; |
9
|
|
|
use whm\Html\Uri; |
10
|
|
|
use whm\Smoke\Rules\CheckResult; |
11
|
|
|
use whm\Smoke\Rules\Rule; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* This rule can validate if a http request takes longer than a given max duration. |
15
|
|
|
* A website that is slower than one second is considered as slow. |
16
|
|
|
*/ |
17
|
|
|
class RedirectRule implements Rule |
18
|
|
|
{ |
19
|
|
|
private $urls; |
20
|
|
|
|
21
|
|
|
public function init($redirectedUrls) |
22
|
|
|
{ |
23
|
|
|
$this->urls = $redirectedUrls; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function validate(ResponseInterface $response) |
27
|
|
|
{ |
28
|
|
|
$client = new GuzzleClient(); |
29
|
|
|
$errors = []; |
30
|
|
|
|
31
|
|
|
$targetUrl = (string)$this->removeCredentials($response->getUri()); |
|
|
|
|
32
|
|
|
|
33
|
|
|
|
34
|
|
|
foreach ($this->urls as $url) { |
35
|
|
|
$uri = new Uri($url['url']); |
36
|
|
|
|
37
|
|
|
$urlResponses = $client->sendRequests([new Request('GET', $uri)]); |
38
|
|
|
$effectiveUrl = (string)$urlResponses[0]->getEffectiveUri(); |
39
|
|
|
|
40
|
|
|
if ($effectiveUrl != $targetUrl) { |
41
|
|
|
$errors[] = 'The url "' . $url['url'] . '" gets redirected to "' . $effectiveUrl . '".'; |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (count($errors) > 0) { |
46
|
|
|
$message = 'Not all given urls do redirect to "' . $targetUrl . '"".<ul>'; |
47
|
|
|
foreach ($errors as $error) { |
48
|
|
|
$message .= '<li>' . $error . '</li>'; |
49
|
|
|
} |
50
|
|
|
$message .= "</ul>"; |
51
|
|
|
|
52
|
|
|
return new CheckResult(CheckResult::STATUS_FAILURE, $message); |
53
|
|
|
} else { |
54
|
|
|
return new CheckResult(CheckResult::STATUS_SUCCESS, 'All given urls redirect to ' . (string)$response->getUri()); |
|
|
|
|
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private function removeCredentials(UriInterface $uri) |
59
|
|
|
{ |
60
|
|
|
$query = ''; |
61
|
|
|
if ($uri->getQuery()) { |
62
|
|
|
$query = "?" . $uri->getQuery(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$plainUri = $uri->getScheme() . '://' . $uri->getHost() . $uri->getPath() . $query; |
66
|
|
|
|
67
|
|
|
return new Uri($plainUri); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: