Skip to content

Handle redirections before creating HTML response #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 34 additions & 17 deletions src/PhpDebugBarMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ public function __construct(DebugBarRenderer $debugbarRenderer)

/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable $next
* @param ResponseInterface $response
* @param callable $next
*
* @return ResponseInterface
*/
Expand All @@ -47,7 +47,7 @@ public function __invoke(ServerRequestInterface $request, ResponseInterface $res

$outResponse = $next($request, $response);

if (!$this->isHtmlAccepted($request)) {
if (!$this->isHtmlAccepted($request) || $this->isRedirect($outResponse)) {
return $outResponse;
}

Expand All @@ -64,10 +64,10 @@ public function __invoke(ServerRequestInterface $request, ResponseInterface $res
return $outResponse;
}

$outResponseBody = Serializer::toString($outResponse);
$template = '<html><head>%s</head><body><h1>DebugBar</h1><p>Response:</p><pre>%s</pre>%s</body></html>';
$outResponseBody = Serializer::toString($outResponse);
$template = '<html><head>%s</head><body><h1>DebugBar</h1><p>Response:</p><pre>%s</pre>%s</body></html>';
$escapedOutResponseBody = htmlspecialchars($outResponseBody);
$result = sprintf($template, $debugBarHead, $escapedOutResponseBody, $debugBarBody);
$result = sprintf($template, $debugBarHead, $escapedOutResponseBody, $debugBarBody);

return new HtmlResponse($result);
}
Expand All @@ -91,9 +91,9 @@ private function getStaticFile(UriInterface $uri)
return;
}

$stream = new Stream($fullPathToFile, 'r');
$stream = new Stream($fullPathToFile, 'r');
$staticResponse = new Response($stream);
$contentType = $this->getContentTypeByFileName($fullPathToFile);
$contentType = $this->getContentTypeByFileName($fullPathToFile);

return $staticResponse->withHeader('Content-type', $contentType);
}
Expand All @@ -108,13 +108,13 @@ private function getContentTypeByFileName($filename)
$ext = pathinfo($filename, PATHINFO_EXTENSION);

$map = [
'css' => 'text/css',
'js' => 'text/javascript',
'otf' => 'font/opentype',
'eot' => 'application/vnd.ms-fontobject',
'svg' => 'image/svg+xml',
'ttf' => 'application/font-sfnt',
'woff' => 'application/font-woff',
'css' => 'text/css',
'js' => 'text/javascript',
'otf' => 'font/opentype',
'eot' => 'application/vnd.ms-fontobject',
'svg' => 'image/svg+xml',
'ttf' => 'application/font-sfnt',
'woff' => 'application/font-woff',
'woff2' => 'application/font-woff2',
];

Expand Down Expand Up @@ -147,13 +147,30 @@ private function isHtmlAccepted(ServerRequestInterface $request)

/**
* @param MessageInterface $message
* @param string $headerName
* @param string $value
* @param string $headerName
* @param string $value
*
* @return bool
*/
private function hasHeaderContains(MessageInterface $message, $headerName, $value)
{
return strpos($message->getHeaderLine($headerName), $value) !== false;
}

/**
* Returns a boolean TRUE for if the response has redirect status code.
*
* Five common HTTP status codes indicates a redirection beginning from 301.
* 304 not modified and 305 use proxy are not redirects.
*
* @see https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection
*
* @param MessageInterface $message
*
* @return bool
*/
private function isRedirect(ResponseInterface $response)
{
return in_array($response->getStatusCode(), [301, 302, 303, 307, 308]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if I send 301 without Location header?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about that. Debugbar may just return it. RFC says:

The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

IMHO producing a 301 response without a location header would a bad response for other layers too like nginx/apache and browsers. I think this is developer's responsibility.

}
}
74 changes: 56 additions & 18 deletions test/PhpDebugBarMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,17 @@ class PhpDebugBarMiddlewareTest extends PHPUnit_Framework_TestCase
protected function setUp()
{
$this->debugbarRenderer = $this->getMockBuilder(JavascriptRenderer::class)->disableOriginalConstructor()->getMock();
$this->middleware = new PhpDebugBarMiddleware($this->debugbarRenderer);
$this->middleware = new PhpDebugBarMiddleware($this->debugbarRenderer);
}

