Completed
Push — master ( c3dd96...e8cc44 )
by Jonathan
01:32
created

Drupal8::findMailSystemSenders()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 4
nop 1
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\mailsystem\MailsystemManager;
11
use Drupal\node\Entity\Node;
12
use Drupal\node\NodeInterface;
13
use Drupal\Core\Entity\ContentEntityInterface;
14
use Drupal\taxonomy\Entity\Term;
15
use Drupal\taxonomy\TermInterface;
16
use Symfony\Component\HttpFoundation\Request;
17
18
/**
19
 * Drupal 8 core.
20
 */
21
class Drupal8 extends AbstractCore {
22
23
  /**
24
   * {@inheritdoc}
25
   */
26
  public function bootstrap() {
27
    // Validate, and prepare environment for Drupal bootstrap.
28
    if (!defined('DRUPAL_ROOT')) {
29
      define('DRUPAL_ROOT', $this->drupalRoot);
30
    }
31
32
    // Bootstrap Drupal.
33
    chdir(DRUPAL_ROOT);
34
    $autoloader = require DRUPAL_ROOT . '/autoload.php';
35
    require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
36
    $this->validateDrupalSite();
37
38
    $request = Request::createFromGlobals();
39
    $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
40
    $kernel->boot();
41
    $kernel->prepareLegacyRequest($request);
42
43
    // Initialise an anonymous session. required for the bootstrap.
44
    \Drupal::service('session_manager')->start();
45
  }
46
47
  /**
48
   * {@inheritdoc}
49
   */
50
  public function clearCache() {
51
    // Need to change into the Drupal root directory or the registry explodes.
52
    drupal_flush_all_caches();
53
  }
54
55
  /**
56
   * {@inheritdoc}
57
   */
58
  public function nodeCreate($node) {
59
    // Throw an exception if the node type is missing or does not exist.
60
    if (!isset($node->type) || !$node->type) {
61
      throw new \Exception("Cannot create content because it is missing the required property 'type'.");
62
    }
63
    $bundles = \Drupal::entityManager()->getBundleInfo('node');
64
    if (!in_array($node->type, array_keys($bundles))) {
65
      throw new \Exception("Cannot create content because provided content type '$node->type' does not exist.");
66
    }
67
    // If 'author' is set, remap it to 'uid'.
68
    if (isset($node->author)) {
69
      $user = user_load_by_name($node->author);
70
      if ($user) {
71
        $node->uid = $user->id();
72
      }
73
    }
74
    $this->expandEntityFields('node', $node);
75
    $entity = Node::create((array) $node);
76
    $entity->save();
77
78
    $node->nid = $entity->id();
79
80
    return $node;
81
  }
82
83
  /**
84
   * {@inheritdoc}
85
   */
86
  public function nodeDelete($node) {
87
    $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...
88
    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...
89
      $node->delete();
90
    }
91
  }
92
93
  /**
94
   * {@inheritdoc}
95
   */
96
  public function runCron() {
97
    return \Drupal::service('cron')->run();
98
  }
99
100
  /**
101
   * {@inheritdoc}
102
   */
103
  public function userCreate(\stdClass $user) {
104
    $this->validateDrupalSite();
105
106
    // Default status to TRUE if not explicitly creating a blocked user.
107
    if (!isset($user->status)) {
108
      $user->status = 1;
109
    }
110
111
    // Clone user object, otherwise user_save() changes the password to the
112
    // hashed password.
113
    $this->expandEntityFields('user', $user);
114
    $account = entity_create('user', (array) $user);
115
    $account->save();
116
117
    // Store UID.
118
    $user->uid = $account->id();
119
  }
120
121
  /**
122
   * {@inheritdoc}
123
   */
124
  public function roleCreate(array $permissions) {
125
    // Generate a random, lowercase machine name.
126
    $rid = strtolower($this->random->name(8, TRUE));
127
128
    // Generate a random label.
129
    $name = trim($this->random->name(8, TRUE));
130
131
    // Convert labels to machine names.
132
    $this->convertPermissions($permissions);
133
134
    // Check the all the permissions strings are valid.
135
    $this->checkPermissions($permissions);
136
137
    // Create new role.
138
    $role = entity_create('user_role', array(
139
      'id' => $rid,
140
      'label' => $name,
141
    ));
142
    $result = $role->save();
143
144
    if ($result === SAVED_NEW) {
145
      // Grant the specified permissions to the role, if any.
146
      if (!empty($permissions)) {
147
        user_role_grant_permissions($role->id(), $permissions);
148
      }
149
      return $role->id();
150
    }
151
152
    throw new \RuntimeException(sprintf('Failed to create a role with "%s" permission(s).', implode(', ', $permissions)));
153
  }
