Completed
Push — master ( a73a59...6682b5 )
by Alejandro
21s queued 11s
created

CloseDbConnectionMiddleware   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 14
c 1
b 0
f 0
dl 0
loc 27
rs 10
ccs 11
cts 12
cp 0.9167

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A process() 0 17 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Common\Middleware;
5
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\EntityManagerInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Throwable;
13
14
class CloseDbConnectionMiddleware implements MiddlewareInterface
15
{
16
    /** @var EntityManagerInterface */
17
    private $em;
18
19 3
    public function __construct(EntityManagerInterface $em)
20
    {
21 3
        $this->em = $em;
22
    }
23
24 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
25
    {
26
        try {
27 3
            return $handler->handle($request);
28 2
        } catch (Throwable $e) {
29
            // FIXME Mega ugly hack to avoid a closed EntityManager to make shlink fail forever on swoole contexts
30
            //       Should be fixed with request-shared EntityManagers, which is not supported by the ServiceManager
31 2
            if (! $this->em->isOpen()) {
32
                (function () {
33 1
                    $this->closed = false;
0 ignored issues
show
Bug Best Practice introduced by
The property closed does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
34 1
                })->bindTo($this->em, EntityManager::class)();
35
            }
36
37 2
            throw $e;
38
        } finally {
39 3
            $this->em->getConnection()->close();
40 3
            $this->em->clear();
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return Psr\Http\Message\ResponseInterface. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
41
        }
42
    }
43
}
44