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\GeneralErrorResponseFactory; |
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
|
28 |
|
public function __construct( |
38
|
|
|
ManagerRegistry $managerRegistry, |
39
|
|
|
LoggerInterface $logger, |
40
|
|
|
string $entityName, |
41
|
|
|
string $dataObjectName, |
42
|
|
|
string $idAttributeName = 'id' |
43
|
|
|
) { |
44
|
28 |
|
$this->managerRegistry = $managerRegistry; |
45
|
28 |
|
$this->logger = $logger; |
46
|
28 |
|
$this->entityName = $entityName; |
47
|
28 |
|
$this->dataObjectName = $dataObjectName; |
48
|
28 |
|
$this->idAttributeName = $idAttributeName; |
49
|
28 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @inheritdoc |
53
|
|
|
*/ |
54
|
28 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
55
|
|
|
{ |
56
|
28 |
|
$id = $request->getAttribute($this->idAttributeName); |
57
|
|
|
|
58
|
28 |
|
if ($id !== null) { |
59
|
|
|
try { |
60
|
28 |
|
$em = $this->managerRegistry->getManagerForClass($this->entityName); |
61
|
28 |
|
$entity = $em->find($this->entityName, $id); |
62
|
28 |
|
if ($entity) { |
63
|
20 |
|
return $handler->handle( |
64
|
20 |
|
$request->withAttribute(self::DATA_RESOURCE, $entity) |
65
|
|
|
); |
66
|
|
|
} else { |
67
|
8 |
|
$msg = sprintf('Could not load %s by provided ID.', $this->dataObjectName); |
68
|
8 |
|
return (new GeneralErrorResponseFactory())($msg, $this->dataObjectName, 404); |
69
|
|
|
} |
70
|
|
|
} catch (ORMInvalidArgumentException $exception) { |
71
|
|
|
$this->logger->error((string)$exception); |
72
|
|
|
$msg = sprintf('Error during loading %s.', $this->dataObjectName); |
73
|
|
|
return (new GeneralErrorResponseFactory())($msg, $this->dataObjectName); |
74
|
|
|
} |
75
|
|
|
} else { |
76
|
|
|
$msg = sprintf('No %s provided.', $this->idAttributeName); |
77
|
|
|
return (new GeneralErrorResponseFactory())($msg, $this->dataObjectName, 400); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|