Completed
Push — develop ( 9f24b8...3ee585 )
by Alejandro
23s queued 13s
created

QrCodeAction   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 94.74%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 24
c 1
b 0
f 0
dl 0
loc 46
ccs 18
cts 19
cp 0.9474
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A getSizeParam() 0 8 3
A process() 0 16 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Core\Action;
6
7
use Endroid\QrCode\QrCode;
8
use Psr\Http\Message\ResponseInterface as Response;
9
use Psr\Http\Message\ServerRequestInterface as Request;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Psr\Log\LoggerInterface;
13
use Psr\Log\NullLogger;
14
use Shlinkio\Shlink\Common\Response\QrCodeResponse;
15
use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
16
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
17
use Shlinkio\Shlink\Core\Service\ShortUrl\ShortUrlResolverInterface;
18
19
class QrCodeAction implements MiddlewareInterface
20
{
21
    private const DEFAULT_SIZE = 300;
22
    private const MIN_SIZE = 50;
23
    private const MAX_SIZE = 1000;
24
25
    private ShortUrlResolverInterface $urlResolver;
26
    private array $domainConfig;
27
    private LoggerInterface $logger;
28
29 3
    public function __construct(
30
        ShortUrlResolverInterface $urlResolver,
31
        array $domainConfig,
32
        ?LoggerInterface $logger = null
33
    ) {
34 3
        $this->urlResolver = $urlResolver;
35 3
        $this->domainConfig = $domainConfig;
36 3
        $this->logger = $logger ?: new NullLogger();
37
    }
38
39 3
    public function process(Request $request, RequestHandlerInterface $handler): Response
40
    {
41 3
        $identifier = ShortUrlIdentifier::fromRedirectRequest($request);
42
43
        try {
44 3
            $shortUrl = $this->urlResolver->resolveEnabledShortUrl($identifier);
45 2
        } catch (ShortUrlNotFoundException $e) {
46 2
            $this->logger->warning('An error occurred while creating QR code. {e}', ['e' => $e]);
47 2
            return $handler->handle($request);
48
        }
49
50 1
        $qrCode = new QrCode($shortUrl->toString($this->domainConfig));
51 1
        $qrCode->setSize($this->getSizeParam($request));
52 1
        $qrCode->setMargin(0);
53
54 1
        return new QrCodeResponse($qrCode);
55
    }
56
57 1
    private function getSizeParam(Request $request): int
58
    {
59 1
        $size = (int) $request->getAttribute('size', self::DEFAULT_SIZE);
60 1
        if ($size < self::MIN_SIZE) {
61
            return self::MIN_SIZE;
62
        }
63
64 1
        return $size > self::MAX_SIZE ? self::MAX_SIZE : $size;
65
    }
66
}
67