11<?php namespace App \Http \Middleware ;
22/**
3- * Copyright 2015 OpenStack Foundation
3+ * Copyright 2022 OpenStack Foundation
44 * Licensed under the Apache License, Version 2.0 (the "License");
55 * you may not use this file except in compliance with the License.
66 * You may obtain a copy of the License at
1111 * See the License for the specific language governing permissions and
1212 * limitations under the License.
1313 **/
14-
1514use Closure ;
16- use Log ;
17-
15+ use Illuminate \Support \Facades \Log ;
1816/**
1917 * Class ETagsMiddleware
2018 * @package App\Http\Middleware
2119 */
2220final class ETagsMiddleware
2321{
2422
25-
2623 /**
2724 * Handle an incoming request.
2825 * @param \Illuminate\Http\Request $request
@@ -31,21 +28,41 @@ final class ETagsMiddleware
3128 */
3229 public function handle ($ request , Closure $ next )
3330 {
31+ // Handle request
32+ $ method = $ request ->getMethod ();
33+
34+ // Support using HEAD method for checking If-None-Match
35+ if ($ request ->isMethod ('HEAD ' )) {
36+ $ request ->setMethod ('GET ' );
37+ }
38+ //Handle response
3439 $ response = $ next ($ request );
40+
3541 if ($ response ->getStatusCode () === 200 && $ request ->getMethod () === 'GET ' )
3642 {
37- $ etag = md5 ($ response ->getContent ());
43+ $ etag = md5 ($ response ->getContent ());
3844 $ requestETag = str_replace ('" ' , '' , $ request ->getETags ());
3945 $ requestETag = str_replace ('-gzip ' , '' , $ requestETag );
46+ if ($ requestETag && is_array ($ requestETag ))
47+ Log::debug (sprintf ("ETagsMiddleware::handle requestEtag %s calculated etag %s " , $ requestETag [0 ], $ etag ));
4048
41- if ($ requestETag && $ requestETag [0 ] == $ etag )
42- {
43- Log::debug ('ETAG 304 ' );
49+ // Strip W/ if weak comparison algorithm can be used
50+ $ requestETag = array_map ([$ this , 'stripWeakTags ' ], $ requestETag );
51+
52+ if (in_array ($ etag , $ requestETag )) {
4453 $ response ->setNotModified ();
4554 }
55+
4656 $ response ->setEtag ($ etag );
4757 }
4858
59+ $ request ->setMethod ($ method );
60+
4961 return $ response ;
5062 }
63+
64+ private function stripWeakTags ($ etag )
65+ {
66+ return str_replace ('W/ ' , '' , $ etag );
67+ }
5168}
0 commit comments