Completed
Pull Request — master (#164)
by
unknown
01:24
created

Drupal8::moduleUninstall()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

This error could be the result of:

1. Missing dependencies

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

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

2. Missing use statement

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

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

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

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

This error could be the result of:

1. Missing dependencies

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

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

2. Missing use statement

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

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

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

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

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

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

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

This error could be the result of:

1. Missing dependencies

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

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

2. Missing use statement

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

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

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

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

This error could be the result of:

1. Missing dependencies

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

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

2. Missing use statement

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

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

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

Loading history...
336
      $term->delete();
337
    }
338
  }
339
340
  /**
341
   * {@inheritdoc}
342
   */
343
  public function getModuleList() {
344
    return array_keys(\Drupal::moduleHandler()->getModuleList());
345
  }
346
347
  /**
348
   * {@inheritdoc}
349
   */
350
  public function getExtensionPathList() {
351
    $paths = array();
352
353
    // Get enabled modules.
354
    foreach (\Drupal::moduleHandler()->getModuleList() as $module) {
355
      $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . $module->getPath();
356
    }
357
358
    return $paths;
359
  }
360
361
  /**
362
   * {@inheritdoc}
363
   */
364
  public function getEntityFieldTypes($entity_type) {
365
    $return = array();
366
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
367
    foreach ($fields as $field_name => $field) {
368
      if ($this->isField($entity_type, $field_name)) {
369
        $return[$field_name] = $field->getType();
370
      }
371
    }
372
    return $return;
373
  }
374
375
  /**
376
   * {@inheritdoc}
377
   */
378
  public function isField($entity_type, $field_name) {
379
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
380
    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...
381
  }
382
383
  /**
384
   * {@inheritdoc}
385
   */
386
  public function languageCreate(\stdClass $language) {
387
    $langcode = $language->langcode;
388
389
    // Enable a language only if it has not been enabled already.
390
    if (!ConfigurableLanguage::load($langcode)) {
391
      $created_language = ConfigurableLanguage::createFromLangcode($language->langcode);
392
      if (!$created_language) {
393
        throw new InvalidArgumentException("There is no predefined language with langcode '{$langcode}'.");
394
      }
395
      $created_language->save();
396
      return $language;
397
    }
398
399
    return FALSE;
400
  }
401
402
  /**
403
   * {@inheritdoc}
404
   */
405
  public function languageDelete(\stdClass $language) {
406
    $configurable_language = ConfigurableLanguage::load($language->langcode);
407
    $configurable_language->delete();
408
  }
409
410
  /**
411
   * {@inheritdoc}
412
   */
413
  public function clearStaticCaches() {
414
    drupal_static_reset();
415
    \Drupal::service('cache_tags.invalidator')->resetChecksums();
416
  }
417
418
  /**
419
   * {@inheritdoc}
420
   */
421
  public function configGet($name, $key = '') {
422
    return \Drupal::config($name)->get($key);
423
  }
424
425
  /**
426
   * {@inheritdoc}
427
   */
428
  public function configSet($name, $key, $value) {
429
    \Drupal::configFactory()->getEditable($name)
430
      ->set($key, $value)
431
      ->save();
432
  }
433
434
  /**
435
   * {@inheritdoc}
436
   */
437
  public function entityCreate($entity_type, $entity) {
438
    // If the bundle field is empty, put the inferred bundle value in it.
439
    $bundle_key = \Drupal::entityManager()->getDefinition($entity_type)->getKey('bundle');
440
    if (!isset($entity->$bundle_key) && isset($entity->step_bundle)) {
441
      $entity->$bundle_key = $entity->step_bundle;
442
    }
443
444
    // Throw an exception if a bundle is specified but does not exist.
445
    if (isset($entity->$bundle_key) && ($entity->$bundle_key !== NULL)) {
446
      $bundles = \Drupal::entityManager()->getBundleInfo($entity_type);
447
      if (!in_array($entity->$bundle_key, array_keys($bundles))) {
448
        throw new \Exception("Cannot create entity because provided bundle '$entity->$bundle_key' does not exist.");
449
      }
450
    }
451
    if (empty($entity_type)) {
452
      throw new \Exception("You must specify an entity type to create an entity.");
453
    }
454
455
    $this->expandEntityFields($entity_type, $entity);
456
    $createdEntity = entity_create($entity_type, (array) $entity);
457
    $createdEntity->save();
458
459
    $entity->id = $createdEntity->id();
460
461
    return $entity;
462
  }
463
464
  /**
465
   * {@inheritdoc}
466
   */
467
  public function entityDelete($entity_type, $entity) {
468
    $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...
469
    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...
470
      $entity->delete();
471
    }
472
  }
473
474
  /**
475
   * {@inheritdoc}
476
   */
477
  public function moduleInstall($module_name) {
478
    // Scan test directories for modules.
479
    $settings = Settings::getAll();
480
    $settings['extension_discovery_scan_tests'] = TRUE;
481
    new Settings($settings);
482
483
    \Drupal::service('module_installer')->install(array($module_name));
484
  }
485
486
  /**
487
   * {@inheritdoc}
488
   */
489
  public function moduleUninstall($module_name) {
490
    \Drupal::service('module_installer')->uninstall(array($module_name));
491
  }
492
493
}
494