1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Middleware; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
7
|
|
|
|
8
|
|
|
class JsonSchema |
9
|
|
|
{ |
10
|
|
|
/** @var string[] */ |
11
|
|
|
private $schemas; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* JsonSchema constructor. |
15
|
|
|
* |
16
|
|
|
* @param string[] $schemas [uri => file] An associative array of HTTP URI to validation schema |
17
|
|
|
*/ |
18
|
|
|
public function __construct(array $schemas) |
19
|
|
|
{ |
20
|
|
|
$this->schemas = $schemas; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Execute the middleware. |
25
|
|
|
* |
26
|
|
|
* @param ServerRequestInterface $request |
27
|
|
|
* @param ResponseInterface $response |
28
|
|
|
* @param callable $next |
29
|
|
|
* |
30
|
|
|
* @return ResponseInterface |
31
|
|
|
*/ |
32
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
33
|
|
|
{ |
34
|
|
|
$schema = $this->getSchema($request); |
35
|
|
|
|
36
|
|
|
if ($schema instanceof \SplFileObject) { |
37
|
|
|
$validator = JsonValidator::fromFile($schema); |
38
|
|
|
return $validator($request, $response, $next); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
return $next($request, $response); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param ServerRequestInterface $request |
46
|
|
|
* |
47
|
|
|
* @return \SplFileObject|null |
48
|
|
|
*/ |
49
|
|
|
private function getSchema(ServerRequestInterface $request) |
50
|
|
|
{ |
51
|
|
|
$uri = $request->getUri(); |
52
|
|
|
$path = $uri->getPath(); |
53
|
|
|
|
54
|
|
|
foreach ($this->schemas as $pattern => $file) { |
55
|
|
|
if (stripos($path, $pattern) === 0) { |
56
|
|
|
return new \SplFileObject($this->normalizeFilePath($file)); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return null; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param string |
65
|
|
|
* |
66
|
|
|
* @return string |
67
|
|
|
*/ |
68
|
|
|
private function normalizeFilePath($path) |
69
|
|
|
{ |
70
|
|
|
if (parse_url($path, PHP_URL_SCHEME)) { |
71
|
|
|
// The schema file already has a scheme, e.g. `file://` or `vfs://`. |
72
|
|
|
return $path; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return 'file://'.$path; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|