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

OverviewController::overview()   C

Complexity

Conditions 8
Paths 34

Size

Total Lines 73
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 44
c 1
b 0
f 0
nc 34
nop 0
dl 0
loc 73
rs 6.3384

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
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\Logger;
11
use MongoDB\Database;
12
use Psr\Log\LogLevel;
13
use Psr\Log\LoggerInterface;
14
use Symfony\Component\DependencyInjection\ContainerInterface;
15
use Drupal\Core\Extension\ModuleHandlerInterface;
16
use Drupal\Core\Form\FormBuilderInterface;
17
18
19
/**
20
 * Class OverviewController provides the main MongoDB Watchdog report page.
21
 */
22
class OverviewController extends ControllerBase {
23
24
  /**
25
   * The MongoDB database for the logger alias.
26
   *
27
   * @var \MongoDB
28
   */
29
  protected $database;
30
31
  /**
32
   * The core logger channel, to log intervening events.
33
   *
34
   * @var \Psr\Log\LoggerInterface
35
   */
36
  protected $logger;
37
38
  /**
39
   * The MongoDB logger, to load events.
40
   *
41
   * @var \Drupal\mongodb_watchdog\Logger
42
   */
43
  protected $watchdog;
44
45
  /**
46
   * The module handler service.
47
   *
48
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
49
   */
50
  protected $moduleHandler;
51
52
  /**
53
   * The form builder service.
54
   *
55
   * @var \Drupal\Core\Form\FormBuilderInterface
56
   */
57
  protected $formBuilder;
58
59
  /**
60
   * Constructor.
61
   *
62
   * @param \MongoDB $database
0 ignored issues
show
Documentation introduced by
Should the type for parameter $database not be Database?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
63
   *   The watchdog database.
64
   * @param \Psr\Log\LoggerInterface $logger
65
   *   The logger service, to log intervening events.
66
   * @param \Drupal\mongodb_watchdog\Logger $watchdog
67
   *   The MongoDB logger, to load stored events.
68
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
69
   *   A module handler.
70
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
71
   *   The form builder service.
72
   */
73
  public function __construct(Database $database, LoggerInterface $logger, Logger $watchdog, ModuleHandlerInterface $module_handler, FormBuilderInterface $form_builder) {
0 ignored issues
show
introduced by
Expected type hint "MongoDB"; found "Database" for $database
Loading history...
74
    $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...
75
    $this->logger = $logger;
76
    $this->moduleHandler = $module_handler;
77
    $this->formBuilder = $form_builder;
78
    $this->watchdog = $watchdog;
79
  }
80
81
  /**
82
   * Controller for mongodb_watchdog.overview.
83
   *
84
   * @return array
85
   *   A render array.
86
   */
87
  public function overview() {
88
    $icons = array(
89
      RfcLogLevel::DEBUG     => '',
90
      RfcLogLevel::INFO      => '',
91
      RfcLogLevel::NOTICE    => '',
92
      RfcLogLevel::WARNING   => ['#theme' => 'image', 'path' => 'misc/watchdog-warning.png', 'alt' => t('warning'), 'title' => t('warning')],
93
      RfcLogLevel::ERROR     => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('error'), 'title' => t('error')],
94
      RfcLogLevel::CRITICAL  => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('critical'), 'title' => t('critical')],
95
      RfcLogLevel::ALERT     => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('alert'), 'title' => t('alert')],
96
      RfcLogLevel::EMERGENCY => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('emergency'), 'title' => t('emergency')],
97
    );
98
99
    $collection = $this->watchdog->templateCollection();
100
    $templates = $collection->find([], Logger::LEGACY_TYPE_MAP)->toArray();
101
ksm($templates);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 4 spaces, found 0
Loading history...
102
    $this->moduleHandler->loadInclude('mongodb_watchdog', 'admin.inc');
103
104
    $build['dblog_filter_form'] = $this->formBuilder->getForm('Drupal\mongodb_watchdog\Form\MongodbWatchdogFilterForm');
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...
105
106
    $header = array(
107
      // Icon column.
108
      '',
109
      t('#'),
110
      array('data' => t('Type')),
111
      array('data' => t('Date')),
112
      t('Source'),
113
      t('Message'),
114
    );
115
116
    $rows = array();
117
    foreach ($templates as $id => $value) {
118
      if ($id < 5) {
119
//        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...
120
//          $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...
121
//          $result = $collection->find()
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
122
//            ->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...
123
//            ->limit(1)
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
124
//            ->getNext();
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
125
//          if ($value) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
126
//            $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...
127
//            $value['line'] = $result['variables']['%line'];
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
128
//            $value['message'] = '%type in %function';
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
129
//            $value['variables'] = $result['variables'];
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
130
//          }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
131
//        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
132
        $message = Unicode::truncate(strip_tags(SafeMarkup::format($value['message'], [])), 56, TRUE, TRUE);
133
        $value['count'] = $this->watchdog->eventCollection($value['_id'])->count();
134
        $rows[$id] = [
135
          $icons[$value['severity']],
136
          isset($value['count']) && $value['count'] > 1 ? intval($value['count']) : 0,
137
          t($value['type']),
0 ignored issues
show
introduced by
Only string literals should be passed to t() where possible
Loading history...
138
          empty($value['timestamp']) ? '' : format_date($value['timestamp'], 'short'),
139
          empty($value['file']) ? '' : Unicode::truncate(basename($value['file']), 30) . (empty($value['line']) ? '' : ('+' . $value['line'])),
140
          \Drupal::l($message, Url::fromRoute('mongodb_watchdog.reports.detail', ['event_template' => $id])),
141
        ];
142
      }
143
144
    }
145
kint($rows);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 4 spaces, found 0
Loading history...
146
    $build['mongodb_watchdog_table'] = array(
147
      '#theme' => 'table',
148
      '#header' => $header,
149
      '#rows' => $rows,
150
      '#attributes' => ['id' => 'admin-mongodb_watchdog'],
151
      '#attached' => array(
152
        'library' => array('mongodb_watchdog/drupal.mongodb_watchdog'),
153
      ),
154
    );
155
156
    $build['mongodb_watchdog_pager'] = array('#type' => 'pager');
157
158
    return $build;
159
  }
160
161
  /**
162
   * The controller factory.
163
   *
164
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
165
   *   The DIC.
166
   *
167
   * @return static
168
   *   The database instance.
169
   */
170
  public static function create(ContainerInterface $container) {
171
    /** @var \MongoDB $database */
172
    $database = $container->get('mongodb.watchdog_storage');
173
174
    $form_builder = $container->get('form_builder');
175
176
    $module_handler = $container->get('module_handler');
177
178
    /** @var \Psr\Log\LoggerInterface $logger */
179
    $logger = $container->get('logger.channel.mongodb_watchdog');
180
181
    /** @var \Drupal\mongodb_watchdog\Logger $logger */
182
    $watchdog = $container->get('mongodb.logger');
183
184
    return new static($database, $logger, $watchdog, $module_handler, $form_builder);
185
  }
186
}
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...
187