1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace SlayerBirden\DataFlowServer\Domain\Controller; |
5
|
|
|
|
6
|
|
|
use Doctrine\Common\Collections\Selectable; |
7
|
|
|
use Doctrine\ORM\ORMException; |
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 Psr\Log\LoggerInterface; |
13
|
|
|
use SlayerBirden\DataFlowServer\Doctrine\Collection\CriteriaBuilder; |
14
|
|
|
use SlayerBirden\DataFlowServer\Doctrine\Hydrator\ListExtractor; |
15
|
|
|
use SlayerBirden\DataFlowServer\Stdlib\Validation\GeneralErrorResponseFactory; |
16
|
|
|
use SlayerBirden\DataFlowServer\Stdlib\Validation\GeneralSuccessResponseFactory; |
17
|
|
|
use Zend\Hydrator\HydratorInterface; |
18
|
|
|
|
19
|
|
|
final class GetUsersAction implements MiddlewareInterface |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var LoggerInterface |
23
|
|
|
*/ |
24
|
|
|
private $logger; |
25
|
|
|
/** |
26
|
|
|
* @var HydratorInterface |
27
|
|
|
*/ |
28
|
|
|
private $hydrator; |
29
|
|
|
/** |
30
|
|
|
* @var Selectable |
31
|
|
|
*/ |
32
|
|
|
private $userRepository; |
33
|
|
|
|
34
|
12 |
|
public function __construct( |
35
|
|
|
Selectable $userRepository, |
36
|
|
|
LoggerInterface $logger, |
37
|
|
|
HydratorInterface $hydrator |
38
|
|
|
) { |
39
|
12 |
|
$this->userRepository = $userRepository; |
40
|
12 |
|
$this->logger = $logger; |
41
|
12 |
|
$this->hydrator = $hydrator; |
42
|
12 |
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @inheritdoc |
46
|
|
|
*/ |
47
|
12 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
48
|
|
|
{ |
49
|
|
|
try { |
50
|
12 |
|
$users = $this->userRepository->matching((new CriteriaBuilder())($request->getQueryParams())); |
51
|
|
|
// before collection load to count all records without pagination |
52
|
12 |
|
$count = $users->count(); |
53
|
|
|
|
54
|
10 |
|
if ($count > 0) { |
55
|
8 |
|
$arrayUsers = (new ListExtractor())($this->hydrator, $users->toArray()); |
56
|
8 |
|
return (new GeneralSuccessResponseFactory())('Success', 'users', $arrayUsers, 200, $count); |
57
|
|
|
} else { |
58
|
2 |
|
$msg = 'Could not find users using given conditions.'; |
59
|
2 |
|
return (new GeneralErrorResponseFactory())($msg, 'users', 404, [], 0); |
60
|
|
|
} |
61
|
2 |
|
} catch (ORMException $exception) { |
62
|
2 |
|
$this->logger->error((string)$exception); |
63
|
2 |
|
$msg = 'There was an error while fetching users.'; |
64
|
2 |
|
return (new GeneralErrorResponseFactory())($msg, 'users', 400, [], 0); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|