DataTables::handle()   B
last analyzed

Complexity

Conditions 6
Paths 20

Size

Total Lines 81
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 41
CRAP Score 6

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 48
c 3
b 0
f 0
dl 0
loc 81
ccs 41
cts 41
cp 1
rs 8.5123
cc 6
nc 20
nop 3
crap 6

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
3
//----------------------------------------------------------------------
4
//
5
//  Copyright (C) 2015-2022 Artem Rodygin
6
//
7
//  This file is part of DataTables Symfony bundle.
8
//
9
//  You should have received a copy of the MIT License along with
10
//  the bundle. If not, see <http://opensource.org/licenses/MIT>.
11
//
12
//----------------------------------------------------------------------
13
14
namespace DataTables;
15
16
use Psr\Log\LoggerInterface;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\Validator\Validator\ValidatorInterface;
19
20
/**
21
 * DataTables lookup service.
22
 */
23
class DataTables implements DataTablesInterface
24
{
25
    protected $logger;
26
    protected $validator;
27
28
    /** @var DataTableHandlerInterface[] List of registered DataTable services */
29
    protected $services = [];
30
31
    /**
32
     * @codeCoverageIgnore Dependency Injection constructor.
33
     */
34
    public function __construct(LoggerInterface $logger, ValidatorInterface $validator)
35
    {
36
        $this->logger    = $logger;
37
        $this->validator = $validator;
38
    }
39
40
    /**
41
     * Registers specified DataTable handler.
42
     *
43
     * @param DataTableHandlerInterface $service Service of the DataTable handler
44
     * @param null|string               $id      DataTable ID
45
     */
46
    public function addService(DataTableHandlerInterface $service, string $id = null)
47
    {
48
        $service_id = $id ?? $service::ID;
49
50
        if (null !== $service_id) {
51
            $this->services[$service_id] = $service;
52
        }
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function handle(Request $request, string $id, array $context = []): DataTableResults
59
    {
60
        $this->logger->debug('Handle DataTable request', [$id]);
61 9
62
        // Retrieve sent parameters.
63 9
        $params = new Parameters();
64
65
        $keyParams = [
66 9
            'draw',
67
            'start',
68
            'length',
69 9
            'search',
70
            'order',
71
            'columns',
72
        ];
73
74
        $params->draw    = $request->get('draw');
75
        $params->start   = $request->get('start');
76
        $params->length  = $request->get('length');
77 9
        $params->search  = $request->get('search');
78 9
        $params->order   = $request->get('order')   ?? [];
79 9
        $params->columns = $request->get('columns') ?? [];
80 9
81 9
        $allParams = $request->isMethod(Request::METHOD_POST)
82 9
            ? $request->request->all()
83
            : $request->query->all();
84 9
85 1
        $params->customData = array_diff_key($allParams, array_flip($keyParams));
86 9
87
        // Validate sent parameters.
88 9
        $violations = $this->validator->validate($params);
89
90
        if (count($violations)) {
91 9
            $message = $violations->get(0)->getMessage();
92
            $this->logger->error($message, ['request']);
93 9
94 1
            throw new DataTableException($message);
95 1
        }
96 1
97
        // Check for valid handler is registered.
98
        if (!array_key_exists($id, $this->services)) {
99
            $message = 'Unknown DataTable ID.';
100 8
            $this->logger->error($message, [$id]);
101 1
102 1
            throw new DataTableException($message);
103 1
        }
104
105
        // Convert sent parameters into data model.
106
        $query = new DataTableQuery($params);
107 7
108
        // Pass the data model to the handler.
109
        $result = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
110 7
111
        $timer_started = microtime(true);
112 7
113
        try {
114
            $result = $this->services[$id]->handle($query, $context);
115 7
        } catch (\Exception $e) {
116
            $this->logger->error($e->getMessage(), [$this->services[$id]]);
117 1
118 1
            throw new DataTableException($e->getMessage());
119 1
        } finally {
120
            $timer_stopped = microtime(true);
121 6
            $this->logger->debug('DataTable processing time', [$timer_stopped - $timer_started, $this->services[$id]]);
122 7
        }
123 7
124
        // Validate results returned from handler.
125
        $violations = $this->validator->validate($result);
126
127 6
        if (count($violations)) {
128
            $message = $violations->get(0)->getMessage();
129 6
            $this->logger->error($message, ['response']);
130 1
131 1
            throw new DataTableException($message);
132 1
        }
133
134
        $reflection = new \ReflectionProperty(DataTableResults::class, 'draw');
135 5
        $reflection->setAccessible(true);
136 5
        $reflection->setValue($result, $params->draw);
137 5
138
        return $result;
139 5
    }
140
}
141