Skip to content

Commit 2a2be7c

Browse files
committed
New version
1 parent 2f40b09 commit 2a2be7c

File tree

7 files changed

+76
-151
lines changed

7 files changed

+76
-151
lines changed

CHANGELOG.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](http://keepachangelog.com/)
66
and this project adheres to [Semantic Versioning](http://semver.org/).
77

8+
## [0.9.0] - 2017-12-16
9+
10+
### Changed
11+
12+
- The request handler used to generate the response must implement `Interop\Http\Server\RequestHandlerInterface`. Removed support for callables.
13+
14+
### Removed
15+
16+
- Removed `arguments()` option.
17+
818
## [0.8.0] - 2017-11-13
919

1020
### Changed
@@ -67,6 +77,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
6777

6878
First version
6979

80+
[0.9.0]: https://github.com/middlewares/error-handler/compare/v0.8.0...v0.9.0
7081
[0.8.0]: https://github.com/middlewares/error-handler/compare/v0.7.0...v0.8.0
7182
[0.7.0]: https://github.com/middlewares/error-handler/compare/v0.6.0...v0.7.0
7283
[0.6.0]: https://github.com/middlewares/error-handler/compare/v0.5.0...v0.6.0

README.md

Lines changed: 18 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -28,23 +28,29 @@ composer require middlewares/error-handler
2828
## Example
2929

3030
```php
31+
use Interop\Http\Server\RequestHandlerInterface;
32+
use Psr\Http\Message\ResponseInterface;
3133
use Psr\Http\Message\ServerRequestInterface;
3234

33-
$handler = function (ServerRequestInterface $request) use ($logger) {
34-
//Get the error info as an instance of Middlewares\HttpErrorException
35-
$error = $request->getAttribute('error');
35+
class ErrorRequestHandler implements RequestHandlerInterface
36+
{
37+
public function handle(ServerRequestInterface $request): ResponseInterface
38+
{
39+
//Get the error info as an instance of Middlewares\HttpErrorException
40+
$error = $request->getAttribute('error');
3641

37-
//The error can contains context data that you can use, for example for PSR-3 loggin
38-
$logger->error("There's an error", $error->getContext());
42+
//The error can contains context data that you can use, for example for PSR-3 loggin
43+
Logger::error("There's an error", $error->getContext());
3944

40-
//Any output is captured and added to the response's body
41-
echo $error->getMessage();
45+
//Any output is captured and added to the response's body
46+
echo $error->getMessage();
4247

43-
return (new Response())->withStatus($error->getCode());
44-
};
48+
return (new Response())->withStatus($error->getCode());
49+
}
50+
}
4551

4652
$dispatcher = new Dispatcher([
47-
new Middlewares\ErrorHandler($handler),
53+
new Middlewares\ErrorHandler(new ErrorRequestHandler()),
4854

4955
function ($request, $next) {
5056
$user = Session::signup($request);
@@ -66,31 +72,9 @@ $response = $dispatcher->dispatch(new ServerRequest());
6672

6773
## Options
6874

69-
#### `__construct(string|callable $handler = null)`
70-
71-
Assign the callable used to handle the error. It can be a callable or a string with the format `Class::method`. The signature of the handler is the following:
72-
73-
```php
74-
use Psr\Http\Message\ServerRequestInterface;
75-
76-
$handler = function (ServerRequestInterface $request) {
77-
//Get the error info using the "error" attribute
78-
$error = $request->getAttribute('error');
79-
80-
//Any output is captured and added to the body stream
81-
echo $error->getMessage();
82-
83-
return (new Response())->withStatus($error->getCode());
84-
};
85-
86-
$dispatcher = new Dispatcher([
87-
new Middlewares\ErrorHandler($handler)
88-
]);
89-
90-
$response = $dispatcher->dispatch(new ServerRequest());
91-
```
75+
#### `__construct(Interop\Http\Server\RequestHandlerInterface $handler = null)`
9276

93-
If it's not provided, use [the default](src/ErrorHandlerDefault.php) that provides different outputs for different formats.
77+
The request handler used to generate the response. If it's not provided, use [the default](src/ErrorHandlerDefault.php) that provides different outputs for different formats.
9478

9579
#### `catchExceptions(true)`
9680

@@ -113,31 +97,6 @@ $dispatcher = new Dispatcher([
11397

11498
The attribute name used to store the instance of `Middlewares\HttpErrorException` with the error info in the server request. By default is `error`.
11599

116-
#### `arguments(...$args)`
117-
118-
Extra arguments to pass to the error handler. This is useful to inject, for example a logger:
119-
120-
```php
121-
$handler = function (ServerRequestInterface $request, $logger) {
122-
$error = $request->getAttribute('error');
123-
$message = sprintf('Oops, a "%s" erro ocurried', $error->getCode());
124-
125-
//Log the error
126-
$logger->error($message, $error->getContext());
127-
128-
//Build the response
129-
$response = (new Response())->withStatus($error->getCode());
130-
$response->getBody()->write($message);
131-
132-
return $response;
133-
};
134-
135-
$dispatcher = new Dispatcher([
136-
(new Middlewares\ErrorHandler($handler))
137-
->arguments($logger)
138-
]);
139-
```
140-
141100
---
142101

143102
Please see [CHANGELOG](CHANGELOG.md) for more information about recent changes and [CONTRIBUTING](CONTRIBUTING.md) for contributing details.

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
},
1717
"require": {
1818
"php": "^7.0",
19-
"middlewares/utils": "~0.13",
19+
"middlewares/utils": "~0.14",
2020
"http-interop/http-server-middleware": "^1.0"
2121
},
2222
"require-dev": {

src/ErrorHandler.php

Lines changed: 2 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,14 @@
55

66
use Interop\Http\Server\MiddlewareInterface;
77
use Interop\Http\Server\RequestHandlerInterface;
8-
use Middlewares\Utils\CallableHandler;
98
use Psr\Http\Message\ResponseInterface;
109
use Psr\Http\Message\ServerRequestInterface;
1110
use Throwable;
1211

1312
class ErrorHandler implements MiddlewareInterface
1413
{
15-
/**
16-
* @var callable|string The handler used
17-
*/
1814
private $handler;
1915

20-
/**
21-
* @var array Extra arguments passed to the handler
22-
*/
23-
private $arguments = [];
24-
2516
/**
2617
* @var callable|null The status code validator
2718
*/
@@ -37,12 +28,7 @@ class ErrorHandler implements MiddlewareInterface
3728
*/
3829
private $attribute = 'error';
3930

40-
/**
41-
* Constructor.
42-
*
43-
* @param callable|string|null $handler
44-
*/
45-
public function __construct($handler = 'Middlewares\\ErrorHandlerDefault')
31+
public function __construct(RequestHandlerInterface $handler = null)
4632
{
4733
$this->handler = $handler;
4834
}
@@ -77,16 +63,6 @@ public function attribute(string $attribute): self
7763
return $this;
7864
}
7965

80-
/**
81-
* Extra arguments passed to the handler.
82-
*/
83-
public function arguments(...$arguments): self
84-
{
85-
$this->arguments = $arguments;
86-
87-
return $this;
88-
}
89-
9066
/**
9167
* Process a server request and return a response.
9268
*/
@@ -125,7 +101,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
125101
private function handleError(ServerRequestInterface $request, HttpErrorException $exception): ResponseInterface
126102
{
127103
$request = $request->withAttribute($this->attribute, $exception);
128-
$handler = new CallableHandler($this->handler, $this->arguments);
104+
$handler = $this->handler ?: new ErrorHandlerDefault();
129105

130106
return $handler->handle($request);
131107
}

src/ErrorHandlerDefault.php

Lines changed: 34 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33

44
namespace Middlewares;
55

6+
use Interop\Http\Server\RequestHandlerInterface;
67
use Psr\Http\Message\ResponseInterface;
78
use Psr\Http\Message\ServerRequestInterface;
89

9-
class ErrorHandlerDefault
10+
class ErrorHandlerDefault implements RequestHandlerInterface
1011
{
1112
private $handlers = [
1213
'plain' => [
@@ -37,7 +38,7 @@ class ErrorHandlerDefault
3738
/**
3839
* Execute the error handler.
3940
*/
40-
public function __invoke(ServerRequestInterface $request): ResponseInterface
41+
public function handle(ServerRequestInterface $request): ResponseInterface
4142
{
4243
$error = $request->getAttribute('error');
4344
$accept = $request->getHeaderLine('Accept');
@@ -46,32 +47,32 @@ public function __invoke(ServerRequestInterface $request): ResponseInterface
4647
foreach ($this->handlers as $method => $types) {
4748
foreach ($types as $type) {
4849
if (stripos($accept, $type) !== false) {
49-
call_user_func(__CLASS__.'::'.$method, $error);
50+
$response->getBody()->write(call_user_func(__CLASS__.'::'.$method, $error));
5051

5152
return $response->withHeader('Content-Type', $type);
5253
}
5354
}
5455
}
5556

56-
static::html($error);
57+
$response->getBody()->write(static::html($error));
5758

5859
return $response->withHeader('Content-Type', 'text/html');
5960
}
6061

6162
/**
62-
* Output the error as plain text.
63+
* Return the error as plain text.
6364
*/
64-
public static function plain(HttpErrorException $error)
65+
public static function plain(HttpErrorException $error): string
6566
{
66-
echo sprintf("Error %s\n%s", $error->getCode(), $error->getMessage());
67+
return sprintf("Error %s\n%s", $error->getCode(), $error->getMessage());
6768
}
6869

6970
/**
70-
* Output the error as svg image.
71+
* Return the error as svg image.
7172
*/
72-
public static function svg(HttpErrorException $error)
73+
public static function svg(HttpErrorException $error): string
7374
{
74-
echo <<<EOT
75+
return <<<EOT
7576
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="50" viewBox="0 0 200 50">
7677
<text x="20" y="30" font-family="sans-serif" title="{$error->getMessage()}">
7778
Error {$error->getCode()}
@@ -81,11 +82,11 @@ public static function svg(HttpErrorException $error)
8182
}
8283

8384
/**
84-
* Output the error as html.
85+
* Return the error as html.
8586
*/
86-
public static function html(HttpErrorException $error)
87+
public static function html(HttpErrorException $error): string
8788
{
88-
echo <<<EOT
89+
return <<<EOT
8990
<!DOCTYPE html>
9091
<html>
9192
<head>
@@ -103,11 +104,11 @@ public static function html(HttpErrorException $error)
103104
}
104105

105106
/**
106-
* Output the error as json.
107+
* Return the error as json.
107108
*/
108-
public static function json(HttpErrorException $error)
109+
public static function json(HttpErrorException $error): string
109110
{
110-
echo json_encode([
111+
return json_encode([
111112
'error' => [
112113
'code' => $error->getCode(),
113114
'message' => $error->getMessage(),
@@ -116,11 +117,11 @@ public static function json(HttpErrorException $error)
116117
}
117118

118119
/**
119-
* Output the error as xml.
120+
* Return the error as xml.
120121
*/
121-
public static function xml(HttpErrorException $error)
122+
public static function xml(HttpErrorException $error): string
122123
{
123-
echo <<<EOT
124+
return <<<EOT
124125
<?xml version="1.0" encoding="UTF-8"?>
125126
<error>
126127
<code>{$error->getCode()}</code>
@@ -130,41 +131,33 @@ public static function xml(HttpErrorException $error)
130131
}
131132

132133
/**
133-
* Output the error as jpeg.
134+
* Return the error as jpeg.
134135
*/
135-
public static function jpeg(HttpErrorException $error)
136+
public static function jpeg(HttpErrorException $error): string
136137
{
137-
$image = self::createImage($error);
138-
139-
imagejpeg($image);
138+
return self::getImage($error, 'imagejpeg');
140139
}
141140

142141
/**
143-
* Output the error as gif.
142+
* Return the error as gif.
144143
*/
145-
public static function gif(HttpErrorException $error)
144+
public static function gif(HttpErrorException $error): string
146145
{
147-
$image = self::createImage($error);
148-
149-
imagegif($image);
146+
return self::getImage($error, 'imagegif');
150147
}
151148

152149
/**
153-
* Output the error as png.
150+
* Return the error as png.
154151
*/
155-
public static function png(HttpErrorException $error)
152+
public static function png(HttpErrorException $error): string
156153
{
157-
$image = self::createImage($error);
158-
159-
imagepng($image);
154+
return self::getImage($error, 'imagepng');
160155
}
161156

162157
/**
163-
* Creates a image resource with the error text.
164-
*
165-
* @return resource
158+
* Create and return a image as string.
166159
*/
167-
private static function createImage(HttpErrorException $error)
160+
private static function getImage(HttpErrorException $error, callable $function): string
168161
{
169162
$size = 200;
170163
$image = imagecreatetruecolor($size, $size);
@@ -175,6 +168,8 @@ private static function createImage(HttpErrorException $error)
175168
imagestring($image, 5, 10, ($line * 18) + 28, $text, $textColor);
176169
}
177170

178-
return $image;
171+
ob_start();
172+
$function($image);
173+
return ob_get_clean();
179174
}
180175
}

src/HttpErrorException.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ class HttpErrorException extends Exception
6868
*
6969
* @return static
7070
*/
71-
public static function create(int $code = 500, array $context = [], Throwable $previous = null)
71+
public static function create(int $code = 500, array $context = [], Throwable $previous = null): self
7272
{
7373
if (!isset(self::$phrases[$code])) {
7474
throw new RuntimeException("Http error not valid ({$code})");

0 commit comments

Comments
 (0)