Completed
Push — master ( ef3bca...8ad209 )
by Jonathan
02:53 queued 01:19
created

Drupal8::getMail()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 0
1
<?php
2
3
namespace Drupal\Driver\Cores;
4
5
use Drupal\Core\DrupalKernel;
6
use Drupal\Core\Field\BaseFieldDefinition;
7
use Drupal\Driver\Exception\BootstrapException;
8
use Drupal\field\Entity\FieldStorageConfig;
9
use Drupal\language\Entity\ConfigurableLanguage;
10
use Drupal\node\Entity\Node;
11
use Drupal\node\NodeInterface;
12
use Drupal\Core\Entity\ContentEntityInterface;
13
use Drupal\taxonomy\Entity\Term;
14
use Drupal\taxonomy\TermInterface;
15
use Symfony\Component\HttpFoundation\Request;
16
17
/**
18
 * Drupal 8 core.
19
 */
20
class Drupal8 extends AbstractCore {
21
22
  /**
23
   * {@inheritdoc}
24
   */
25
  public function bootstrap() {
26
    // Validate, and prepare environment for Drupal bootstrap.
27
    if (!defined('DRUPAL_ROOT')) {
28
      define('DRUPAL_ROOT', $this->drupalRoot);
29
    }
30
31
    // Bootstrap Drupal.
32
    chdir(DRUPAL_ROOT);
33
    $autoloader = require DRUPAL_ROOT . '/autoload.php';
34
    require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
35
    $this->validateDrupalSite();
36
37
    $request = Request::createFromGlobals();
38
    $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
39
    $kernel->boot();
40
    $kernel->prepareLegacyRequest($request);
41
42
    // Initialise an anonymous session. required for the bootstrap.
43
    \Drupal::service('session_manager')->start();
44
  }
45
46
  /**
47
   * {@inheritdoc}
48
   */
49
  public function clearCache() {
50
    // Need to change into the Drupal root directory or the registry explodes.
51
    drupal_flush_all_caches();
52
  }
53
54
  /**
55
   * {@inheritdoc}
56
   */
57
  public function nodeCreate($node) {
58
    // Throw an exception if the node type is missing or does not exist.
59
    if (!isset($node->type) || !$node->type) {
60
      throw new \Exception("Cannot create content because it is missing the required property 'type'.");
61
    }
62
    $bundles = \Drupal::entityManager()->getBundleInfo('node');
63
    if (!in_array($node->type, array_keys($bundles))) {
64
      throw new \Exception("Cannot create content because provided content type '$node->type' does not exist.");
65
    }
66
    // If 'author' is set, remap it to 'uid'.
67
    if (isset($node->author)) {
68
      $user = user_load_by_name($node->author);
69
      if ($user) {
70
        $node->uid = $user->id();
71
      }
72
    }
73
    $this->expandEntityFields('node', $node);
74
    $entity = Node::create((array) $node);
75
    $entity->save();
76
77
    $node->nid = $entity->id();
78
79
    return $node;
80
  }
81
82
  /**
83
   * {@inheritdoc}
84
   */
85
  public function nodeDelete($node) {
86
    $node = $node instanceof NodeInterface ? $node : Node::load($node->nid);
0 ignored issues
show
Bug introduced by
The class Drupal\node\NodeInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
87
    if ($node instanceof NodeInterface) {
0 ignored issues
show
Bug introduced by
The class Drupal\node\NodeInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
88
      $node->delete();
89
    }
90
  }
91
92
  /**
93
   * {@inheritdoc}
94
   */
95
  public function runCron() {
96
    return \Drupal::service('cron')->run();
97
  }
98
99
  /**
100
   * {@inheritdoc}
101
   */
102
  public function userCreate(\stdClass $user) {
103
    $this->validateDrupalSite();
104
105
    // Default status to TRUE if not explicitly creating a blocked user.
106
    if (!isset($user->status)) {
107
      $user->status = 1;
108
    }
109
110
    // Clone user object, otherwise user_save() changes the password to the
111
    // hashed password.
112
    $this->expandEntityFields('user', $user);
113
    $account = entity_create('user', (array) $user);
114
    $account->save();
115
116
    // Store UID.
117
    $user->uid = $account->id();
118
  }
119
120
  /**
121
   * {@inheritdoc}
122
   */
123
  public function roleCreate(array $permissions) {
124
    // Generate a random, lowercase machine name.
125
    $rid = strtolower($this->random->name(8, TRUE));
126
127
    // Generate a random label.
128
    $name = trim($this->random->name(8, TRUE));
129
130
    // Convert labels to machine names.
131
    $this->convertPermissions($permissions);
132
133
    // Check the all the permissions strings are valid.
134
    $this->checkPermissions($permissions);
135
136
    // Create new role.
137
    $role = entity_create('user_role', array(
138
      'id' => $rid,
139
      'label' => $name,
140
    ));
141
    $result = $role->save();
142
143
    if ($result === SAVED_NEW) {
144
      // Grant the specified permissions to the role, if any.
145
      if (!empty($permissions)) {
146
        user_role_grant_permissions($role->id(), $permissions);
147
      }
148
      return $role->id();
149
    }
150
151
    throw new \RuntimeException(sprintf('Failed to create a role with "%s" permission(s).', implode(', ', $permissions)));
152
  }
153
154
  /**
155
   * {@inheritdoc}
156
   */
157
  public function roleDelete($role_name) {
158
    $role = user_role_load($role_name);
159
160
    if (!$role) {
161
      throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
162
    }
163
164
    $role->delete();
165
  }
166
167
  /**
168
   * {@inheritdoc}
169
   */
170
  public function processBatch() {
171
    $this->validateDrupalSite();
172
    $batch =& batch_get();
173
    $batch['progressive'] = FALSE;
174
    batch_process();
175
  }
176
177
  /**
178
   * Retrieve all permissions.
179
   *
180
   * @return array
181
   *   Array of all defined permissions.
182
   */
183
  protected function getAllPermissions() {
184
    $permissions = &drupal_static(__FUNCTION__);
185
186
    if (!isset($permissions)) {
187
      $permissions = \Drupal::service('user.permissions')->getPermissions();
188
    }
189
190
    return $permissions;
191
  }
192
193
  /**
194
   * Convert any permission labels to machine name.
195
   *
196
   * @param array &$permissions
197
   *   Array of permission names.
198
   */
199
  protected function convertPermissions(array &$permissions) {
200
    $all_permissions = $this->getAllPermissions();
201
202
    foreach ($all_permissions as $name => $definition) {
203
      $key = array_search($definition['title'], $permissions);
204
      if (FALSE !== $key) {
205
        $permissions[$key] = $name;
206
      }
207
    }
208
  }
209
210
  /**
211
   * Check to make sure that the array of permissions are valid.
212
   *
213
   * @param array $permissions
214
   *   Permissions to check.
215
   */
216
  protected function checkPermissions(array &$permissions) {
217
    $available = array_keys($this->getAllPermissions());
218
219
    foreach ($permissions as $permission) {
220
      if (!in_array($permission, $available)) {
221
        throw new \RuntimeException(sprintf('Invalid permission "%s".', $permission));
222
      }
223
    }
224
  }
225
226
  /**
227
   * {@inheritdoc}
228
   */
229
  public function userDelete(\stdClass $user) {
230
    user_cancel(array(), $user->uid, 'user_cancel_delete');
231
  }
232
233
  /**
234
   * {@inheritdoc}
235
   */
236
  public function userAddRole(\stdClass $user, $role_name) {
237
    // Allow both machine and human role names.
238
    $roles = user_role_names();
239
    $id = array_search($role_name, $roles);
240
    if (FALSE !== $id) {
241
      $role_name = $id;
242
    }
243
244
    if (!$role = user_role_load($role_name)) {
245
      throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
246
    }
247
248
    $account = \user_load($user->uid);
249
    $account->addRole($role->id());
250
    $account->save();
251
  }
252
253
  /**
254
   * {@inheritdoc}
255
   */
256
  public function validateDrupalSite() {
257
    if ('default' !== $this->uri) {
258
      // Fake the necessary HTTP headers that Drupal needs:
259
      $drupal_base_url = parse_url($this->uri);
260
      // If there's no url scheme set, add http:// and re-parse the url
261
      // so the host and path values are set accurately.
262
      if (!array_key_exists('scheme', $drupal_base_url)) {
263
        $drupal_base_url = parse_url($this->uri);
264
      }
265
      // Fill in defaults.
266
      $drupal_base_url += array(
267
        'path' => NULL,
268
        'host' => NULL,
269
        'port' => NULL,
270
      );
271
      $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
272
273
      if ($drupal_base_url['port']) {
274
        $_SERVER['HTTP_HOST'] .= ':' . $drupal_base_url['port'];
275
      }
276
      $_SERVER['SERVER_PORT'] = $drupal_base_url['port'];
277
278
      if (array_key_exists('path', $drupal_base_url)) {
279
        $_SERVER['PHP_SELF'] = $drupal_base_url['path'] . '/index.php';
280
      }
281
      else {
282
        $_SERVER['PHP_SELF'] = '/index.php';
283
      }
284
    }
285
    else {
286
      $_SERVER['HTTP_HOST'] = 'default';
287
      $_SERVER['PHP_SELF'] = '/index.php';
288
    }
289
290
    $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
291
    $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
292
    $_SERVER['REQUEST_METHOD'] = NULL;
293
294
    $_SERVER['SERVER_SOFTWARE'] = NULL;
295
    $_SERVER['HTTP_USER_AGENT'] = NULL;
296
297
    $conf_path = DrupalKernel::findSitePath(Request::createFromGlobals());
298
    $conf_file = $this->drupalRoot . "/$conf_path/settings.php";
299
    if (!file_exists($conf_file)) {
300
      throw new BootstrapException(sprintf('Could not find a Drupal settings.php file at "%s"', $conf_file));
301
    }
302
    $drushrc_file = $this->drupalRoot . "/$conf_path/drushrc.php";
303
    if (file_exists($drushrc_file)) {
304
      require_once $drushrc_file;
305
    }
306
  }
307
308
  /**
309
   * {@inheritdoc}
310
   */
311
  public function termCreate(\stdClass $term) {
312
    $term->vid = $term->vocabulary_machine_name;
313
314 View Code Duplication
    if (isset($term->parent)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
315
      $parent = \taxonomy_term_load_multiple_by_name($term->parent, $term->vocabulary_machine_name);
316
      if (!empty($parent)) {
317
        $parent = reset($parent);
318
        $term->parent = $parent->id();
319
      }
320
    }
321
322
    $this->expandEntityFields('taxonomy_term', $term);
323
    $entity = Term::create((array) $term);
324
    $entity->save();
325
326
    $term->tid = $entity->id();
327
    return $term;
328
  }
329
330
  /**
331
   * {@inheritdoc}
332
   */
333
  public function termDelete(\stdClass $term) {
334
    $term = $term instanceof TermInterface ? $term : Term::load($term->tid);
0 ignored issues
show
Bug introduced by
The class Drupal\taxonomy\TermInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
335
    if ($term instanceof TermInterface) {
0 ignored issues
show
Bug introduced by
The class Drupal\taxonomy\TermInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
336
      $term->delete();
337
    }
338
  }
339
340
  /**
341
   * {@inheritdoc}
342
   */
343
  public function getModuleList() {
344
    return array_keys(\Drupal::moduleHandler()->getModuleList());
345
  }
346
347
  /**
348
   * {@inheritdoc}
349
   */
350
  public function getExtensionPathList() {
351
    $paths = array();
352
353
    // Get enabled modules.
354
    foreach (\Drupal::moduleHandler()->getModuleList() as $module) {
355
      $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . $module->getPath();
356
    }
357
358
    return $paths;
359
  }
360
361
  /**
362
   * Expands specified base fields on the entity object.
363
   *
364
   * @param string $entity_type
365
   *   The entity type for which to return the field types.
366
   * @param \stdClass $entity
367
   *   Entity object.
368
   * @param array $base_fields
369
   *   Base fields to be expanded in addition to user defined fields.
370
   */
371
  public function expandEntityBaseFields($entity_type, \stdClass $entity, array $base_fields) {
372
    $this->expandEntityFields($entity_type, $entity, $base_fields);
373
  }
374
375
  /**
376
   * {@inheritdoc}
377
   */
378
  public function getEntityFieldTypes($entity_type, array $base_fields = array()) {
379
    $return = array();
380
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
381
    foreach ($fields as $field_name => $field) {
382
      if ($this->isField($entity_type, $field_name)
383
        || (in_array($field_name, $base_fields) && $this->isBaseField($entity_type, $field_name))) {
384
        $return[$field_name] = $field->getType();
385
      }
386
    }
387
    return $return;
388
  }
389
390
  /**
391
   * {@inheritdoc}
392
   */
393
  public function isField($entity_type, $field_name) {
394
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
395
    return (isset($fields[$field_name]) && $fields[$field_name] instanceof FieldStorageConfig);
0 ignored issues
show
Bug introduced by
The class Drupal\field\Entity\FieldStorageConfig does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
396
  }
397
398
  /**
399
   * {@inheritdoc}
400
   */
401
  public function isBaseField($entity_type, $field_name) {
402
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
403
    return (isset($fields[$field_name]) && $fields[$field_name] instanceof BaseFieldDefinition);
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Field\BaseFieldDefinition does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
404
  }
405
406
  /**
407
   * {@inheritdoc}
408
   */
409
  public function languageCreate(\stdClass $language) {
410
    $langcode = $language->langcode;
411
412
    // Enable a language only if it has not been enabled already.
413
    if (!ConfigurableLanguage::load($langcode)) {
414
      $created_language = ConfigurableLanguage::createFromLangcode($language->langcode);
415
      if (!$created_language) {
416
        throw new InvalidArgumentException("There is no predefined language with langcode '{$langcode}'.");
417
      }
418
      $created_language->save();
419
      return $language;
420
    }
421
422
    return FALSE;
423
  }
424
425
  /**
426
   * {@inheritdoc}
427
   */
428
  public function languageDelete(\stdClass $language) {
429
    $configurable_language = ConfigurableLanguage::load($language->langcode);
430
    $configurable_language->delete();
431
  }
432
433
  /**
434
   * {@inheritdoc}
435
   */
436
  public function clearStaticCaches() {
437
    drupal_static_reset();
438
    \Drupal::service('cache_tags.invalidator')->resetChecksums();
439
  }
440
441
  /**
442
   * {@inheritdoc}
443
   */
444
  public function configGet($name, $key = '') {
445
    return \Drupal::config($name)->get($key);
446
  }
447
448
  /**
449
   * {@inheritdoc}
450
   */
451
  public function configSet($name, $key, $value) {
452
    \Drupal::configFactory()->getEditable($name)
453
      ->set($key, $value)
454
      ->save();
455
  }
456
457
  /**
458
   * {@inheritdoc}
459
   */
460
  public function entityCreate($entity_type, $entity) {
461
    // If the bundle field is empty, put the inferred bundle value in it.
462
    $bundle_key = \Drupal::entityManager()->getDefinition($entity_type)->getKey('bundle');
463 View Code Duplication
    if (!isset($entity->$bundle_key) && isset($entity->step_bundle)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
464
      $entity->$bundle_key = $entity->step_bundle;
465
    }
466
467
    // Throw an exception if a bundle is specified but does not exist.
468 View Code Duplication
    if (isset($entity->$bundle_key) && ($entity->$bundle_key !== NULL)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
469
      $bundles = \Drupal::entityManager()->getBundleInfo($entity_type);
470
      if (!in_array($entity->$bundle_key, array_keys($bundles))) {
471
        throw new \Exception("Cannot create entity because provided bundle '$entity->$bundle_key' does not exist.");
472
      }
473
    }
474
    if (empty($entity_type)) {
475
      throw new \Exception("You must specify an entity type to create an entity.");
476
    }
477
478
    $this->expandEntityFields($entity_type, $entity);
479
    $createdEntity = entity_create($entity_type, (array) $entity);
480
    $createdEntity->save();
481
482
    $entity->id = $createdEntity->id();
483
484
    return $entity;
485
  }
486
487
  /**
488
   * {@inheritdoc}
489
   */
490
  public function entityDelete($entity_type, $entity) {
491
    $entity = $entity instanceof ContentEntityInterface ? $entity : entity_load($entity_type, $entity->id);
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Entity\ContentEntityInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
492
    if ($entity instanceof ContentEntityInterface) {
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Entity\ContentEntityInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
493
      $entity->delete();
494
    }
495
  }
496
497
  /**
498
   * {@inheritdoc}
499
   */
500
  public function startCollectingMail() {
501
    // @todo Use a collector that supports html after D#2223967 lands.
502
    \Drupal::config('system.mail')->setModuleOverride(['interface' => ['default' => 'test_mail_collector']]);
503
  }
504
505
  /**
506
   * {@inheritdoc}
507
   */
508
  public function stopCollectingMail() {
509
    $original = \Drupal::config('system.mail')->getOriginal('interface.default', FALSE);
510
    \Drupal::config('system.mail')->setModuleOverride(['interface' => ['default' => $original]]);
511
  }
512
513
  /**
514
   * {@inheritdoc}
515
   */
516
  public function getMail() {
517
    \Drupal::state()->resetCache();
518
    $mail = \Drupal::state()->get('system.test_mail_collector') ?: [];
519
    // Discard cancelled mail.
520
    $mail = array_values(array_filter($mail, function ($mailItem) {
521
      return ($mailItem['send'] == TRUE);
522
    }));
523
    return $mail;
524
  }
525
526
  /**
527
   * {@inheritdoc}
528
   */
529
  public function clearMail() {
530
    \Drupal::state()->set('system.test_mail_collector', []);
531
  }
532
533
  /**
534
   * {@inheritdoc}
535
   */
536
  public function sendMail($body = '', $subject = '', $to = '', $langcode = '') {
537
    // Send the mail, via the system module's hook_mail.
538
    $params['context']['message'] = $body;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = 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...
539
    $params['context']['subject'] = $subject;
540
    $mailManager = \Drupal::service('plugin.manager.mail');
541
    $result = $mailManager->mail('system', '', $to, $langcode, $params, NULL, TRUE);
542
    return $result;
543
  }
544
545
}
546