Completed
Push — master ( 298ac7...0024da )
by Oleg
12:58
created

GetConfigsAction::process()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 58
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 5.2526

Importance

Changes 0
Metric Value
dl 0
loc 58
ccs 29
cts 37
cp 0.7838
rs 8.7274
c 0
b 0
f 0
cc 5
eloc 43
nc 16
nop 2
crap 5.2526

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\EntityManager;
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\Authentication\Middleware\TokenMiddleware;
16
use SlayerBirden\DataFlowServer\Db\Entities\DbConfiguration;
17
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
18
use Zend\Diactoros\Response\JsonResponse;
19
use Zend\Hydrator\ExtractionInterface;
20
21
class GetConfigsAction implements MiddlewareInterface
22
{
23
    /**
24
     * @var EntityManager
25
     */
26
    private $entityManager;
27
    /**
28
     * @var LoggerInterface
29
     */
30
    private $logger;
31
    /**
32
     * @var ExtractionInterface
33
     */
34
    private $extraction;
35
36 5
    public function __construct(
37
        EntityManager $entityManager,
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
38
        LoggerInterface $logger,
39
        ExtractionInterface $extraction
40
    ) {
41 5
        $this->entityManager = $entityManager;
42 5
        $this->logger = $logger;
43 5
        $this->extraction = $extraction;
44 5
    }
45
46
    /**
47
     * @inheritdoc
48
     */
49 5
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
50
    {
51 5
        $data = $request->getQueryParams();
52 5
        $page = isset($data['p']) ? abs($data['p']) : null;
53 5
        $filters = $data['f'] ?? [];
54 5
        $sorting = $data['s'] ?? [];
55 5
        $success = false;
56 5
        $msg = null;
57 5
        $status = 200;
58
59
60 5
        $currentOwner = $request->getAttribute(TokenMiddleware::USER_PARAM);
61
62 5
        if (!$currentOwner) {
63
            return new JsonResponse([
64
                'data' => [
65
                    'configurations' => [],
66
                    'count' => 0,
67
                ],
68
                'msg' => new DangerMessage('Access denied. Only Logged In users can access this resource.'),
69
                'success' => false
70
            ], 403);
71
        }
72 5
        $filters['owner'] = $currentOwner;
73
74
        try {
75 5
            $criteria = $this->buildCriteria($filters, $sorting, $page);
76
77
            /** @var Collection $configs */
78 5
            $configs = $this->entityManager
79 5
                ->getRepository(DbConfiguration::class)
80 5
                ->matching($criteria);
81
            // before collection load to count all records without pagination
82 5
            $count = $configs->count();
83 5
            if ($count > 0) {
84
                $arrayConfigs = array_map(function ($user) {
85 4
                    return $this->extraction->extract($user);
86 4
                }, $configs->toArray());
87 4
                $success = true;
88
            } else {
89 1
                $msg = new DangerMessage('Could not find configurations using given conditions.');
90 1
                $status = 404;
91
            }
92
        } catch (ORMException $exception) {
93
            $this->logger->error((string)$exception);
94
            $msg = new DangerMessage('Could not fetch configs.');
95
            $status = 400;
96
        }
97
98 5
        return new JsonResponse([
99 5
            'data' => [
100 5
                'configurations' => $arrayConfigs ?? [],
101 5
                'count' => $count ?? 0,
102
            ],
103 5
            'success' => $success,
104 5
            'msg' => $msg,
105 5
        ], $status);
106
    }
107
108 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...
109
    {
110 5
        $criteria = Criteria::create();
111 5
        if ($page !== null) {
112 1
            $criteria->setFirstResult(($page - 1) * $limit)
113 1
                ->setMaxResults($limit);
114
        }
115 5
        foreach ($filters as $key => $value) {
116 5
            if (is_string($value)) {
117 2
                $criteria->andWhere(Criteria::expr()->contains($key, $value));
118
            } else {
119 5
                $criteria->andWhere(Criteria::expr()->eq($key, $value));
120
            }
121
        }
122 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...
123 1
            foreach ($sorting as $key => $dir) {
124 1
                $criteria->orderBy($sorting);
125
            }
126
        }
127
128 5
        return $criteria;
129
    }
130
}
131