Completed
Push — master ( 2ef37c...52cad6 )
by Oleg
02:13
created

GetConfigsAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 3
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 1
rs 9.6666
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Db\Controller;
5
6
use Doctrine\Common\Collections\Collection;
7
use Doctrine\Common\Collections\Criteria;
8
use Doctrine\ORM\EntityManagerInterface;
9
use Doctrine\ORM\ORMException;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\ServerRequestInterface;
12
use Psr\Http\Server\MiddlewareInterface;
13
use Psr\Http\Server\RequestHandlerInterface;
14
use Psr\Log\LoggerInterface;
15
use SlayerBirden\DataFlowServer\Db\Entities\DbConfiguration;
16
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
17
use Zend\Diactoros\Response\JsonResponse;
18
use Zend\Hydrator\ExtractionInterface;
19
20
class GetConfigsAction implements MiddlewareInterface
21
{
22
    /**
23
     * @var EntityManagerInterface
24
     */
25
    private $entityManager;
26
    /**
27
     * @var LoggerInterface
28
     */
29
    private $logger;
30
    /**
31
     * @var ExtractionInterface
32
     */
33
    private $extraction;
34
35 5
    public function __construct(
36
        EntityManagerInterface $entityManager,
37
        LoggerInterface $logger,
38
        ExtractionInterface $extraction
39
    ) {
40 5
        $this->entityManager = $entityManager;
41 5
        $this->logger = $logger;
42 5
        $this->extraction = $extraction;
43 5
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48 5
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
49
    {
50 5
        $data = $request->getQueryParams();
51 5
        $page = isset($data['p']) ? abs($data['p']) : null;
52 5
        $filters = $data['f'] ?? [];
53 5
        $sorting = $data['s'] ?? [];
54 5
        $success = false;
55 5
        $msg = '';
56 5
        $status = 200;
57
58
        try {
59 5
            $criteria = $this->buildCriteria($filters, $sorting, $page);
60
61
            /** @var Collection $configs */
62 5
            $configs = $this->entityManager
63 5
                ->getRepository(DbConfiguration::class)
64 5
                ->matching($criteria);
65
            // before collection load to count all records without pagination
66 5
            $count = $configs->count();
67 5
            if ($count > 0) {
68 4
                $arrayConfigs = array_map(function ($user) {
69
                    return $this->extraction->extract($user);
70 4
                }, $configs->toArray());
71
                $success = true;
72
            } else {
73 1
                $msg = new DangerMessage('Could not find configurations using given conditions.');
74 1
                $status = 404;
75
            }
76
        } catch (ORMException $exception) {
77
            $this->logger->error((string)$exception);
78
            $msg = new DangerMessage('Could not fetch configs.');
79
            $status = 400;
80
        }
81
82 1
        return new JsonResponse([
83 1
            'data' => [
84 1
                'configurations' => $arrayConfigs ?? [],
85 1
                'count' => $count ?? 0,
86
            ],
87 1
            'success' => $success,
88 1
            'msg' => $msg,
89 1
        ], $status);
90
    }
91
92 5
    private function buildCriteria(array $filters = [], array $sorting = [], ?int $page, int $limit = 10): Criteria
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
93
    {
94
        // todo add filter for current user
95 5
        $criteria = Criteria::create();
96 5
        if ($page !== null) {
97 1
            $criteria->setFirstResult(($page - 1) * $limit)
98 1
                ->setMaxResults($limit);
99
        }
100 5
        foreach ($filters as $key => $value) {
101 2
            $criteria->andWhere(Criteria::expr()->contains($key, $value));
102
        }
103 5
        if ($sorting) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sorting of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
104 1
            foreach ($sorting as $key => $dir) {
105 1
                $criteria->orderBy($sorting);
106
            }
107
        }
108
109 5
        return $criteria;
110
    }
111
}
112