Completed
Push — master ( b67001...22ee1f )
by Jonathan
10s
created

Drupal8::configGetOriginal()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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