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

OverviewController::overviewRows()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 20
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 28
rs 8.8571
1
<?php
2
3
namespace Drupal\mongodb_watchdog\Controller;
4
5
use Drupal\Component\Utility\SafeMarkup;
6
use Drupal\Component\Utility\Unicode;
7
use Drupal\Core\Controller\ControllerBase;
8
use Drupal\Core\Logger\RfcLogLevel;
9
use Drupal\Core\Url;
10
use Drupal\mongodb_watchdog\Form\OverviewFilterForm;
11
use Drupal\mongodb_watchdog\Logger;
12
use MongoDB\Database;
13
use Psr\Log\LoggerInterface;
14
use Psr\Log\LogLevel;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16
use Drupal\Core\Extension\ModuleHandlerInterface;
17
use Drupal\Core\Form\FormBuilderInterface;
18
19
/**
20
 * Class OverviewController provides the main MongoDB Watchdog report page.
21
 */
22
class OverviewController extends ControllerBase {
23
  const SEVERITY_PREFIX = 'mongodb_watchdog__severity_';
24
  const SEVERITY_CLASSES = [
25
    RfcLogLevel::DEBUG => self::SEVERITY_PREFIX . LogLevel::DEBUG,
26
    RfcLogLevel::INFO => self::SEVERITY_PREFIX . LogLevel::INFO,
27
    RfcLogLevel::NOTICE => self::SEVERITY_PREFIX . LogLevel::NOTICE,
28
    RfcLogLevel::WARNING => self::SEVERITY_PREFIX . LogLevel::WARNING,
29
    RfcLogLevel::ERROR => self::SEVERITY_PREFIX . LogLevel::ERROR,
30
    RfcLogLevel::CRITICAL => self::SEVERITY_PREFIX . LogLevel::CRITICAL,
31
    RfcLogLevel::ALERT => self::SEVERITY_PREFIX . LogLevel::ALERT,
32
    RfcLogLevel::EMERGENCY => self::SEVERITY_PREFIX . LogLevel::EMERGENCY,
33
  ];
34
35
  /**
36
   * The MongoDB database for the logger alias.
37
   *
38
   * @var \MongoDB
39
   */
40
  protected $database;
41
42
  /**
43
   * The core logger channel, to log intervening events.
44
   *
45
   * @var \Psr\Log\LoggerInterface
46
   */
47
  protected $logger;
48
49
  /**
50
   * The MongoDB logger, to load events.
51
   *
52
   * @var \Drupal\mongodb_watchdog\Logger
53
   */
54
  protected $watchdog;
55
56
  /**
57
   * The module handler service.
58
   *
59
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
60
   */
61
  protected $moduleHandler;
62
63
  /**
64
   * The form builder service.
65
   *
66
   * @var \Drupal\Core\Form\FormBuilderInterface
67
   */
68
  protected $formBuilder;
69
70
  /**
71
   * Constructor.
72
   *
73
   * @param \MongoDB\Database $database
74
   *   The watchdog database.
75
   * @param \Psr\Log\LoggerInterface $logger
76
   *   The logger service, to log intervening events.
77
   * @param \Drupal\mongodb_watchdog\Logger $watchdog
78
   *   The MongoDB logger, to load stored events.
79
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
80
   *   A module handler.
81
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
82
   *   The form builder service.
83
   */
84
  public function __construct(
85
    Database $database,
86
    LoggerInterface $logger,
87
    Logger $watchdog,
88
    ModuleHandlerInterface $module_handler,
89
    FormBuilderInterface $form_builder) {
90
    $this->database = $database;
0 ignored issues
show
Documentation Bug introduced by
It seems like $database of type object<MongoDB\Database> is incompatible with the declared type object<MongoDB> of property $database.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
91
    $this->formBuilder = $form_builder;
92
    $this->logger = $logger;
93
    $this->moduleHandler = $module_handler;
94
    $this->watchdog = $watchdog;
95
  }
96
97
  /**
98
   * {@inheritdoc}
99
   */
100
  public static function create(ContainerInterface $container) {
101
    /** @var \MongoDB $database */
102
    $database = $container->get('mongodb.watchdog_storage');
103
104
    /** @var \Drupal\Core\Form\FormBuilderInterface $form_builder */
105
    $form_builder = $container->get('form_builder');
106
107
    /** @var \Psr\Log\LoggerInterface $logger */
108
    $logger = $container->get('logger.channel.mongodb_watchdog');
109
110
    /** @var \Drupal\Core\Extension\ModuleHandlerInterface $module_handler */
111
    $module_handler = $container->get('module_handler');
112
113
    /** @var \Drupal\mongodb_watchdog\Logger $logger */
114
    $watchdog = $container->get('mongodb.logger');
115
116
    return new static($database, $logger, $watchdog, $module_handler, $form_builder);
117
  }
118
119
  /**
120
   * Controller for mongodb_watchdog.overview.
121
   *
122
   * @return array
123
   *   A render array.
124
   */
125
  public function overview() {
126
    $ret = [
127
      '#attached' => [
128
        'library' => ['mongodb_watchdog/styling']
129
      ]
130
    ] + $this->overviewFilters()
131
      + $this->overviewRows();
0 ignored issues
show
introduced by
Expected 1 space before "+"; newline found
Loading history...
132
133
    $ret += $this->overview7();
134
    return $ret;
135
  }
136
137
  /**
138
   * Build the filters area on top of the event rows.
139
   *
140
   * @return array
141
   *   A render array.
142
   */
143
  public function overviewFilters() {
144
    $build = [
145
      'filter_form' => $this->formBuilder->getForm('Drupal\mongodb_watchdog\Form\OverviewFilterForm')
146
    ];
147
    return $build;
148
  }
149
150
  /**
151
   * Build the event rows
152
   *
153
   * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,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...
154
   *   A render array.
155
   */
156
  public function overviewRows() {
157
    $header = [
158
      t('#'),
159
      t('Severity'),
160
161
    ];
162
    $rows = [];
163
    $levels = RfcLogLevel::getLevels();
164
    $filters = $_SESSION[OverviewFilterForm::SESSION_KEY] ?? NULL;
1 ignored issue
show
introduced by
Expected 1 space after "?"; 0 found
Loading history...
165
    $cursor = $this->watchdog->templates($filters['type'] ?? [], $filters['severity'] ?? []);
1 ignored issue
show
introduced by
Expected 1 space after "?"; 0 found
Loading history...
166
    /** @var \Drupal\mongodb_watchdog\EventTemplate $template */
167
    foreach ($cursor as $template) {
168
      $row = [];
169
      $row[] = $template->count;
170
      $row[] = [
171
        'class' => static::SEVERITY_CLASSES[$template->severity],
172
        'data' => $levels[$template->severity],
173
      ];
174
      $rows[] = $row;
175
    }
176
    return [
177
      'rows' => [
178
        '#type' => 'table',
179
        '#header' => $header,
180
        '#rows' => $rows,
181
      ],
182
    ];
183
  }
184
185
  /**
186
   * Controller for mongodb_watchdog.overview.
187
   *
188
   * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,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...
189
   *   A render array.
190
   */
191
  public function overview7() {
192
    $icons = array(
193
      RfcLogLevel::DEBUG     => '',
194
      RfcLogLevel::INFO      => '',
195
      RfcLogLevel::NOTICE    => '',
196
      RfcLogLevel::WARNING   => ['#theme' => 'image', 'path' => 'misc/watchdog-warning.png', 'alt' => t('warning'), 'title' => t('warning')],
197
      RfcLogLevel::ERROR     => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('error'), 'title' => t('error')],
198
      RfcLogLevel::CRITICAL  => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('critical'), 'title' => t('critical')],
199
      RfcLogLevel::ALERT     => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('alert'), 'title' => t('alert')],