154
155
  /**
156
   * {@inheritdoc}
157
   */
158
  public function roleDelete($role_name) {
159
    $role = user_role_load($role_name);
160
161
    if (!$role) {
162
      throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
163
    }
164
165
    $role->delete();
166
  }
167
168
  /**
169
   * {@inheritdoc}
170
   */
171
  public function processBatch() {
172
    $this->validateDrupalSite();
173
    $batch =& batch_get();
174
    $batch['progressive'] = FALSE;
175
    batch_process();
176
  }
177
178
  /**
179
   * Retrieve all permissions.
180
   *
181
   * @return array
182
   *   Array of all defined permissions.
183
   */
184
  protected function getAllPermissions() {
185
    $permissions = &drupal_static(__FUNCTION__);
186
187
    if (!isset($permissions)) {
188
      $permissions = \Drupal::service('user.permissions')->getPermissions();
189
    }
190
191
    return $permissions;
192
  }
193
194
  /**
195
   * Convert any permission labels to machine name.
196
   *
197
   * @param array &$permissions
198
   *   Array of permission names.
199
   */
200
  protected function convertPermissions(array &$permissions) {
201
    $all_permissions = $this->getAllPermissions();
202
203
    foreach ($all_permissions as $name => $definition) {
204
      $key = array_search($definition['title'], $permissions);
205
      if (FALSE !== $key) {
206
        $permissions[$key] = $name;
207
      }
208
    }
209
  }
210
211
  /**
212
   * Check to make sure that the array of permissions are valid.
213
   *
214
   * @param array $permissions
215
   *   Permissions to check.
216
   */
217
  protected function checkPermissions(array &$permissions) {
218
    $available = array_keys($this->getAllPermissions());
219
220
    foreach ($permissions as $permission) {
221
      if (!in_array($permission, $available)) {
222
        throw new \RuntimeException(sprintf('Invalid permission "%s".', $permission));
223
      }
224
    }
225
  }
226
227
  /**
228
   * {@inheritdoc}
229
   */
230
  public function userDelete(\stdClass $user) {
231
    user_cancel(array(), $user->uid, 'user_cancel_delete');
232
  }
233
234
  /**
235
   * {@inheritdoc}
236
   */
237
  public function userAddRole(\stdClass $user, $role_name) {
238
    // Allow both machine and human role names.
239
    $roles = user_role_names();
240
    $id = array_search($role_name, $roles);
241
    if (FALSE !== $id) {
242
      $role_name = $id;
243
    }
244
245
    if (!$role = user_role_load($role_name)) {
246
      throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
247
    }
248
249
    $account = \user_load($user->uid);
250
    $account->addRole($role->id());
251
    $account->save();
252
  }
253
254
  /**
255
   * {@inheritdoc}
256
   */
257
  public function validateDrupalSite() {
258
    if ('default' !== $this->uri) {
259
      // Fake the necessary HTTP headers that Drupal needs:
260
      $drupal_base_url = parse_url($this->uri);
261
      // If there's no url scheme set, add http:// and re-parse the url
262
      // so the host and path values are set accurately.
263
      if (!array_key_exists('scheme', $drupal_base_url)) {
264
        $drupal_base_url = parse_url($this->uri);
265
      }
266
      // Fill in defaults.
267
      $drupal_base_url += array(
268
        'path' => NULL,
269
        'host' => NULL,
270
        'port' => NULL,
271
      );
272
      $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
273
274
      if ($drupal_base_url['port']) {
275
        $_SERVER['HTTP_HOST'] .= ':' . $drupal_base_url['port'];
276
      }
277
      $_SERVER['SERVER_PORT'] = $drupal_base_url['port'];
278
279
      if (array_key_exists('path', $drupal_base_url)) {
280
        $_SERVER['PHP_SELF'] = $drupal_base_url['path'] . '/index.php';
281
      }
282
      else {
283
        $_SERVER['PHP_SELF'] = '/index.php';
284
      }
285
    }
286
    else {
287
      $_SERVER['HTTP_HOST'] = 'default';
288
      $_SERVER['PHP_SELF'] = '/index.php';
289
    }
290
291
    $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
292
    $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
293
    $_SERVER['REQUEST_METHOD'] = NULL;
294
295
    $_SERVER['SERVER_SOFTWARE'] = NULL;
296
    $_SERVER['HTTP_USER_AGENT'] = NULL;
297
298
    $conf_path = DrupalKernel::findSitePath(Request::createFromGlobals());
299
    $conf_file = $this->drupalRoot . "/$conf_path/settings.php";
300
    if (!file_exists($conf_file)) {
301
      throw new BootstrapException(sprintf('Could not find a Drupal settings.php file at "%s"', $conf_file));
302
    }
303
    $drushrc_file = $this->drupalRoot . "/$conf_path/drushrc.php";
304
    if (file_exists($drushrc_file)) {
305
      require_once $drushrc_file;
306
    }
307
  }