public function testNotAttachIfNotAccept()
{
$request = new ServerRequest();
$response = new Response();
$calledOut = false;
$request = new ServerRequest();
$response = new Response();
$calledOut = false;
$outFunction = function ($request, $response) use (&$calledOut) {
$calledOut = true;

return $response;
};

Expand All @@ -44,12 +45,13 @@ public function testNotAttachIfNotAccept()

public function testAttachToNoneHtmlResponse()
{
$request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']);
$request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']);
$response = new Response();
$response->getBody()->write('ResponseBody');
$calledOut = false;
$calledOut = false;
$outFunction = function ($request, $response) use (&$calledOut) {
$calledOut = true;

return $response;
};

Expand All @@ -65,12 +67,13 @@ public function testAttachToNoneHtmlResponse()

public function testAttachToHtmlResponse()
{
$request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']);
$request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']);
$response = new Response('php://memory', 200, ['Content-Type' => 'text/html']);
$response->getBody()->write('ResponseBody');
$calledOut = false;
$calledOut = false;
$outFunction = function ($request, $response) use (&$calledOut) {
$calledOut = true;

return $response;
};

Expand All @@ -86,12 +89,13 @@ public function testAttachToHtmlResponse()

public function testAppendsToEndOfHtmlResponse()
{
$html = '<html><head><title>Foo</title></head><body>Content</body>';
$request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']);
$response = new Response\HtmlResponse($html);
$calledOut = false;
$html = '<html><head><title>Foo</title></head><body>Content</body>';
$request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']);
$response = new Response\HtmlResponse($html);
$calledOut = false;
$outFunction = function ($request, $response) use (&$calledOut) {
$calledOut = true;

return $response;
};

Expand All @@ -109,13 +113,14 @@ public function testTryToHandleNotExistingStaticFile()
{
$this->debugbarRenderer->expects($this->any())->method('getBaseUrl')->willReturn('/phpdebugbar');

$uri = new Uri('http://example.com/phpdebugbar/boo.css');
$request = new ServerRequest([], [], $uri, null, 'php://memory');
$uri = new Uri('http://example.com/phpdebugbar/boo.css');
$request = new ServerRequest([], [], $uri, null, 'php://memory');
$response = new Response\HtmlResponse('<html></html>');

$calledOut = false;
$calledOut = false;
$outFunction = function ($request, $response) use (&$calledOut) {
$calledOut = true;

return $response;
};

Expand All @@ -134,15 +139,16 @@ public function testHandleStaticFile($extension, $contentType)
$this->debugbarRenderer->expects($this->any())->method('getBaseUrl')->willReturn('/phpdebugbar');
$this->debugbarRenderer->expects($this->any())->method('getBasePath')->willReturn(vfsStream::url('boo'));

$uri = new Uri(sprintf('http://example.com/phpdebugbar/debugbar.%s', $extension));
$request = new ServerRequest([], [], $uri, null, 'php://memory');
$uri = new Uri(sprintf('http://example.com/phpdebugbar/debugbar.%s', $extension));
$request = new ServerRequest([], [], $uri, null, 'php://memory');
$response = new Response\HtmlResponse('<html></html>');

vfsStream::newFile(sprintf('debugbar.%s', $extension))->withContent('filecontent')->at($root);

$calledOut = false;
$calledOut = false;
$outFunction = function ($request, $response) use (&$calledOut) {
$calledOut = true;

return $response;
};

Expand All @@ -153,6 +159,38 @@ public function testHandleStaticFile($extension, $contentType)
$this->assertSame('filecontent', (string) $result->getBody());
}

/**
* @dataProvider statusCodeProvider
*/
public function testHandleRedirects($code, $handle)
{
$request = new ServerRequest();
$response = new Response('php://memory', $code, ['Location' => 'http://www.foo.bar']);
$calledOut = false;
$outFunction = function ($request, $response) use (&$calledOut) {
$calledOut = true;

return $response;
};

$result = call_user_func($this->middleware, $request, $response, $outFunction);

$this->assertEquals($response->getStatusCode() === $code, $handle);
$this->assertTrue($calledOut, 'Out is not called');
$this->assertSame($response, $result);
}

public function statusCodeProvider()
{
return [
[301, true],
[302, true],
[303, true],
[307, true],
[308, true],
];
}

public function getContentTypes()
{
return [
Expand Down