Completed
Push — master ( 0024da...3d898f )
by Oleg
03:17
created

GetConfigsAction::process()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 6.3357

Importance

Changes 0
Metric Value
dl 0
loc 59
ccs 30
cts 38
cp 0.7895
rs 8.2723
c 0
b 0
f 0
cc 6
nc 32
nop 2
crap 6.3357

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