200
      RfcLogLevel::EMERGENCY => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('emergency'), 'title' => t('emergency')],
201
    );
202
203
    $collection = $this->watchdog->templateCollection();
204
    $templates = $collection->find([], Logger::LEGACY_TYPE_MAP)->toArray();
205
    $this->moduleHandler->loadInclude('mongodb_watchdog', 'admin.inc');
206
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
207
208
    $header = array(
209
      // Icon column.
210
      '',
211
      t('#'),
212
      array('data' => t('Type')),
213
      array('data' => t('Date')),
214
      t('Source'),
215
      t('Message'),
216
    );
217
218
    $rows = array();
219
    foreach ($templates as $id => $value) {
220
      if ($id < 5) {
221
//        if ($value['type'] == 'php' && $value['message'] == '%type: %message in %function (line %line of %file).') {
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 118 characters
Loading history...
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
introduced by
8 spaces found before inline comment; expected "// if ($value['type'] == 'php' && $value['message'] == 'type: message in function (line line of file).') {" but found "// if ($value['type'] == 'php' && $value['message'] == 'type: message in function (line line of file).') {"
Loading history...
introduced by
Inline comments must start with a capital letter
Loading history...
222
//          $collection = $this->logger->eventCollection($value['_id']);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
introduced by
Comment indentation error, expected only 8 spaces
Loading history...
223
//          $result = $collection->find()
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
224
//            ->sort(['$natural' => -1])
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
introduced by
Comment indentation error, expected only 10 spaces
Loading history...
225
//            ->limit(1)
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
226
//            ->getNext();
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
227
//          if ($value) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
228
//            $value['file'] = basename($result['variables']['%file']);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
introduced by
Comment indentation error, expected only 10 spaces
Loading history...
229
//            $value['line'] = $result['variables']['%line'];
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
230
//            $value['message'] = '%type in %function';
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
231
//            $value['variables'] = $result['variables'];
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
232
//          }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
233
//        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
234
        $message = Unicode::truncate(strip_tags(SafeMarkup::format($value['message'], [])), 56, TRUE, TRUE);
235
        $value['count'] = $this->watchdog->eventCollection($value['_id'])->count();
236
        $rows[$id] = [
237
          $icons[$value['severity']],
238
          isset($value['count']) && $value['count'] > 1 ? intval($value['count']) : 0,
239
          t($value['type']),
0 ignored issues
show
introduced by
Only string literals should be passed to t() where possible
Loading history...
240
          empty($value['timestamp']) ? '' : format_date($value['timestamp'], 'short'),
241
          empty($value['file']) ? '' : Unicode::truncate(basename($value['file']), 30) . (empty($value['line']) ? '' : ('+' . $value['line'])),
242
          \Drupal::l($message, Url::fromRoute('mongodb_watchdog.reports.detail', ['event_template' => $id])),
243
        ];
244
      }
245
246
    }
247
248
    $build['mongodb_watchdog_table'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$build was never initialized. Although not strictly required by PHP, it is generally a good practice to add $build = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
249
      '#theme' => 'table',
250
      '#header' => $header,
251
      '#rows' => $rows,
252
      '#attributes' => ['id' => 'admin-mongodb_watchdog'],
253
      '#attached' => array(
254
        'library' => array('mongodb_watchdog/drupal.mongodb_watchdog'),
255
      ),
256
    );
257
258
    $build['mongodb_watchdog_pager'] = array('#type' => 'pager');
259
260
    return $build;
261
  }
262
263
}
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...
264