308
309
  /**
310
   * {@inheritdoc}
311
   */
312
  public function termCreate(\stdClass $term) {
313
    $term->vid = $term->vocabulary_machine_name;
314
315 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...
316
      $parent = \taxonomy_term_load_multiple_by_name($term->parent, $term->vocabulary_machine_name);
317
      if (!empty($parent)) {
318
        $parent = reset($parent);
319
        $term->parent = $parent->id();
320
      }
321
    }
322
323
    $this->expandEntityFields('taxonomy_term', $term);
324
    $entity = Term::create((array) $term);
325
    $entity->save();
326
327
    $term->tid = $entity->id();
328
    return $term;
329
  }
330
331
  /**
332
   * {@inheritdoc}
333
   */
334
  public function termDelete(\stdClass $term) {
335
    $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...
336
    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...
337
      $term->delete();
338
    }
339
  }
340
341
  /**
342
   * {@inheritdoc}
343
   */
344
  public function getModuleList() {
345
    return array_keys(\Drupal::moduleHandler()->getModuleList());
346
  }
347
348
  /**
349
   * {@inheritdoc}
350
   */
351
  public function getExtensionPathList() {
352
    $paths = array();
353
354
    // Get enabled modules.
355
    foreach (\Drupal::moduleHandler()->getModuleList() as $module) {
356
      $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . $module->getPath();
357
    }
358
359
    return $paths;
360
  }
361
362
  /**
363
   * Expands specified base fields on the entity object.
364
   *
365
   * @param string $entity_type
366
   *   The entity type for which to return the field types.
367
   * @param \stdClass $entity
368
   *   Entity object.
369
   * @param array $base_fields
370
   *   Base fields to be expanded in addition to user defined fields.
371
   */
372
  public function expandEntityBaseFields($entity_type, \stdClass $entity, array $base_fields) {
373
    $this->expandEntityFields($entity_type, $entity, $base_fields);
374
  }
375
376
  /**
377
   * {@inheritdoc}
378
   */
379
  public function getEntityFieldTypes($entity_type, array $base_fields = array()) {
380
    $return = array();
381
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
382
    foreach ($fields as $field_name => $field) {
383
      if ($this->isField($entity_type, $field_name)
384
        || (in_array($field_name, $base_fields) && $this->isBaseField($entity_type, $field_name))) {
385
        $return[$field_name] = $field->getType();
386
      }
387
    }
388
    return $return;
389
  }
390
391
  /**
392
   * {@inheritdoc}
393
   */
394
  public function isField($entity_type, $field_name) {
395
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
396
    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...
397
  }
398
399
  /**
400
   * {@inheritdoc}
401
   */
402
  public function isBaseField($entity_type, $field_name) {
403
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
404
    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...
405
  }
406
407
  /**
408
   * {@inheritdoc}
409
   */
410
  public function languageCreate(\stdClass $language) {
411
    $langcode = $language->langcode;
412
413
    // Enable a language only if it has not been enabled already.
414
    if (!ConfigurableLanguage::load($langcode)) {
415
      $created_language = ConfigurableLanguage::createFromLangcode($language->langcode);
416
      if (!$created_language) {
417
        throw new InvalidArgumentException("There is no predefined language with langcode '{$langcode}'.");
418
      }
419
      $created_language->save();
420
      return $language;
421
    }
422
423
    return FALSE;
424
  }
425
426
  /**
427
   * {@inheritdoc}
428
   */
429
  public function languageDelete(\stdClass $language) {
430
    $configurable_language = ConfigurableLanguage::load($language->langcode);
431
    $configurable_language->delete();
432
  }
433
434
  /**
435
   * {@inheritdoc}
436
   */
437
  public function clearStaticCaches() {
438
    drupal_static_reset();
439
    \Drupal::service('cache_tags.invalidator')->resetChecksums();
440
  }
441
442
  /**
443
   * {@inheritdoc}
444
   */
445
  public function configGet($name, $key = '') {
446
    return \Drupal::config($name)->get($key);
447
  }
448
449
  /**
450
   * {@inheritdoc}
451
   */
452
  public function configSet($name, $key, $value) {
453
    \Drupal::configFactory()->getEditable($name)
454
      ->set($key, $value)
455
      ->save();
456
  }
457
458
  /**
459
   * {@inheritdoc}
460
   */
