Completed
Pull Request — master (#134)
by
unknown
01:26
created

Drupal8   C

Complexity

Total Complexity 77

Size/Duplication

Total Lines 505
Duplicated Lines 1.39 %

Coupling/Cohesion

Components 2
Dependencies 3

Importance

Changes 0
Metric Value
wmc 77
lcom 2
cbo 3
dl 7
loc 505
rs 5.4715
c 0
b 0
f 0

33 Methods

Rating   Name   Duplication   Size   Complexity  
A clearCache() 0 4 1
A bootstrap() 0 20 2
B nodeCreate() 0 24 6
A nodeDelete() 0 6 3
A runCron() 0 3 1
A userCreate() 0 17 2
B roleCreate() 0 30 3
A roleDelete() 0 9 2
A processBatch() 0 6 1
A getAllPermissions() 0 9 2
A convertPermissions() 0 10 3
A checkPermissions() 0 9 3
A userDelete() 0 3 1
A userAddRole() 0 16 3
C validateDrupalSite() 0 51 7
A termCreate() 7 18 3
A termDelete() 0 6 3
A getModuleList() 0 3 1
A getExtensionPathList() 0 10 2
A getEntityFieldTypes() 0 10 3
A isField() 0 4 2
A languageCreate() 0 15 3
A languageDelete() 0 4 1
A clearStaticCaches() 0 4 1
A configGet() 0 3 1
A configSet() 0 5 1
C entityCreate() 0 26 7
A entityDelete() 0 6 3
A startCollectingMail() 0 5 1
A stopCollectingMail() 0 5 1
A getMail() 0 9 2
A clearMail() 0 3 1
A sendMail() 0 8 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Drupal8 often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Drupal8, and based on these observations, apply Extract Interface, too.

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