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

AdminController::detail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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
    foreach ($cursor as $id => $value) {
119
      if ($id < 5) {
120
        kint($value, $id);
121
        kint($value->_id);
122
//        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...
123
//          $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...
124
//          $result = $collection->find()
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
125
//            ->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...
126
//            ->limit(1)
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
127
//            ->getNext();
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
128
//          if ($value) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
129
//            $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...
130
//            $value['line'] = $result['variables']['%line'];
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
131
//            $value['message'] = '%type in %function';
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
132
//            $value['variables'] = $result['variables'];
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 0
Loading history...
133
//          }
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
        $message = Unicode::truncate(strip_tags(SafeMarkup::format($value['message'], [])), 56, TRUE, TRUE);
136
        $value['count'] = 0; // $this->logger->eventCollection($value['_id'])->count();
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 87 characters
Loading history...
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...
Coding Style introduced by
Comments may not appear after statements
Loading history...
137
        $rows[$id] = [
138
          $icons[$value->severity],
139
          isset($value['count']) && $value['count'] > 1 ? intval($value['count']) : 0,
140
          t($value['type']),
0 ignored issues
show
introduced by
Only string literals should be passed to t() where possible
Loading history...
141
          empty($value['timestamp']) ? '' : format_date($value['timestamp'], 'short'),
142
          empty($value['file']) ? '' : Unicode::truncate(basename($value['file']), 30) . (empty($value['line']) ? '' : ('+' . $value['line'])),
143
          \Drupal::l($message, Url::fromRoute('mongodb_watchdog.reports.detail', ['id' => $id])),
144
        ];
145
      }
146
147
    }
148
kint($rows);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 4 spaces, found 0
Loading history...
149
    $build['mongodb_watchdog_table'] = array(
150
      '#theme' => 'table',
151
      '#header' => $header,
152
      '#rows' => $rows,
153
      '#attributes' => ['id' => 'admin-mongodb_watchdog'],
154
      '#attached' => array(
155
        'library' => array('mongodb_watchdog/drupal.mongodb_watchdog'),
156
      ),
157
    );
158
159
    $build['mongodb_watchdog_pager'] = array('#type' => 'pager');
160
161
    return $build;
162
  }
163
164
  /**
165
   * The controller factory.
166
   *
167
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
168
   *   The DIC.
169
   *
170
   * @return static
171
   *   The database instance.
172
   */
173
  public static function create(ContainerInterface $container) {
174
    /** @var \MongoDB $database */
175
    $database = $container->get('mongodb.watchdog_storage');
176
    /** @var \Psr\Log\LoggerInterface $logger */
177
    $logger = $container->get('logger.factory')->get('mongodb_watchdog');
178
179
    $form_builder = $container->get('form_builder');
180
    $module_handler = $container->get('module_handler');
181
    return new static(
182
      $database,
183
      $logger,
184
      $module_handler,
185
      $form_builder
186
    );
187
  }
188
}
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...
189