Completed
Pull Request — master (#69)
by Pieter
02:08
created

Drupal8::installModules()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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

This error could be the result of:

1. Missing dependencies

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

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

2. Missing use statement

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

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

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

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

This error could be the result of:

1. Missing dependencies

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

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

2. Missing use statement

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

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

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

Loading history...
89
      $node->delete();
90
    }
91
  }
92
93
  /**
94
   * {@inheritdoc}
95
   */
96
  public function runCron() {
97
    return \Drupal::service('cron')->run();
98
  }
99
100
  /**
101
   * {@inheritdoc}
102
   */
103
  public function userCreate(\stdClass $user) {
104
    $this->validateDrupalSite();
105
106
    // Default status to TRUE if not explicitly creating a blocked user.
107
    if (!isset($user->status)) {
108
      $user->status = 1;
109
    }
110
111
    // Clone user object, otherwise user_save() changes the password to the
112
    // hashed password.
113
    $this->expandEntityFields('user', $user);
114
    $account = entity_create('user', (array) $user);
115
    $account->save();
116
117
    // Store UID.
118
    $user->uid = $account->id();
119
  }
120
121
  /**
122
   * {@inheritdoc}
123
   */
124
  public function roleCreate(array $permissions) {
125
    // Generate a random, lowercase machine name.
126
    $rid = strtolower($this->random->name(8, TRUE));
127
128
    // Generate a random label.
129
    $name = trim($this->random->name(8, TRUE));
130
131
    // Convert labels to machine names.
132
    $this->convertPermissions($permissions);
133
134
    // Check the all the permissions strings are valid.
135
    $this->checkPermissions($permissions);
136
137
    // Create new role.
138
    $role = entity_create('user_role', array(
139
      'id' => $rid,
140
      'label' => $name,
141
    ));
142
    $result = $role->save();
143
144
    if ($result === SAVED_NEW) {
145
      // Grant the specified permissions to the role, if any.
146
      if (!empty($permissions)) {
147
        user_role_grant_permissions($role->id(), $permissions);
148
      }
149
      return $role->id();
150
    }
151
152
    throw new \RuntimeException(sprintf('Failed to create a role with "%s" permission(s).', implode(', ', $permissions)));
153
  }
154
155
  /**
156
   * {@inheritdoc}
157
   */
158
  public function roleDelete($role_name) {
159
    $role = user_role_load($role_name);
160
161
    if (!$role) {
162
      throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
163
    }
164
165
    $role->delete();
166
  }
167
168
  /**
169
   * {@inheritdoc}
170
   */
171
  public function processBatch() {
172
    $this->validateDrupalSite();
173
    $batch =& batch_get();
174
    $batch['progressive'] = FALSE;
175
    batch_process();
176
  }
177
178
  /**
179
   * Retrieve all permissions.
180
   *
181
   * @return array
182
   *   Array of all defined permissions.
183
   */
184
  protected function getAllPermissions() {
185
    $permissions = &drupal_static(__FUNCTION__);
186
187
    if (!isset($permissions)) {
188
      $permissions = \Drupal::service('user.permissions')->getPermissions();
189
    }
190
191
    return $permissions;
192
  }
193
194
  /**
195
   * Convert any permission labels to machine name.
196
   *
197
   * @param array &$permissions
198
   *   Array of permission names.
199
   */
200
  protected function convertPermissions(array &$permissions) {
201
    $all_permissions = $this->getAllPermissions();
202
203
    foreach ($all_permissions as $name => $definition) {
204
      $key = array_search($definition['title'], $permissions);
205
      if (FALSE !== $key) {
206
        $permissions[$key] = $name;
207
      }
208
    }
209
  }
210
211
  /**
212
   * Check to make sure that the array of permissions are valid.
213
   *
214
   * @param array $permissions
215
   *   Permissions to check.
216
   */
217
  protected function checkPermissions(array &$permissions) {
218
    $available = array_keys($this->getAllPermissions());
219
220
    foreach ($permissions as $permission) {
221
      if (!in_array($permission, $available)) {
222
        throw new \RuntimeException(sprintf('Invalid permission "%s".', $permission));
223
      }
224
    }
225
  }
226
227
  /**
228
   * {@inheritdoc}
229
   */
230
  public function userDelete(\stdClass $user) {
231
    user_cancel(array(), $user->uid, 'user_cancel_delete');
232
  }
233
234
  /**
235
   * {@inheritdoc}
236
   */
237
  public function userAddRole(\stdClass $user, $role_name) {
238
    // Allow both machine and human role names.
239
    $roles = user_role_names();
240
    $id = array_search($role_name, $roles);
241
    if (FALSE !== $id) {
242
      $role_name = $id;
243
    }
244
245
    if (!$role = user_role_load($role_name)) {
246
      throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
247
    }
248
249
    $account = \user_load($user->uid);
250
    $account->addRole($role->id());
251
    $account->save();
252
  }
253
254
  /**
255
   * {@inheritdoc}
256
   */
