1414namespace ApiPlatform \HttpCache \EventListener ;
1515
1616use ApiPlatform \Core \Metadata \Resource \Factory \ResourceMetadataFactoryInterface ;
17+ use ApiPlatform \Metadata \Resource \Factory \ResourceMetadataCollectionFactoryInterface ;
18+ use ApiPlatform \Util \OperationRequestInitiatorTrait ;
1719use ApiPlatform \Util \RequestAttributesExtractor ;
1820use Symfony \Component \HttpKernel \Event \ResponseEvent ;
1921
2628 */
2729final class AddHeadersListener
2830{
31+ use OperationRequestInitiatorTrait;
32+
2933 private $ etag ;
3034 private $ maxAge ;
3135 private $ sharedMaxAge ;
@@ -35,7 +39,10 @@ final class AddHeadersListener
3539 private $ staleWhileRevalidate ;
3640 private $ staleIfError ;
3741
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 )
3946 {
4047 $ this ->etag = $ etag ;
4148 $ this ->maxAge = $ maxAge ;
@@ -65,13 +72,14 @@ public function onKernelResponse(ResponseEvent $event): void
6572 return ;
6673 }
6774
68- $ resourceCacheHeaders = [];
75+ $ operation = $ this ->initializeOperation ($ request );
76+ $ resourceCacheHeaders = $ attributes ['cache_headers ' ] ?? [];
6977
70- if ($ this ->resourceMetadataFactory ) {
78+ if ($ this ->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface ) {
7179 $ resourceMetadata = $ this ->resourceMetadataFactory ->create ($ attributes ['resource_class ' ]);
7280 $ resourceCacheHeaders = $ resourceMetadata ->getOperationAttribute ($ attributes , 'cache_headers ' , [], true );
73- } else {
74- $ resourceCacheHeaders = $ attributes [ ' cache_headers ' ] ?? [] ;
81+ } elseif ( $ operation ) {
82+ $ resourceCacheHeaders = $ operation -> getCacheHeaders () ;
7583 }
7684
7785 if ($ this ->etag && !$ response ->getEtag ()) {
0 commit comments