1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Tebe\Pvc\Exception; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
|
10
|
|
|
class HttpException extends Exception |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var array |
14
|
|
|
*/ |
15
|
|
|
private $allowed = []; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param string $path |
19
|
|
|
* @param string|null $format |
20
|
|
|
* @return static |
21
|
|
|
*/ |
22
|
|
|
public static function notFound(string $path, string $format = null): HttpException |
23
|
|
|
{ |
24
|
|
|
$format = $format ?? 'Cannot find any resource at `%s`'; |
25
|
|
|
$message = sprintf($format, $path); |
26
|
|
|
return new static($message, 404); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param string $path |
31
|
|
|
* @param string $method |
32
|
|
|
* @param array $allowed |
33
|
|
|
* @param string|null $format |
34
|
|
|
* @return static |
35
|
|
|
*/ |
36
|
|
|
public static function methodNotAllowed( |
37
|
|
|
string $path, |
38
|
|
|
string $method, |
39
|
|
|
array $allowed, |
40
|
|
|
string $format = null |
41
|
|
|
): HttpException { |
42
|
|
|
$format = $format ?? 'Cannot access resource `%s` using method `%s`'; |
43
|
|
|
$message = sprintf($format, $path, $method); |
44
|
|
|
$error = new static($message, 405); |
45
|
|
|
$error->allowed = $allowed; |
46
|
|
|
return $error; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param string $path |
51
|
|
|
* @param string|null $format |
52
|
|
|
* @return static |
53
|
|
|
*/ |
54
|
|
|
public static function badRequest(string $path, string $format = null): HttpException |
55
|
|
|
{ |
56
|
|
|
$format = $format ?? 'Cannot parse the request: %s'; |
57
|
|
|
return new static(sprintf( |
58
|
|
|
$format, |
59
|
|
|
$path |
60
|
|
|
), 400); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param ResponseInterface $response |
65
|
|
|
* @return ResponseInterface |
66
|
|
|
*/ |
67
|
|
|
public function withResponse(ResponseInterface $response): ResponseInterface |
68
|
|
|
{ |
69
|
|
|
if (!empty($this->allowed)) { |
70
|
|
|
$response = $response->withHeader('Allow', implode(',', $this->allowed)); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return $response; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|