Completed
Pull Request — master (#20)
by
unknown
05:54
created

EntityManagerCloseMiddleware   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 42
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A execute() 0 13 3
A tryToCloseEntityManager() 0 7 3
1
<?php
2
3
namespace League\Tactician\Doctrine\ORM;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use League\Tactician\Middleware;
7
8
/**
9
 * Close Doctrine EntityManager on any exception
10
 */
11
class EntityManagerCloseMiddleware implements Middleware
12
{
13
    /** @var EntityManagerInterface */
14
    private $entityManager;
15
16
    /**
17
     * @param EntityManagerInterface $entityManager
18
     */
19
    public function __construct(EntityManagerInterface $entityManager)
20
    {
21
        $this->entityManager = $entityManager;
22
    }
23
24
25
    /**
26
     * @inheritdoc
27
     */
28
    public function execute($command, callable $next)
29
    {
30
        try {
31
            return $next($command);
32
        } catch (\Exception $exception) {
33
            // Only for backward capability ( < PHP 7.0.0)
34
            $this->tryToCloseEntityManager();
35
            throw $exception;
36
        } catch (\Throwable $throwable) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
37
            $this->tryToCloseEntityManager();
38
            throw  $throwable;
39
        }
40
    }
41
42
    /**
43
     * Close entityManager when possible
44
     */
45
    private function tryToCloseEntityManager()
46
    {
47
        $connection = $this->entityManager->getConnection();
48
        if (!$connection->isTransactionActive() || $connection->isRollbackOnly()) {
49
            $this->entityManager->close();
50
        }
51
    }
52
}
53