Completed
Push — 8.x-2.x ( df78be...308518 )
by Frédéric G.
04:56 queued 04:51
created

AdminForm::buildForm()   C

Complexity

Conditions 10
Paths 97

Size

Total Lines 64
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 49
c 1
b 0
f 0
nc 97
nop 2
dl 0
loc 64
rs 6.309

How to fix   Long Method    Complexity   

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 AdminForm.
5
 */
6
7
namespace Drupal\mongodb_watchdog\Form;
8
9
use Drupal\Core\Form\FormBase;
10
use Drupal\Core\Form\FormStateInterface;
11
use Drupal\Component\Utility\SafeMarkup;
12
use Drupal\Component\Utility\Unicode;
13
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
14
use Drupal\Core\Url;
15
use Drupal\mongodb\Connection;
16
use Drupal\mongodb_watchdog\Logger;
17
use Psr\Log\LoggerInterface;
18
use Symfony\Component\DependencyInjection\ContainerInterface;
19
20
/**
21
 * Class AdminForm.
22
 *
23
 * @package Drupal\mongodb_watchdog
24
 */
25
class AdminForm extends FormBase implements ContainerInjectionInterface {
26
27
  /**
0 ignored issues
show
introduced by
Missing short description in doc comment
Loading history...
28
   * @var \MongoDB
29
   */
30
  protected $database;
31
32
  /**
0 ignored issues
show
introduced by
Missing short description in doc comment
Loading history...
33
   * @var \Drupal\mongodb_watchdog\Logger
34
   */
35
  protected $logger;
36
37
  /**
38
   * Constructor.
39
   *
40
   * @param \MongoDB $database
0 ignored issues
show
Documentation introduced by
Should the type for parameter $database not be \MongoDB\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...
41
   *   The watchdog database.
42
   * @param \Drupal\mongodb_watchdog\Logger $logger
0 ignored issues
show
introduced by
Missing parameter comment
Loading history...
43
   */
44
  public function __construct(\MongoDB\database $database, Logger $logger) {
0 ignored issues
show
introduced by
Expected type hint "MongoDB"; found "\MongoDB\database" for $database
Loading history...
45
    $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...
46
    $this->logger = $logger;
47
  }
48
49
  /**
50
   * From for mongodb_watchdog.detail.
51
   *
52
   * @return array
53
   *   A render array.
54
   */
55
  public function detail() {
56
    return [];
57
  }
58
59
  /**
60
   * Form for mongodb_watchdog.overview.
61
   *
62
   * @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...
63
   *   A render array.
64
   */
65
  public function overview() {
66
    $icons = array(
67
      WATCHDOG_DEBUG     => '',
68
      WATCHDOG_INFO      => '',
69
      WATCHDOG_NOTICE    => '',
70
      WATCHDOG_WARNING   => ['#theme' => 'image', 'path' => 'misc/watchdog-warning.png', 'alt' => t('warning'), 'title' => t('warning')],
71
      WATCHDOG_ERROR     => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('error'), 'title' => t('error')],
72
      WATCHDOG_CRITICAL  => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('critical'), 'title' => t('critical')],
73
      WATCHDOG_ALERT     => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('alert'), 'title' => t('alert')],
74
      WATCHDOG_EMERGENCY => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('emergency'), 'title' => t('emergency')],
75
    );
76
77
    $collection = $this->database->selectCollection(Logger::TEMPLATE_COLLECTION);
78
    $cursor = $collection->find();
79
80
    $header = array(
81
      // Icon column.
82
      '',
83
      t('#'),
84
      array('data' => t('Type')),
85
      array('data' => t('Date')),
86
      t('Source'),
87
      t('Message'),
88
    );
89
90
    $rows = array();
91
    foreach ($cursor as $id => $value) {
92
      dsm($value, $id);
0 ignored issues
show
introduced by
The use of function dsm() is discouraged
Loading history...
93
//      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 116 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 6 spaces, found 0
Loading history...
introduced by
6 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...
94
//        $collection = $this->logger->eventCollection($value['_id']);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
introduced by
Comment indentation error, expected only 6 spaces
Loading history...
95
//        $result = $collection->find()
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
96
//                             ->sort(array('$natural' => -1))
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
introduced by
Comment indentation error, expected only 8 spaces
Loading history...
97
//                             ->limit(1)
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
98
//                             ->getNext();
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
99
//        if ($value) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
100
//          $value['file'] = basename($result['variables']['%file']);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
introduced by
Comment indentation error, expected only 8 spaces
Loading history...
101
//          $value['line'] = $result['variables']['%line'];
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
102
//          $value['message'] = '%type in %function';
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
103
//          $value['variables'] = $result['variables'];
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
104
//        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
105
//      }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 0
Loading history...
106
      $message = Unicode::truncate(strip_tags(SafeMarkup::format($value)), 56, TRUE, TRUE);
107
      $value['count'] = $this->logger->eventCollection($value['_id'])->count();
108
      $rows[$id] = array(
109
        $icons[$value['severity']],
110
        isset($value['count']) && $value['count'] > 1 ? intval($value['count']) : 0,
111
        t($value['type']),
0 ignored issues
show
introduced by
Only string literals should be passed to t() where possible
Loading history...
112
        empty($value['timestamp']) ? '' : format_date($value['timestamp'], 'short'),
113
        empty($value['file']) ? '' : Unicode::truncate(basename($value['file']), 30) . (empty($value['line']) ? '' : ('+' . $value['line'])),
114
        \Drupal::l($message, Url::fromRoute('mongodb_watchdog.detail', ['id' => $id])),
115
      );
116
    }
