1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace SlayerBirden\DataFlowServer\Doctrine\Middleware; |
5
|
|
|
|
6
|
|
|
use Doctrine\Common\Persistence\ManagerRegistry; |
7
|
|
|
use Doctrine\ORM\ORMInvalidArgumentException; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
11
|
|
|
use Psr\Log\LoggerInterface; |
12
|
|
|
use SlayerBirden\DataFlowServer\Stdlib\Validation\ResponseFactory; |
13
|
|
|
|
14
|
|
|
final class BaseResourceMiddleware implements ResourceMiddlewareInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var LoggerInterface |
18
|
|
|
*/ |
19
|
|
|
private $logger; |
20
|
|
|
/** |
21
|
|
|
* @var string |
22
|
|
|
*/ |
23
|
|
|
private $entityName; |
24
|
|
|
/** |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
private $dataObjectName; |
28
|
|
|
/** |
29
|
|
|
* @var string |
30
|
|
|
*/ |
31
|
|
|
private $idAttributeName; |
32
|
|
|
/** |
33
|
|
|
* @var ManagerRegistry |
34
|
|
|
*/ |
35
|
|
|
private $managerRegistry; |
36
|
|
|
|
37
|
70 |
|
public function __construct( |
38
|
|
|
ManagerRegistry $managerRegistry, |
39
|
|
|
LoggerInterface $logger, |
40
|
|
|
string $entityName, |
41
|
|
|
string $dataObjectName, |
42
|
|
|
string $idAttributeName = 'id' |
43
|
|
|
) { |
44
|
70 |
|
$this->managerRegistry = $managerRegistry; |
45
|
70 |
|
$this->logger = $logger; |
46
|
70 |
|
$this->entityName = $entityName; |
47
|
70 |
|
$this->dataObjectName = $dataObjectName; |
48
|
70 |
|
$this->idAttributeName = $idAttributeName; |
49
|
70 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @inheritdoc |
53
|
|
|
*/ |
54
|
70 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
55
|
|
|
{ |
56
|
70 |
|
$id = $request->getAttribute($this->idAttributeName); |
57
|
|
|
|
58
|
|
|
try { |
59
|
70 |
|
$em = $this->managerRegistry->getManagerForClass($this->entityName); |
60
|
70 |
|
$entity = $em->find($this->entityName, $id); |
61
|
70 |
|
if ($entity) { |
62
|
54 |
|
return $handler->handle( |
63
|
54 |
|
$request->withAttribute(self::DATA_RESOURCE, $entity) |
64
|
|
|
); |
65
|
|
|
} else { |
66
|
16 |
|
$msg = sprintf('Could not load %s by provided ID.', $this->dataObjectName); |
67
|
16 |
|
return (new ResponseFactory())($msg, 404, $this->dataObjectName); |
68
|
|
|
} |
69
|
|
|
} catch (ORMInvalidArgumentException $exception) { |
70
|
|
|
$this->logger->error((string)$exception); |
71
|
|
|
$msg = sprintf('Error during loading %s.', $this->dataObjectName); |
72
|
|
|
return (new ResponseFactory())($msg, 400, $this->dataObjectName); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|