|
1
|
|
|
<?php |
|
2
|
|
|
namespace Shlinkio\Shlink\Core\Action; |
|
3
|
|
|
|
|
4
|
|
|
use Acelaya\ZsmAnnotatedServices\Annotation\Inject; |
|
5
|
|
|
use Interop\Http\ServerMiddleware\DelegateInterface; |
|
6
|
|
|
use Interop\Http\ServerMiddleware\MiddlewareInterface; |
|
7
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
|
8
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
|
9
|
|
|
use Shlinkio\Shlink\Common\Service\PreviewGenerator; |
|
10
|
|
|
use Shlinkio\Shlink\Common\Service\PreviewGeneratorInterface; |
|
11
|
|
|
use Shlinkio\Shlink\Common\Util\ResponseUtilsTrait; |
|
12
|
|
|
use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; |
|
13
|
|
|
use Shlinkio\Shlink\Core\Service\UrlShortener; |
|
14
|
|
|
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface; |
|
15
|
|
|
|
|
16
|
|
|
class PreviewAction implements MiddlewareInterface |
|
17
|
|
|
{ |
|
18
|
|
|
use ResponseUtilsTrait; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var PreviewGeneratorInterface |
|
22
|
|
|
*/ |
|
23
|
|
|
private $previewGenerator; |
|
24
|
|
|
/** |
|
25
|
|
|
* @var UrlShortenerInterface |
|
26
|
|
|
*/ |
|
27
|
|
|
private $urlShortener; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* PreviewAction constructor. |
|
31
|
|
|
* @param PreviewGeneratorInterface $previewGenerator |
|
32
|
|
|
* @param UrlShortenerInterface $urlShortener |
|
33
|
|
|
* |
|
34
|
|
|
* @Inject({PreviewGenerator::class, UrlShortener::class}) |
|
35
|
|
|
*/ |
|
36
|
3 |
|
public function __construct(PreviewGeneratorInterface $previewGenerator, UrlShortenerInterface $urlShortener) |
|
37
|
|
|
{ |
|
38
|
3 |
|
$this->previewGenerator = $previewGenerator; |
|
39
|
3 |
|
$this->urlShortener = $urlShortener; |
|
40
|
3 |
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Process an incoming server request and return a response, optionally delegating |
|
44
|
|
|
* to the next middleware component to create the response. |
|
45
|
|
|
* |
|
46
|
|
|
* @param Request $request |
|
47
|
|
|
* @param DelegateInterface $delegate |
|
48
|
|
|
* |
|
49
|
|
|
* @return Response |
|
50
|
|
|
*/ |
|
51
|
3 |
|
public function process(Request $request, DelegateInterface $delegate) |
|
52
|
|
|
{ |
|
53
|
3 |
|
$shortCode = $request->getAttribute('shortCode'); |
|
54
|
|
|
|
|
55
|
|
|
try { |
|
56
|
3 |
|
$url = $this->urlShortener->shortCodeToUrl($shortCode); |
|
57
|
2 |
|
if (! isset($url)) { |
|
58
|
1 |
|
return $delegate->process($request); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
1 |
|
$imagePath = $this->previewGenerator->generatePreview($url); |
|
62
|
1 |
|
return $this->generateImageResponse($imagePath); |
|
63
|
1 |
|
} catch (InvalidShortCodeException $e) { |
|
64
|
1 |
|
return $delegate->process($request); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|