@@ -36,6 +36,11 @@ class Controller
3636 */
3737 protected $ exposedRoutesExtractor ;
3838
39+ /**
40+ * @var array
41+ */
42+ protected $ cacheControl ;
43+
3944 /**
4045 * @var boolean
4146 */
@@ -46,12 +51,14 @@ class Controller
4651 *
4752 * @param mixed $serializer Any object with a serialize($data, $format) method
4853 * @param ExposedRoutesExtractorInterface $exposedRoutesExtractor The extractor service.
54+ * @param array $cacheControl
4955 * @param boolean $debug
5056 */
51- public function __construct ($ serializer , ExposedRoutesExtractorInterface $ exposedRoutesExtractor , $ debug = false )
57+ public function __construct ($ serializer , ExposedRoutesExtractorInterface $ exposedRoutesExtractor , array $ cacheControl = array (), $ debug = false )
5258 {
5359 $ this ->serializer = $ serializer ;
5460 $ this ->exposedRoutesExtractor = $ exposedRoutesExtractor ;
61+ $ this ->cacheControl = $ cacheControl ;
5562 $ this ->debug = $ debug ;
5663 }
5764
@@ -96,6 +103,40 @@ public function indexAction(Request $request, $_format)
96103 $ content = $ callback .'( ' .$ content .'); ' ;
97104 }
98105
99- return new Response ($ content , 200 , array ('Content-Type ' => $ request ->getMimeType ($ _format )));
106+ $ response = new Response ($ content , 200 , array ('Content-Type ' => $ request ->getMimeType ($ _format )));
107+
108+ return $ this ->setCacheHeaders ($ response );
109+ }
110+
111+ /**
112+ * @param Response $response
113+ *
114+ * @return Response
115+ */
116+ protected function setCacheHeaders (Response $ response )
117+ {
118+ if (empty ($ this ->cacheControl ['enabled ' ])) {
119+ return $ response ;
120+ }
121+
122+ $ this ->cacheControl ['public ' ] ? $ response ->setPublic () : $ response ->setPrivate ();
123+
124+ if (is_integer ($ this ->cacheControl ['maxage ' ])) {
125+ $ response ->setMaxAge ($ this ->cacheControl ['maxage ' ]);
126+ }
127+
128+ if (is_integer ($ this ->cacheControl ['smaxage ' ])) {
129+ $ response ->setSharedMaxAge ($ this ->cacheControl ['smaxage ' ]);
130+ }
131+
132+ if ($ this ->cacheControl ['expires ' ] !== null ) {
133+ $ response ->setExpires (new \DateTime ($ this ->cacheControl ['expires ' ]));
134+ }
135+
136+ if (!empty ($ this ->cacheControl ['vary ' ])) {
137+ $ response ->setVary ($ this ->cacheControl ['vary ' ]);
138+ }
139+
140+ return $ response ;
100141 }
101142}
0 commit comments