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

AdminController::overview()   C

Complexity

Conditions 8
Paths 34

Size

Total Lines 73
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 1
Metric Value
cc 8
eloc 44
c 8
b 0
f 1
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
 * @file
4
 * Contains AdminController.
5
 */
6
7
namespace Drupal\mongodb_watchdog\Controller;
8
9
use Drupal\Component\Utility\SafeMarkup;
10
use Drupal\Component\Utility\Unicode;
11
use Drupal\Core\Controller\ControllerBase;
12
use Drupal\Core\Logger\RfcLogLevel;
13
use Drupal\Core\Url;
14
use Drupal\mongodb\Connection;
15
use Drupal\mongodb_watchdog\Logger;
16
use MongoDB\Database;
17
use Psr\Log\LoggerInterface;
18
use Symfony\Component\DependencyInjection\ContainerInterface;
19
use Drupal\Core\Extension\ModuleHandlerInterface;
20
use Drupal\Core\Form\FormBuilderInterface;
21
22
23
/**
24
 * Class AdminController.
25
 *
26
 * @package Drupal\mongodb_watchdog
27
 */
28
class AdminController extends ControllerBase {
29
30
  /**
0 ignored issues
show
introduced by
Missing short description in doc comment
Loading history...
31
   * @var \MongoDB
32
   */
33
  protected $database;
34
35
  /**
0 ignored issues
show
introduced by
Missing short description in doc comment
Loading history...
36
   * @var \Drupal\mongodb_watchdog\Logger
37
   */
38
  protected $logger;
39
40
  /**
41
   * The module handler service.
42
   *
43
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
44
   */
45
  protected $moduleHandler;
46
47
  /**
48
   * The form builder service.
49
   *
50
   * @var \Drupal\Core\Form\FormBuilderInterface
51
   */
52
  protected $formBuilder;
53
54
  /**
55
   * Constructor.
56
   *
57
   * @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...
58
   *   The watchdog database.
59
   * @param \Psr\Log\LoggerInterface $logger
60
   *   The logger service, to log intervening events.
61
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
62
   *   A module handler.
63
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
64
   *   The form builder service.
65
   * @param \Drupal\mongodb_watchdog\Logger $watchdog
66
   *   The MongoDB Logger, to load events.
67
   */
68
  public function __construct(Database $database, LoggerInterface $logger, ModuleHandlerInterface $module_handler, FormBuilderInterface $form_builder, Logger $watchdog) {
0 ignored issues
show
introduced by
Expected type hint "MongoDB"; found "Database" for $database
Loading history...
69
    $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...
70
    $this->logger = $logger;
0 ignored issues
show
Documentation Bug introduced by
$logger is of type object<Psr\Log\LoggerInterface>, but the property $logger was declared to be of type object<Drupal\mongodb_watchdog\Logger>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

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