257
  public function validateDrupalSite() {
258
    if ('default' !== $this->uri) {
259
      // Fake the necessary HTTP headers that Drupal needs:
260
      $drupal_base_url = parse_url($this->uri);
261
      // If there's no url scheme set, add http:// and re-parse the url
262
      // so the host and path values are set accurately.
263
      if (!array_key_exists('scheme', $drupal_base_url)) {
264
        $drupal_base_url = parse_url($this->uri);
265
      }
266
      // Fill in defaults.
267
      $drupal_base_url += array(
268
        'path' => NULL,
269
        'host' => NULL,
270
        'port' => NULL,
271
      );
272
      $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
273
274
      if ($drupal_base_url['port']) {
275
        $_SERVER['HTTP_HOST'] .= ':' . $drupal_base_url['port'];
276
      }
277
      $_SERVER['SERVER_PORT'] = $drupal_base_url['port'];
278
279
      if (array_key_exists('path', $drupal_base_url)) {
280
        $_SERVER['PHP_SELF'] = $drupal_base_url['path'] . '/index.php';
281
      }
282
      else {
283
        $_SERVER['PHP_SELF'] = '/index.php';
284
      }
285
    }
286
    else {
287
      $_SERVER['HTTP_HOST'] = 'default';
288
      $_SERVER['PHP_SELF'] = '/index.php';
289
    }
290
291
    $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
292
    $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
293
    $_SERVER['REQUEST_METHOD']  = NULL;
294
295
    $_SERVER['SERVER_SOFTWARE'] = NULL;
296
    $_SERVER['HTTP_USER_AGENT'] = NULL;
297
298
    $conf_path = DrupalKernel::findSitePath(Request::createFromGlobals());
299
    $conf_file = $this->drupalRoot . "/$conf_path/settings.php";
300
    if (!file_exists($conf_file)) {
301
      throw new BootstrapException(sprintf('Could not find a Drupal settings.php file at "%s"', $conf_file));
302
    }
303
  }
304
305
  /**
306
   * {@inheritdoc}
307
   */
308
  public function termCreate(\stdClass $term) {
309
    $term->vid = $term->vocabulary_machine_name;
310
    $this->expandEntityFields('taxonomy_term', $term);
311
    $entity = Term::create((array) $term);
312
    $entity->save();
313
314
    $term->tid = $entity->id();
315
    return $term;
316
  }
317
318
  /**
319
   * {@inheritdoc}
320
   */
321
  public function termDelete(\stdClass $term) {
322
    $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...
323
    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...
324
      $term->delete();
325
    }
326
  }
327
328
  /**
329
   * {@inheritdoc}
330
   */
331
  public function getModuleList() {
332
    return array_keys(\Drupal::moduleHandler()->getModuleList());
333
  }
334
335
  /**
336
   * {@inheritdoc}
337
   */
338
  public function installModules(array $modules, $install_dependencies = TRUE) {
339
    try {
340
      \Drupal::service('module_installer')->install($modules, $install_dependencies);
341
    }
342
    catch (\Exception $e) {
343
      throw new ModuleInstallException('The modules could not be installed because an error occurred.', 0, $e);
344
    }
345
  }
346
347
  /**
348
   * {@inheritdoc}
349
   */
350
  public function uninstallModules(array $modules) {
351
    try {
352
      \Drupal::service('module_installer')->uninstall($modules);
353
    }
354
    catch (\Exception $e) {
355
      throw new ModuleUninstallException('The modules could not be uninstalled because an error occurred.', 0, $e);
356
    }
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
   * {@inheritdoc}
375
   */
376
  public function getEntityFieldTypes($entity_type) {
377
    $return = array();
378
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
379
    foreach ($fields as $field_name => $field) {
380
      if ($this->isField($entity_type, $field_name)) {
381
        $return[$field_name] = $field->getType();
382
      }
383
    }
384
    return $return;
385
  }
386
387
  /**
388
   * {@inheritdoc}
389
   */
390
  public function isField($entity_type, $field_name) {
391
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
392
    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...
393
  }
394
395
  /**
396
   * {@inheritdoc}
397
   */
398
  public function languageCreate(\stdClass $language) {
399
    $langcode = $language->langcode;
400
401
    // Enable a language only if it has not been enabled already.
402
    if (!ConfigurableLanguage::load($langcode)) {
403
      $created_language = ConfigurableLanguage::createFromLangcode($language->langcode);
404
      if (!$created_language) {
405
        throw new InvalidArgumentException("There is no predefined language with langcode '{$langcode}'.");
406
      }
407
      $created_language->save();
408
      return $language;
409
    }
410
411
    return FALSE;
412
  }
413
414
  /**
415
   * {@inheritdoc}
416
   */
417
  public function languageDelete(\stdClass $language) {
418
    $configurable_language = ConfigurableLanguage::load($language->langcode);
419
    $configurable_language->delete();
420
  }
421
422
  /**
423
   * {@inheritdoc}
424
   */
425
  public function clearStaticCaches() {
426
    drupal_static_reset();
427
    \Drupal::service('cache_tags.invalidator')->resetChecksums();
428
  }
429
430
}
431