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

AdminController   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 162
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 6
Bugs 0 Features 0
Metric Value
c 6
b 0
f 0
dl 0
loc 162
rs 10
wmc 11
lcom 1
cbo 0

4 Methods

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