Completed
Pull Request — 8.x-2.x (#24)
by Frédéric G.
03:14
created

RequestController::buildRows()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 26
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 40
rs 8.8571
1
<?php
2
3
namespace Drupal\mongodb_watchdog\Controller;
4
5
use Drupal\Component\Utility\Unicode;
6
use Drupal\Core\Config\ImmutableConfig;
7
use Drupal\Core\Datetime\DateFormatterInterface;
8
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
9
use Drupal\Core\Link;
10
use Drupal\Core\Logger\RfcLogLevel;
11
use Drupal\mongodb_watchdog\Logger;
12
use Symfony\Component\DependencyInjection\ContainerInterface;
13
use Symfony\Component\HttpFoundation\Request;
14
15
/**
16
 * Implements the controller for the request events page.
17
 */
18
class RequestController extends ControllerBase implements ContainerInjectionInterface {
19
20
  /**
21
   * The core date.formatter service.
22
   *
23
   * @var \Drupal\Core\Datetime\DateFormatterInterface
24
   */
25
  protected $dateFormatter;
26
27
  /**
28
   * The length of the absolute path to the site root, in runes.
29
   *
30
   * @var int
31
   */
32
  protected $rootLength;
33
34
  /**
35
   * The MongoDB logger, to load events.
36
   *
37
   * @var \Drupal\mongodb_watchdog\Logger
38
   */
39
  protected $watchdog;
40
41
  /**
42
   * Controller constructor.
43
   *
44
   * @param \Drupal\mongodb_watchdog\Logger $watchdog
45
   *   The MongoDB logger service, to load event data.
46
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
47
   *   The core date.formatter service.
48
   * @param \Drupal\Core\Config\ImmutableConfig $config
49
   *   The module configuration.
50
   */
51
  public function __construct(
52
    Logger $watchdog,
53
    DateFormatterInterface $date_formatter,
54
    ImmutableConfig $config) {
55
    parent::__construct($config);
56
    $this->dateFormatter = $date_formatter;
57
    $this->watchdog = $watchdog;
58
59
    // Add terminal "/".
60
    $this->rootLength = Unicode::strlen(DRUPAL_ROOT) + 1;
61
  }
62
63
  /**
64
   * Controller.
65
   *
66
   * @param string $uniqueId
67
   *   The unique request id from mod_unique_id. Unsafe.
68
   *
69
   * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,string|array>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
70
   *   A render array.
71
   */
72
  public function build(Request $request, $uniqueId) {
73
    if (!preg_match('/[\w-]+/', $uniqueId)) {
74
      return ['#markup' => ''];
75
    }
76
77
    $page = $this->setupPager($request, $uniqueId);
78
    $skip = $page * $this->itemsPerPage;
79
    $height = $this->itemsPerPage;
80
81
    $events = $this->watchdog->requestEvents($uniqueId, $skip, $height);
82
    $ret = [
83
      'request' => $this->buildRequest($uniqueId, $events),
84
      'events' => $this->buildRows($events),
85
      'pager' => [
86
        '#type' => 'pager',
87
      ],
88
      '#attached' => [
89
        'library' => ['mongodb_watchdog/styling'],
90
      ],
91
    ];
92
93
    return $ret;
94
  }
95
96
  /**
97
   * Build the top part of the page, about the request.
98
   *
99
   * @param string $unique_id
100
   *   The unique request id.
101
   * @param array<\Drupal\mongodb_watchdog\EventTemplate\Drupal\mongodb_watchdog\Event[]> $events
102
   *   A fully loaded array of events and their templates.
103
   *
104
   * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,string|array[]>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
105
   *   A render array for a table.
106
   */
107
  public function buildRequest($unique_id, array $events) {
108
    if ($events) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $events of type Drupal\mongodb_watchdog\...godb_watchdog\Event[][] 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...
109
      $row = array_slice($events, 0, 1);
110
      /** @var \Drupal\mongodb_watchdog\Event $first */
111
      list($template, $first) = reset($row);
0 ignored issues
show
Unused Code introduced by
The assignment to $template is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
introduced by
Unused variable $template.
Loading history...
112
113
      $location = $first->location;
114
      $timestamp = isset($first->timestamp)
115
        ? $this->dateFormatter->format($first->timestamp, 'long')
116
        : t('No information');
117
    }
118
    else {
119
      $location = $timestamp = t('No information');
120
    }
121
122
    $rows = [
123
      [t('Request ID'), $unique_id],
124
      [t('Location'), $location],
125
      [t('Date/time'), $timestamp],
126
    ];
127
128
    foreach ($rows as &$row) {
129
      $row[0] = [
130
        'data' => $row[0],
131
        'header' => TRUE,
132
      ];
133
    }
134
135
    $ret = [
136
      '#type' => 'table',
137
      '#rows' => $rows,
138
    ];
139
    return $ret;
140
  }
141
142
  /**
143
   * Build the bottom part of the page, about the events during the request.
144
   *
145
   * @param array<\Drupal\mongodb_watchdog\EventTemplate\Drupal\mongodb_watchdog\Event[]> $events
146
   *   A fully loaded array of events and their templates.
147
   *
148
   * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,string|array>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
149
   *   A render array for a table.
150
   */
151
  public function buildRows(array $events) {
152
    $header = [
153
      t('Sequence'),
154
      t('Type'),
155
      t('Severity'),
156
      t('Event'),
157
      t('File'),
158
      t('Line'),
159
    ];
160
    $rows = [];
161
    $levels = RfcLogLevel::getLevels();
162
163
    /** @var \Drupal\mongodb_watchdog\EventTemplate $template */
164
    /** @var \Drupal\mongodb_watchdog\Event $event */
165
    foreach ($events as list($template, $event)) {
0 ignored issues
show
introduced by
Variable $template is undefined.
Loading history...
introduced by
Variable $event is undefined.
Loading history...
166
      $row = [
167
        ['data' => $event->requestTracking_sequence],
0 ignored issues
show
introduced by
Variable $event is undefined.
Loading history...
168
        $template->type,
0 ignored issues
show
introduced by
Variable $template is undefined.
Loading history...
169
        [
170
          'data' => $levels[$template->severity],
0 ignored issues
show
introduced by
Variable $template is undefined.
Loading history...
171
          'class' => OverviewController::SEVERITY_CLASSES[$template->severity],
0 ignored issues
show
introduced by
Variable $template is undefined.
Loading history...
172
        ],
173
        [
174
          'data' => Link::createFromRoute($template->asString($event->variables), 'mongodb_watchdog.reports.detail', [
0 ignored issues
show
introduced by
Variable $template is undefined.
Loading history...
introduced by
Variable $event is undefined.
Loading history...
175
            'event_template' => $template->_id,
0 ignored issues
show
introduced by
Variable $template is undefined.
Loading history...
176
          ]),
177
        ],
178
        $this->simplifyPath($event->variables['%file']),
0 ignored issues
show
introduced by
Variable $event is undefined.
Loading history...
179
        $event->variables['%line'],
0 ignored issues
show
introduced by
Variable $event is undefined.
Loading history...
180
      ];
181
      $rows[] = $row;
182
    }
183
184
    $ret = [
185
      '#type' => 'table',
186
      '#rows' => $rows,
187
      '#header' => $header,
188
    ];
189
    return $ret;
190
  }
191
192
  /**
193
   * {@inheritdoc}
194
   */
195
  public static function create(ContainerInterface $container) {
196
    /** @var \Drupal\mongodb_watchdog\Logger $watchdog */
197
    $watchdog = $container->get('mongodb.logger');
198
199
    /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
200
    $date_formatter = $container->get('date.formatter');
201
202
    /** @var \Drupal\Core\Config\ImmutableConfig $config */
203
    $config = $container->get('config.factory')->get('mongodb_watchdog.settings');
204
205
    return new static($watchdog, $date_formatter, $config);
206
  }
207
208
  /**
209
   * Set up the templates pager.
210
   *
211
   * @param \Symfony\Component\HttpFoundation\Request $request
212
   *   The current request.
213
   * @param int $uniqueId
214
   *   The uniqueId of the current request.
215
   *
216
   * @return int
217
   *   The number of the page to display, starting at 0.
218
   */
219 View Code Duplication
  public function setupPager(Request $request, $uniqueId) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
220
    $count = $this->watchdog->requestEventsCount($uniqueId);
221
    $height = $this->itemsPerPage;
222
    pager_default_initialize($count, $height);
223
224
    $page = intval($request->query->get('page'));
225
    if ($page < 0) {
226
      $page = 0;
227
    }
228
    else {
229
      $page_max = intval(min(ceil($count / $height), PHP_INT_MAX) - 1);
230
      if ($page > $page_max) {
231
        $page = $page_max;
232
      }
233
    }
234
235
    return $page;
236
  }
237
238
  /**
239
   * Convert an absolute path to a relative one if below the site root.
240
   *
241
   * @param string $path
242
   *   An absolute path on the filesystem.
243
   *
244
   * @return string
245
   *   A relative path if possible, otherwise the input path.
246
   */
247
  public function simplifyPath($path) {
248
    $ret = (Unicode::strpos($path, DRUPAL_ROOT) === 0)
249
      ? Unicode::substr($path, $this->rootLength)
250
      : $path;
251
    return $ret;
252
  }
253
254
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
255