1
|
|
|
<?php |
2
|
|
|
namespace Shlinkio\Shlink\Core\Middleware; |
3
|
|
|
|
4
|
|
|
use Acelaya\ZsmAnnotatedServices\Annotation\Inject; |
5
|
|
|
use Doctrine\Common\Cache\Cache; |
6
|
|
|
use Interop\Http\ServerMiddleware\DelegateInterface; |
7
|
|
|
use Interop\Http\ServerMiddleware\MiddlewareInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
10
|
|
|
use Zend\Diactoros\Response as DiactResp; |
11
|
|
|
|
12
|
|
|
class QrCodeCacheMiddleware implements MiddlewareInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var Cache |
16
|
|
|
*/ |
17
|
|
|
private $cache; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* QrCodeCacheMiddleware constructor. |
21
|
|
|
* @param Cache $cache |
22
|
|
|
* |
23
|
|
|
* @Inject({Cache::class}) |
24
|
|
|
*/ |
25
|
2 |
|
public function __construct(Cache $cache) |
26
|
|
|
{ |
27
|
2 |
|
$this->cache = $cache; |
28
|
2 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Process an incoming server request and return a response, optionally delegating |
32
|
|
|
* to the next middleware component to create the response. |
33
|
|
|
* |
34
|
|
|
* @param Request $request |
35
|
|
|
* @param DelegateInterface $delegate |
36
|
|
|
* |
37
|
|
|
* @return Response |
38
|
|
|
*/ |
39
|
2 |
|
public function process(Request $request, DelegateInterface $delegate) |
40
|
|
|
{ |
41
|
2 |
|
$cacheKey = $request->getUri()->getPath(); |
42
|
|
|
|
43
|
|
|
// If this QR code is already cached, just return it |
44
|
2 |
|
if ($this->cache->contains($cacheKey)) { |
45
|
1 |
|
$qrData = $this->cache->fetch($cacheKey); |
46
|
1 |
|
$response = new DiactResp(); |
47
|
1 |
|
$response->getBody()->write($qrData['body']); |
48
|
1 |
|
return $response->withHeader('Content-Type', $qrData['content-type']); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
// If not, call the next middleware and cache it |
52
|
|
|
/** @var Response $resp */ |
53
|
1 |
|
$resp = $delegate->process($request); |
54
|
1 |
|
$this->cache->save($cacheKey, [ |
55
|
1 |
|
'body' => $resp->getBody()->__toString(), |
56
|
1 |
|
'content-type' => $resp->getHeaderLine('Content-Type'), |
57
|
1 |
|
]); |
58
|
1 |
|
return $resp; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|