461
  public function entityCreate($entity_type, $entity) {
462
    // If the bundle field is empty, put the inferred bundle value in it.
463
    $bundle_key = \Drupal::entityManager()->getDefinition($entity_type)->getKey('bundle');
464 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...
465
      $entity->$bundle_key = $entity->step_bundle;
466
    }
467
468
    // Throw an exception if a bundle is specified but does not exist.
469 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...
470
      $bundles = \Drupal::entityManager()->getBundleInfo($entity_type);
471
      if (!in_array($entity->$bundle_key, array_keys($bundles))) {
472
        throw new \Exception("Cannot create entity because provided bundle '$entity->$bundle_key' does not exist.");
473
      }
474
    }
475
    if (empty($entity_type)) {
476
      throw new \Exception("You must specify an entity type to create an entity.");
477
    }
478
479
    $this->expandEntityFields($entity_type, $entity);
480
    $createdEntity = entity_create($entity_type, (array) $entity);
481
    $createdEntity->save();
482
483
    $entity->id = $createdEntity->id();
484
485
    return $entity;
486
  }
487
488
  /**
489
   * {@inheritdoc}
490
   */
491
  public function entityDelete($entity_type, $entity) {
492
    $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...
493
    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...
494
      $entity->delete();
495
    }
496
  }
497
498
  /**
499
   * {@inheritdoc}
500
   */
501
  public function startCollectingMail() {
502
    // @todo Use a collector that supports html after D#2223967 lands.
503
    \Drupal::config('system.mail')->setModuleOverride(['interface' => ['default' => 'test_mail_collector']]);
504
    // Disable the mail system module's mail if enabled.
505
    $this->startCollectingMailSystemMail();
506
  }
507
508
  /**
509
   * {@inheritdoc}
510
   */
511
  public function stopCollectingMail() {
512
    $original = \Drupal::config('system.mail')->getOriginal('interface.default', FALSE);
513
    \Drupal::config('system.mail')->setModuleOverride(['interface' => ['default' => $original]]);
514
    // Re-enable the mailsystem module's mail if enabled.
515
    $this->stopCollectingMailSystemMail();
516
  }
517
518
  /**
519
   * {@inheritdoc}
520
   */
521
  public function getMail() {
522
    \Drupal::state()->resetCache();
523
    $mail = \Drupal::state()->get('system.test_mail_collector') ?: [];
524
    // Discard cancelled mail.
525
    $mail = array_values(array_filter($mail, function ($mailItem) {
526
      return ($mailItem['send'] == TRUE);
527
    }));
528
    return $mail;
529
  }
530
531
  /**
532
   * {@inheritdoc}
533
   */
534
  public function clearMail() {
535
    \Drupal::state()->set('system.test_mail_collector', []);
536
  }
537
538
  /**
539
   * {@inheritdoc}
540
   */
541
  public function sendMail($body = '', $subject = '', $to = '', $langcode = '') {
542
    // Send the mail, via the system module's hook_mail.
543
    $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...
544
    $params['context']['subject'] = $subject;
545
    $mailManager = \Drupal::service('plugin.manager.mail');
546
    $result = $mailManager->mail('system', '', $to, $langcode, $params, NULL, TRUE);
547
    return $result;
548
  }
549
550
  /**
551
   * If the Mail System module is enabled, collect that mail too.
552
   *
553
   * @see MailsystemManager::getPluginInstance()
554
   */
555
  protected function startCollectingMailSystemMail() {
556
    if (\Drupal::moduleHandler()->moduleExists('mailsystem')) {
557
      $data = \Drupal::config('mailsystem.settings')->getRawData();
558
      // Convert all of the 'senders' to the test collector.
559
      $data = $this->findMailSystemSenders($data);
560
      \Drupal::config('mailsystem.settings')->setModuleOverride($data);
561
    }
562
  }
563
564
  /**
565
   * Find and replace all the mail system sender plugins with the test plugin.
566
   *
567
   * This method calls itself recursively.
568
   */
569
  protected function findMailSystemSenders(array $data) {
570
    foreach ($data as $key => $values) {
571
      if (is_array($values)) {
572
        if (isset($values[MailsystemManager::MAILSYSTEM_TYPE_SENDING])) {
573
          $data[$key][MailsystemManager::MAILSYSTEM_TYPE_SENDING] = 'test_mail_collector';
574
        }
575
        else {
576
          $data[$key] = $this->findMailSystemSenders($values);
577
        }
578
      }
579
    }
580
    return $data;
581
  }
582
583
  /**
584
   * If the Mail System module is enabled, stop collecting those mails.
585
   */
586
  protected function stopCollectingMailSystemMail() {
587
    if (\Drupal::moduleHandler()->moduleExists('mailsystem')) {
588
      \Drupal::config('mailsystem.settings')->setModuleOverride([]);
589
    }
590
  }
591
592
}
593