Completed
Pull Request — master (#101)
by
unknown
02:11
created

Drupal8::termDelete()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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