117
118
    $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...
119
      '#theme' => 'table',
120
      '#header' => $header,
121
      '#rows' => $rows,
122
      '#attributes' => ['id' => 'admin-mongodb_watchdog'],
123
    );
124
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
125
126
    return $build;
127
  }
128
129
  /**
130
   * The form factory.
131
   *
132
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
133
   *   The DIC.
134
   *
135
   * @return static
136
   *   The database instance.
137
   */
138
  public static function create(ContainerInterface $container) {
139
    /** @var \MongoDB $database */
140
    $database = $container->get('mongodb.watchdog_storage');
141
    /** @var \Drupal\mongodb_watchdog\Logger $logger */
142
    $logger = $container->get('mongodb.logger');
143
144
    return new static($database, $logger);
145
  }
146
147
148
  /**
149
   * {@inheritdoc}
150
   */
151
  public function getFormId() {
152
    return 'mongodb_watchdog_overview';
153
  }
154
155
  /**
156
   * {@inheritdoc}
157
   */
158
  public function buildForm(array $form, FormStateInterface $form_state) {
159
160
    $form = array();
161
    $icons = array(
162
      WATCHDOG_DEBUG     => '',
163
      WATCHDOG_INFO      => '',
164
      WATCHDOG_NOTICE    => '',
165
      WATCHDOG_WARNING   => ['#theme' => 'image', 'path' => 'misc/watchdog-warning.png', 'alt' => t('warning'), 'title' => t('warning')],
166
      WATCHDOG_ERROR     => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('error'), 'title' => t('error')],
167
      WATCHDOG_CRITICAL  => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('critical'), 'title' => t('critical')],
168
      WATCHDOG_ALERT     => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('alert'), 'title' => t('alert')],
169
      WATCHDOG_EMERGENCY => ['#theme' => 'image', 'path' => 'misc/watchdog-error.png', 'alt' => t('emergency'), 'title' => t('emergency')],
170
    );
171
172
    $collection = $this->database->selectCollection(Logger::TEMPLATE_COLLECTION);
173
    $cursor = $collection->find();
174
175
    $header = array(
176
      // Icon column.
177
      '',
178
      t('#'),
179
      array('data' => t('Type')),
180
      array('data' => t('Date')),
181
      t('Source'),
182
      t('Message'),
183
    );
184
185
    $rows = array();
186
    foreach ($cursor as $id => $value) {
187
      dsm($value, $id);
0 ignored issues
show
introduced by
The use of function dsm() is discouraged
Loading history...
188
      if ($value['type'] == 'php' && $value['message'] == '%type: %message in %function (line %line of %file).') {
189
        $collection = $this->logger->eventCollection($value['_id']);
190
        $result = $collection->find()
191
                             ->sort(array('$natural' => -1))
192
                             ->limit(1)
193
                             ->getNext();
194
        if ($value) {
195
          $value['file'] = basename($result['variables']['%file']);
196
          $value['line'] = $result['variables']['%line'];
197
          $value['message'] = '%type in %function';
198
          $value['variables'] = $result['variables'];
199
        }
200
      }
201
      $message = Unicode::truncate(strip_tags(SafeMarkup::format($value['message'], array())), 56, TRUE, TRUE);
202
      $value['count'] = $this->logger->eventCollection($value['_id'])->count();
203
      $rows[$id] = array(
204
        $icons[$value['severity']],
205
        isset($value['count']) && $value['count'] > 1 ? intval($value['count']) : 0,
206
        t($value['type']),
0 ignored issues
show
introduced by
Only string literals should be passed to t() where possible
Loading history...
207
        empty($value['timestamp']) ? '' : format_date($value['timestamp'], 'short'),
208
        empty($value['file']) ? '' : Unicode::truncate(basename($value['file']), 30) . (empty($value['line']) ? '' : ('+' . $value['line'])),
209
        \Drupal::l($message, Url::fromRoute('mongodb_watchdog.detail', ['id' => $id])),
210
      );
211
    }
212
213
    $form['mongodb_watchdog_table'] = array(
214
      '#theme' => 'table',
215
      '#header' => $header,
216
      '#rows' => $rows,
217
      '#attributes' => ['id' => 'admin-mongodb_watchdog'],
218
    );
219
220
    return $form;
221
  }
222
223
  /**
224
   * {@inheritdoc}
225
   */
226
  public function submitForm(array &$form, FormStateInterface $form_state) {
227
228
  }
229
}
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...
230