Completed
Push — 8.x-2.x ( 8ecf3f...eae9c1 )
by Frédéric G.
02:53
created

Logger::uninstall()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
c 1
b 0
f 0
nc 6
nop 0
dl 0
loc 18
rs 9.2
1
<?php
2
3
namespace Drupal\mongodb_watchdog;
4
5
use Drupal\Component\Utility\Unicode;
6
use Drupal\Core\Logger\LogMessageParserInterface;
7
use MongoDB\Database;
8
use MongoDB\Driver\Exception\InvalidArgumentException;
9
use Psr\Log\AbstractLogger;
10
11
/**
12
 * Class Logger is a PSR/3 Logger using a MongoDB data store.
13
 *
14
 * @package Drupal\mongodb_watchdog
15
 */
16
class Logger extends AbstractLogger {
17
18
  const TEMPLATE_COLLECTION = 'watchdog';
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
19
  const EVENT_COLLECTION_PREFIX = 'watchdog_event_';
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
20
  const EVENT_COLLECTIONS_PATTERN = '^watchdog_event_[[:xdigit:]]{24}$';
21
22
  /**
23
   * The logger storage.
24
   *
25
   * @var \MongoDB\Database
26
   */
27
  protected $database;
28
29
  /**
30
   * The collection holding message templates.
31
   *
32
   * @var \MongoDB\Collection
33
   */
34
  protected $templatesCollection;
35
36
  /**
37
   * The message's placeholders parser.
38
   *
39
   * @var \Drupal\Core\Logger\LogMessageParserInterface
40
   */
41
  protected $parser;
42
43
  /**
44
   * Constructs a Logger object.
45
   *
46
   * @param \MongoDB\Database $database
47
   *   The database object.
48
   * @param \Drupal\Core\Logger\LogMessageParserInterface $parser
49
   *   The parser to use when extracting message variables.
50
   */
51
  public function __construct(Database $database, LogMessageParserInterface $parser) {
52
    $this->database = $database;
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 12 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
53
    $this->parser = $parser;
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 14 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
54
    $this->templatesCollection = $database->selectCollection(static::TEMPLATE_COLLECTION);
55
  }
56
57
  /**
58
   * {@inheritdoc}
59
   */
60
  public function log($level, $message, array $context = []) {
61
    // Remove any backtraces since they may contain an unserializable variable.
62
    unset($context['backtrace']);
63
64
    // Convert PSR3-style messages to SafeMarkup::format() style, so they can be
65
    // translated too in runtime.
66
    $message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
67
68
    $template_result = $this->database
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
69
      ->selectCollection(static::TEMPLATE_COLLECTION)
70
      ->insertOne([
71
        'type' => Unicode::substr($context['channel'], 0, 64),
72
        'message' => $message,
73
        'severity' => $level,
74
      ]);
75
    $template_id = $template_result->getInsertedId();
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
76
    $event_collection = $this->eventCollection($template_id);
77
    $event_collection->insertOne([
78
      'hostname' => Unicode::substr($context['ip'], 0, 128),
79
      'link' => $context['link'],
80
      'location' => $context['request_uri'],
81
      'referer' => $context['referer'],
82
      'timestamp' => $context['timestamp'],
83
      'user' => array(
84
        // 'name' => isset($account->name) ? $account->name : t('Anonymous')).
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
85
        'uid' => $context['uid'],
86
      ),
87
      'variables' => $message_placeholders,
88
    ]);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 6 spaces, found 4
Loading history...
89
  }
90
91
  /**
92
   * List the event collections.
93
   *
94
   * @return \MongoDB\Collection[]
95
   *   The collections with a name matching the event pattern.
96
   */
97
  public function eventCollections() {
98
    echo static::EVENT_COLLECTIONS_PATTERN;
99
    $options = [
100
      'filter' => [
101
        'name' => ['$regex' => static::EVENT_COLLECTIONS_PATTERN],
102
      ],
103
    ];
104
    $result = iterator_to_array($this->database->listCollections($options));
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
105
    return $result;
106
  }
107
108
  /**
109
   * Return a collection, given its template id.
110
   *
111
   * @param string $template_id
112
   *   The string representation of a template \MongoId.
113
   *
114
   * @return \MongoDB\Collection
115
   *   A collection object for the specified template id.
116
   */
117
  public function eventCollection($template_id) {
118
    $collection_name = static::EVENT_COLLECTION_PREFIX . $template_id;
119
    if (!preg_match('/' . static::EVENT_COLLECTIONS_PATTERN . '/', $collection_name)) {
120
      throw new InvalidArgumentException(t('Invalid watchdog template id `@id`.', [
121
        '@id' => $collection_name,
122
      ]));
123
    }
124
    $collection = $this->database->selectCollection($collection_name);
125
    return $collection;
126
  }
127
128
  /**
129
   * Ensure indexes are set on the collections.
130
   *
131
   * First index is on <line, timestamp> instead of <function, line, timestamp>,
132
   * because we write to this collection a lot, and the smaller index on two
133
   * numbers should be much faster to create than one with a string included.
134
   */
135
  public function ensureIndexes() {
136
    $templates = $this->templatesCollection;
137
    $indexes = [
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
138
      // Index for adding/updating increments.
139
      [
140
        'name' => 'for-increments',
141
        'key' => ['line' => 1, 'timestamp' => -1],
142
      ],
143
144
      // Index for admin page without filters.
145
      [
146
        'name' => 'admin-no-filters',
147
        'key' => ['timestamp' => -1],
148
      ],
149
150
      // Index for admin page filtering by type.
151
      [
152
        'name' => 'admin-by-type',
153
        'key' => ['type' => 1, 'timestamp' => -1],
154
      ],
155
156
      // Index for admin page filtering by severity.
157
      [
158
        'name' => 'admin-by-severity',
159
        'key' => ['severity' => 1, 'timestamp' => -1],
160
      ],
161
162
      // Index for admin page filtering by type and severity.
163
      [
164
        'name' => 'admin-by-both',
165
        'key' => ['type' => 1, 'severity' => 1, 'timestamp' => -1],
166
      ],
167
    ];
168
    $templates->createIndexes($indexes);
169
  }
170
171
  /**
172
   * Load a MongoDB watchdog event.
173
   *
174
   * @param string $id
175
   *   The string representation of a MongoId.
176
   *
177
   * @return \Drupal\mongodb_watchdog\Event|bool
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use Event|false.

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...
178
   *   FALSE if the event cannot be loaded.
179
   */
180
  public function eventLoad($id) {
181
    $criteria = ['_id' => $id];
182
    $result = new Event($this->templatesCollection->findOne($criteria));
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
Bug introduced by
It seems like $this->templatesCollection->findOne($criteria) targeting MongoDB\Collection::findOne() can also be of type null or object; however, Drupal\mongodb_watchdog\Event::__construct() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
183
    $result = $result ?: FALSE;
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
184
    return $result;
185
  }
186
187
}
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...
188