Completed
Push — master ( da5e66...74d4ef )
by Pieter
8s
created

Drupal8::roleCreate()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 30
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 14
nc 3
nop 1
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
    $this->expandEntityFields('taxonomy_term', $term);
313
    $entity = Term::create((array) $term);
314
    $entity->save();
315
316
    $term->tid = $entity->id();
317
    return $term;
318
  }
319
320
  /**
321
   * {@inheritdoc}
322
   */
323
  public function termDelete(\stdClass $term) {
324
    $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...
325
    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...
326
      $term->delete();
327
    }
328
  }
329
330
  /**
331
   * {@inheritdoc}
332
   */
333
  public function getModuleList() {
334
    return array_keys(\Drupal::moduleHandler()->getModuleList());
335
  }
336
337
  /**
338
   * {@inheritdoc}
339
   */
340
  public function getExtensionPathList() {
341
    $paths = array();
342
343
    // Get enabled modules.
344
    foreach (\Drupal::moduleHandler()->getModuleList() as $module) {
345
      $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . $module->getPath();
346
    }
347
348
    return $paths;
349
  }
350
351
  /**
352
   * {@inheritdoc}
353
   */
354
  public function getEntityFieldTypes($entity_type) {
355
    $return = array();
356
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
357
    foreach ($fields as $field_name => $field) {
358
      if ($this->isField($entity_type, $field_name)) {
359
        $return[$field_name] = $field->getType();
360
      }
361
    }
362
    return $return;
363
  }
364
365
  /**
366
   * {@inheritdoc}
367
   */
368
  public function isField($entity_type, $field_name) {
369
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
370
    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...
371
  }
372
373
  /**
374
   * {@inheritdoc}
375
   */
376
  public function languageCreate(\stdClass $language) {
377
    $langcode = $language->langcode;
378
379
    // Enable a language only if it has not been enabled already.
380
    if (!ConfigurableLanguage::load($langcode)) {
381
      $created_language = ConfigurableLanguage::createFromLangcode($language->langcode);
382
      if (!$created_language) {
383
        throw new InvalidArgumentException("There is no predefined language with langcode '{$langcode}'.");
384
      }
385
      $created_language->save();
386
      return $language;
387
    }
388
389
    return FALSE;
390
  }
391
392
  /**
393
   * {@inheritdoc}
394
   */
395
  public function languageDelete(\stdClass $language) {
396
    $configurable_language = ConfigurableLanguage::load($language->langcode);
397
    $configurable_language->delete();
398
  }
399
400
  /**
401
   * {@inheritdoc}
402
   */
403
  public function clearStaticCaches() {
404
    drupal_static_reset();
405
    \Drupal::service('cache_tags.invalidator')->resetChecksums();
406
  }
407
408
  /**
409
   * {@inheritdoc}
410
   */
411
  public function configGet($name, $key = '') {
412
    return \Drupal::config($name)->get($key);
413
  }
414
415
  /**
416
   * {@inheritdoc}
417
   */
418
  public function configSet($name, $key, $value) {
419
    \Drupal::configFactory()->getEditable($name)
420
      ->set($key, $value)
421
      ->save();
422
  }
423
424
  /**
425
   * {@inheritdoc}
426
   */
427
  public function entityCreate($entity_type, $entity) {
428
    // If the bundle field is empty, put the inferred bundle value in it.
429
    $bundle_key = \Drupal::entityManager()->getDefinition($entity_type)->getKey('bundle');
430
    if (!isset($entity->$bundle_key) && isset($entity->step_bundle)) {
431
      $entity->$bundle_key = $entity->step_bundle;
432
    }
433
434
    // Throw an exception if a bundle is specified but does not exist.
435
    if (isset($entity->$bundle_key) && ($entity->$bundle_key !== NULL)) {
436
      $bundles = \Drupal::entityManager()->getBundleInfo($entity_type);
437
      if (!in_array($entity->$bundle_key, array_keys($bundles))) {
438
        throw new \Exception("Cannot create entity because provided bundle '$entity->$bundle_key' does not exist.");
439
      }
440
    }
441
    if (empty($entity_type)) {
442
      throw new \Exception("You must specify an entity type to create an entity.");
443
    }
444
445
    $this->expandEntityFields($entity_type, $entity);
446
    $createdEntity = entity_create($entity_type, (array) $entity);
447
    $createdEntity->save();
448
449
    $entity->id = $createdEntity->id();
450
451
    return $entity;
452
  }
453
454
  /**
455
   * {@inheritdoc}
456
   */
457
  public function entityDelete($entity_type, $entity) {
458
    $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...
459
    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...
460
      $entity->delete();
461
    }
462
  }
463
464
}
465