Completed
Push — master ( 5c71f2...630401 )
by Oleg
07:36
created

GetConfigsAction::process()   A

Complexity

Conditions 5
Paths 32

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 21
cts 21
cp 1
rs 9.0808
c 0
b 0
f 0
cc 5
nc 32
nop 2
crap 5
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Db\Controller;
5
6
use Doctrine\Common\Collections\Criteria;
7
use Doctrine\Common\Collections\Selectable;
8
use Doctrine\ORM\ORMException;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Psr\Log\LoggerInterface;
14
use SlayerBirden\DataFlowServer\Authentication\Middleware\TokenMiddleware;
15
use SlayerBirden\DataFlowServer\Stdlib\Validation\GeneralErrorResponseFactory;
16
use SlayerBirden\DataFlowServer\Stdlib\Validation\GeneralSuccessResponseFactory;
17
use Zend\Hydrator\HydratorInterface;
18
19
final class GetConfigsAction 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 $dbConfigRepository;
33
34 6
    public function __construct(
35
        Selectable $dbConfigRepository,
36
        LoggerInterface $logger,
37
        HydratorInterface $hydrator
38
    ) {
39 6
        $this->logger = $logger;
40 6
        $this->hydrator = $hydrator;
41 6
        $this->dbConfigRepository = $dbConfigRepository;
42 6
    }
43
44
    /**
45
     * @inheritdoc
46
     */
47 6
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
48
    {
49 6
        $data = $request->getQueryParams();
50 6
        $page = isset($data['p']) ? abs($data['p']) : 1;
51 6
        $limit = isset($data['l']) ? abs($data['l']) : 10;
52 6
        $filters = $data['f'] ?? [];
53 6
        $sorting = $data['s'] ?? [];
54
55
56 6
        $currentOwner = $request->getAttribute(TokenMiddleware::USER_PARAM);
57 6
        $filters['owner'] = $currentOwner;
58
59
        try {
60 6
            $criteria = $this->buildCriteria($filters, $sorting, $page, $limit);
61
62 6
            $configs = $this->dbConfigRepository->matching($criteria);
63
            // before collection load to count all records without pagination
64 6
            $count = $configs->count();
65 5
            if ($count > 0) {
66
                $arrayConfigs = array_map(function ($config) {
67 4
                    return $this->hydrator->extract($config);
68 4
                }, $configs->toArray());
69 4
                return (new GeneralSuccessResponseFactory())('Success', 'configurations', $arrayConfigs, 200, $count);
70
            } else {
71 1
                $msg = 'Could not find configurations using given conditions.';
72 1
                return (new GeneralErrorResponseFactory())($msg, 'configurations', 404, [], 0);
73
            }
74 1
        } catch (ORMException $exception) {
75 1
            $this->logger->error((string)$exception);
76 1
            $msg = 'There was an error while fetching configurations.';
77 1
            return (new GeneralErrorResponseFactory())($msg, 'configurations', 400, [], 0);
78
        }
79
    }
80
81 6
    private function buildCriteria(
82
        array $filters = [],
83
        array $sorting = [],
84
        int $page = 1,
85
        int $limit = 10
86
    ): Criteria {
87 6
        $criteria = Criteria::create();
88 6
        $criteria->setFirstResult(($page - 1) * $limit)
89 6
            ->setMaxResults($limit);
90 6
        foreach ($filters as $key => $value) {
91 6
            if (is_string($value)) {
92 3
                $criteria->andWhere(Criteria::expr()->contains($key, $value));
93
            } else {
94 6
                $criteria->andWhere(Criteria::expr()->eq($key, $value));
95
            }
96
        }
97 6
        if (! empty($sorting)) {
98 1
            foreach ($sorting as $key => $dir) {
99 1
                $criteria->orderBy($sorting);
100
            }
101
        }
102
103 6
        return $criteria;
104
    }
105
}
106