Drupal8::stopCollectingMailSystemMail()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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