14
14
namespace ApiPlatform \HttpCache \EventListener ;
15
15
16
16
use ApiPlatform \Core \Metadata \Resource \Factory \ResourceMetadataFactoryInterface ;
17
+ use ApiPlatform \Metadata \Resource \Factory \ResourceMetadataCollectionFactoryInterface ;
18
+ use ApiPlatform \Util \OperationRequestInitiatorTrait ;
17
19
use ApiPlatform \Util \RequestAttributesExtractor ;
18
20
use Symfony \Component \HttpKernel \Event \ResponseEvent ;
19
21
26
28
*/
27
29
final class AddHeadersListener
28
30
{
31
+ use OperationRequestInitiatorTrait;
32
+
29
33
private $ etag ;
30
34
private $ maxAge ;
31
35
private $ sharedMaxAge ;
@@ -35,7 +39,10 @@ final class AddHeadersListener
35
39
private $ staleWhileRevalidate ;
36
40
private $ staleIfError ;
37
41
38
- public function __construct (bool $ etag = false , int $ maxAge = null , int $ sharedMaxAge = null , array $ vary = null , bool $ public = null , ResourceMetadataFactoryInterface $ resourceMetadataFactory = null , int $ staleWhileRevalidate = null , int $ staleIfError = null )
42
+ /**
43
+ * @param ResourceMetadataFactoryInterface|ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory
44
+ */
45
+ public function __construct (bool $ etag = false , int $ maxAge = null , int $ sharedMaxAge = null , array $ vary = null , bool $ public = null , $ resourceMetadataFactory = null , int $ staleWhileRevalidate = null , int $ staleIfError = null )
39
46
{
40
47
$ this ->etag = $ etag ;
41
48
$ this ->maxAge = $ maxAge ;
@@ -65,13 +72,14 @@ public function onKernelResponse(ResponseEvent $event): void
65
72
return ;
66
73
}
67
74
68
- $ resourceCacheHeaders = [];
75
+ $ operation = $ this ->initializeOperation ($ request );
76
+ $ resourceCacheHeaders = $ attributes ['cache_headers ' ] ?? [];
69
77
70
- if ($ this ->resourceMetadataFactory ) {
78
+ if ($ this ->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface ) {
71
79
$ resourceMetadata = $ this ->resourceMetadataFactory ->create ($ attributes ['resource_class ' ]);
72
80
$ resourceCacheHeaders = $ resourceMetadata ->getOperationAttribute ($ attributes , 'cache_headers ' , [], true );
73
- } else {
74
- $ resourceCacheHeaders = $ attributes [ ' cache_headers ' ] ?? [] ;
81
+ } elseif ( $ operation ) {
82
+ $ resourceCacheHeaders = $ operation -> getCacheHeaders () ;
75
83
}
76
84
77
85
if ($ this ->etag && !$ response ->getEtag ()) {
0 commit comments