-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiddleware.php
More file actions
61 lines (47 loc) · 1.53 KB
/
Middleware.php
File metadata and controls
61 lines (47 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
/**
* The InertiaJS middleware.
*
* @package TheWebSolver\Codegarage\Library
*/
declare( strict_types = 1 );
namespace TheWebSolver\Codegarage\Lib\Inertia;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class Middleware implements MiddlewareInterface {
private readonly string $rootView;
private readonly string $version;
public function set( string $version = '1.0', string $rootView = '' ): static {
$this->rootView ??= $rootView;
$this->version ??= $version;
return $this;
}
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
$response = Header::Vary->addTo( $handler->handle( $request ), value: Header::Inertia->value );
// Run subscriber during middleware process.
Inertia::subscribe( subscriber: false );
if ( $this->version ?? false ) {
Inertia::setVersion( $this->version );
}
Inertia::share(
data: array( 'errors' => $request->getAttribute( 'validationErrors', default: array() ) )
);
if ( $this->rootView ?? false ) {
Inertia::setRoot( $this->rootView );
}
if ( ! Inertia::active( $request ) ) {
return $response;
}
return $this->needsCacheBusting( $request )
? Inertia::reloadServer( $request, $response )
: $response;
}
private function needsCacheBusting( ServerRequestInterface $request ): bool {
return 'GET' === $request->getMethod() && ! Inertia::sameVersion( $request );
}
}