|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace App\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Import classes |
|
7
|
|
|
*/ |
|
8
|
|
|
use App\ContainerAwareTrait; |
|
9
|
|
|
use Doctrine\ORM\EntityManager; |
|
10
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
12
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
13
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
14
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Import constants |
|
18
|
|
|
*/ |
|
19
|
|
|
use const PHP_SAPI; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* DoctrinePersistentEntityManagerMiddleware |
|
23
|
|
|
* |
|
24
|
|
|
* This middleware is for long-running applications only! |
|
25
|
|
|
*/ |
|
26
|
|
|
final class DoctrinePersistentEntityManagerMiddleware implements MiddlewareInterface |
|
27
|
|
|
{ |
|
28
|
|
|
use ContainerAwareTrait; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* {@inheritDoc} |
|
32
|
|
|
* |
|
33
|
|
|
* @param ServerRequestInterface $request |
|
34
|
|
|
* @param RequestHandlerInterface $handler |
|
35
|
|
|
* |
|
36
|
|
|
* @return ResponseInterface |
|
37
|
|
|
*/ |
|
38
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface |
|
39
|
|
|
{ |
|
40
|
|
|
if ($this->isCli()) { |
|
41
|
|
|
$this->container->set('entityManager', $this->reopen( |
|
|
|
|
|
|
42
|
|
|
$this->container->get('entityManager') |
|
43
|
|
|
)); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
return $handler->handle($request); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Checks if the application is running in CLI mode |
|
51
|
|
|
* |
|
52
|
|
|
* @return bool |
|
53
|
|
|
*/ |
|
54
|
|
|
private function isCli() : bool |
|
55
|
|
|
{ |
|
56
|
|
|
return 'cli' === PHP_SAPI && 'test' !== $this->container->get('app.env'); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Reopens the given entity manager |
|
61
|
|
|
* |
|
62
|
|
|
* @param EntityManagerInterface $entityManager |
|
63
|
|
|
* |
|
64
|
|
|
* @return EntityManagerInterface |
|
65
|
|
|
*/ |
|
66
|
|
|
private function reopen(EntityManagerInterface $entityManager) : EntityManagerInterface |
|
67
|
|
|
{ |
|
68
|
|
|
if ($entityManager->isOpen()) { |
|
69
|
|
|
return $entityManager; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
return EntityManager::create( |
|
73
|
|
|
$entityManager->getConnection(), |
|
74
|
|
|
$entityManager->getConfiguration(), |
|
75
|
|
|
$entityManager->getConnection()->getEventManager() |
|
76
|
|
|
); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|