Completed
Push — 8.x-2.x ( 8af97d...4c7eae )
by Frédéric G.
03:11
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
/**
4
 * @file
5
 * Contains MongoDB Logger.
6
 */
7
8
namespace Drupal\mongodb_watchdog;
9
10
11
use Drupal\Component\Utility\Unicode;
12
use Drupal\Core\Logger\LogMessageParserInterface;
13
use Drupal\Core\Logger\RfcLoggerTrait;
14
use Psr\Log\AbstractLogger;
15
use Psr\Log\LoggerInterface;
16
17
/**
18
 * Class Logger is a PSR/3 Logger using a MongoDB data store.
19
 *
20
 * @package Drupal\mongodb_watchdog
21
 */
22
class Logger extends AbstractLogger {
23
24
  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...
25
  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...
26
  const EVENT_COLLECTIONS_PATTERN = '/watchdog_event_[[:xdigit:]]{32}$/';
27
28
29
  /**
30
   * The logger storage.
31
   *
32
   * @var \MongoDB
33
   */
34
  protected $database;
35
36
  /**
37
   * The collection holding message templates.
38
   *
39
   * @var \MongoCollection
40
   */
41
  protected $templatesCollection;
42
43
  /**
44
   * The message's placeholders parser.
45
   *
46
   * @var \Drupal\Core\Logger\LogMessageParserInterface
47
   */
48
  protected $parser;
49
50
  /**
51
   * Constructs a Logger object.
52
   *
53
   * @param \MongoDB $database
54
   *   The database object.
55
   * @param \Drupal\Core\Logger\LogMessageParserInterface $parser
56
   *   The parser to use when extracting message variables.
57
   */
58
  public function __construct(\MongoDB $database, LogMessageParserInterface $parser) {
59
    $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...
60
    $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...
61
    $this->templatesCollection = $database->selectCollection(static::TEMPLATE_COLLECTION);
62
  }
63
64
  /**
65
   * {@inheritdoc}
66
   */
67
  public function log($level, $message, array $context = []) {
68
    // Remove any backtraces since they may contain an unserializable variable.
69
    unset($context['backtrace']);
70
71
    // Convert PSR3-style messages to SafeMarkup::format() style, so they can be
72
    // translated too in runtime.
73
    $message_placeholders = $this->parser->parseMessagePlaceholders($message,
74
      $context);
75
76
    $this->database
77
      ->selectCollection(static::TEMPLATE_COLLECTION)
78
      ->insert([
79
        'uid' => $context['uid'],
80
        'type' => Unicode::substr($context['channel'], 0, 64),
81
        'message' => $message,
82
        'variables' => serialize($message_placeholders),
83
        'severity' => $level,
84
        'link' => $context['link'],
85
        'location' => $context['request_uri'],
86
        'referer' => $context['referer'],
87
        'hostname' => Unicode::substr($context['ip'], 0, 128),
88
        'timestamp' => $context['timestamp'],
89
      ]);
90
  }
91
92
  /**
93
   * List the event collections.
94
   *
95
   * @return \MongoCollection[]
96
   *   The collections with a name matching the event pattern.
97
   */
98
  public function eventCollections() {
99
    $result = [];
100
    foreach ($this->database->listCollections() as $collection) {
101
      $name = $collection->getName();
102
      if (preg_match(static::EVENT_COLLECTIONS_PATTERN, $name)) {
103
        $result[] = $collection;
104
      }
105
    }
106
107
    return $result;
108
  }
109
110
  /**
111
   * Return a collection, given its template id.
112
   *
113
   * @param string $template_id
114
   *   The string representation of a template \MongoId.
115
   *
116
   * @return \MongoCollection
117
   *   A collection object for the specified template id.
118
   */
119
  public function eventCollection($template_id) {
120
    $collection_name = static::EVENT_COLLECTION_PREFIX . $template_id;
121
    assert('preg_match(static::EVENT_COLLECTIONS_PATTERN, $collection_name)');
122
    return $this->database->selectCollection($collection_name);
123
  }
124
125
  /**
126
   * Ensure indexes are set on the collections.
127
   *
128
   * First index is on <line, timestamp> instead of <function, line, timestamp>,
129
   * because we write to this collection a lot, and the smaller index on two
130
   * numbers should be much faster to create than one with a string included.
131
   */
132
  public function ensureIndexes() {
133
    $templates = $this->templatesCollection;
134
    $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...
135
      // Index for adding/updating increments.
136
      [
137
        'line' => 1,
138
        'timestamp' => -1
139
      ],
140
      // Index for admin page without filters.
141
      [
142
        'timestamp' => -1
143
      ],
144
      // Index for admin page filtering by type.
145
      [
146
        'type' => 1,
147
        'timestamp' => -1
148
      ],
149
      // Index for admin page filtering by severity.
150
      [
151
        'severity' => 1,
152
        'timestamp' => -1
153
      ],
154
      // Index for admin page filtering by type and severity.
155
      [
156
        'type' => 1,
157
        'severity' => 1,
158
        'timestamp' => -1
159
      ],
160
    ];
161
162
    foreach ($indexes as $index) {
163
      $templates->ensureIndex($index);
164
    }
165
  }
166
167
  /**
168
   * Load a MongoDB watchdog event.
169
   *
170
   * @param string $id
171
   *   The string representation of a MongoId.
172
   *
173
   * @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...
174
   *   FALSE if the event cannot be loaded.
175
   */
176
  public function eventLoad($id) {
177
    $criteria = ['_id' => $id];
178
    $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...
179
    $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...
180
    return $result;
181
  }
182
183
  /**
184
   * Drop the logger collections.
185
   *
186
   * @return int
187
   *   The number of collections dropped.
188
   */
189
  public function uninstall() {
190
    $count = 0;
191
192
    $collections = $this->eventCollections();
193
    foreach ($collections as $collection) {
194
      $status = $collection->drop();
195
      if ($status['ok'] == 1) {
196
        ++$count;
197
      }
198
    }
199
200
    $status = $this->templatesCollection->drop();
201
    if ($status['ok'] == 1) {
202
      ++$count;
203
    }
204
205
    return $count;
206
  }
207
}
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...
208