Completed
Push — master ( f267d9...25d6ce )
by Jonathan
8s
created

Drupal8::processBatch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
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\taxonomy\Entity\Term;
12
use Drupal\taxonomy\TermInterface;
13
use Symfony\Component\HttpFoundation\Request;
14
15
/**
16
 * Drupal 8 core.
17
 */
18
class Drupal8 extends AbstractCore {
19
20
  /**
21
   * {@inheritdoc}
22
   */
23
  public function bootstrap() {
24
    // Validate, and prepare environment for Drupal bootstrap.
25
    if (!defined('DRUPAL_ROOT')) {
26
      define('DRUPAL_ROOT', $this->drupalRoot);
27
    }
28
29
    // Bootstrap Drupal.
30
    chdir(DRUPAL_ROOT);
31
    $autoloader = require DRUPAL_ROOT . '/autoload.php';
32
    require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
33
    $this->validateDrupalSite();
34
35
    $request = Request::createFromGlobals();
36
    $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
37
    $kernel->boot();
38
    $kernel->prepareLegacyRequest($request);
39
40
    // Initialise an anonymous session. required for the bootstrap.
41
    \Drupal::service('session_manager')->start();
42
  }
43
44
  /**
45
   * {@inheritdoc}
46
   */
47
  public function clearCache() {
48
    // Need to change into the Drupal root directory or the registry explodes.
49
    drupal_flush_all_caches();
50
  }
51
52
  /**
53
   * {@inheritdoc}
54
   */
55
  public function nodeCreate($node) {
56
    // Throw an exception if the node type is missing or does not exist.
57
    if (!isset($node->type) || !$node->type) {
58
      throw new \Exception("Cannot create content because it is missing the required property 'type'.");
59
    }
60
    $bundles = \Drupal::entityManager()->getBundleInfo('node');
61
    if (!in_array($node->type, array_keys($bundles))) {
62
      throw new \Exception("Cannot create content because provided content type '$node->type' does not exist.");
63
    }
64
    // Default status to 1 if not set.
65
    if (!isset($node->status)) {
66
      $node->status = 1;
67
    }
68
    // If 'author' is set, remap it to 'uid'.
69
    if (isset($node->author)) {
70
      $user = user_load_by_name($node->author);
71
      if ($user) {
72
        $node->uid = $user->id();
73
      }
74
    }
75
    $this->expandEntityFields('node', $node);
76
    $entity = entity_create('node', (array) $node);
77
    $entity->save();
78
79
    $node->nid = $entity->id();
80
81
    return $node;
82
  }
83
84
  /**
85
   * {@inheritdoc}
86
   */
87
  public function nodeDelete($node) {
88
    $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...
89
    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...
90
      $node->delete();
91
    }
92
  }
93
94
  /**
95
   * {@inheritdoc}
96
   */
97
  public function runCron() {
98
    return \Drupal::service('cron')->run();
99
  }
100
101
  /**
102
   * {@inheritdoc}
103
   */
104
  public function userCreate(\stdClass $user) {
105
    $this->validateDrupalSite();
106
107
    // Default status to TRUE if not explicitly creating a blocked user.
108
    if (!isset($user->status)) {
109
      $user->status = 1;
110
    }
111
112
    // Clone user object, otherwise user_save() changes the password to the
113
    // hashed password.
114
    $this->expandEntityFields('user', $user);
115
    $account = entity_create('user', (array) $user);
116
    $account->save();
117
118
    // Store UID.
119
    $user->uid = $account->id();
120
  }
121
122
  /**
123
   * {@inheritdoc}
124
   */
125
  public function roleCreate(array $permissions) {
126
    // Generate a random, lowercase machine name.
127
    $rid = strtolower($this->random->name(8, TRUE));
128
129
    // Generate a random label.
130
    $name = trim($this->random->name(8, TRUE));
131
132
    // Convert labels to machine names.
133
    $this->convertPermissions($permissions);
134
135
    // Check the all the permissions strings are valid.
136
    $this->checkPermissions($permissions);
137
138
    // Create new role.
139
    $role = entity_create('user_role', array(
140
      'id' => $rid,
141
      'label' => $name,
142
    ));
143
    $result = $role->save();
144
145
    if ($result === SAVED_NEW) {
146
      // Grant the specified permissions to the role, if any.
147
      if (!empty($permissions)) {
148
        user_role_grant_permissions($role->id(), $permissions);
149
      }
150
      return $role->id();
151
    }
152
153
    throw new \RuntimeException(sprintf('Failed to create a role with "%s" permission(s).', implode(', ', $permissions)));
154
  }
155
156
  /**
157
   * {@inheritdoc}
158
   */
159
  public function roleDelete($role_name) {
160
    $role = user_role_load($role_name);
161
162
    if (!$role) {
163
      throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
164
    }
165
166
    $role->delete();
167
  }
168
169
  /**
170
   * {@inheritdoc}
171
   */
172
  public function processBatch() {
173
    $this->validateDrupalSite();
174
    $batch =& batch_get();
175
    $batch['progressive'] = FALSE;
176
    batch_process();
177
  }
178
179
  /**
180
   * Retrieve all permissions.
181
   *
182
   * @return array
183
   *   Array of all defined permissions.
184
   */
185
  protected function getAllPermissions() {
186
    $permissions = &drupal_static(__FUNCTION__);
187
188
    if (!isset($permissions)) {
189
      $permissions = \Drupal::service('user.permissions')->getPermissions();
190
    }
191
192
    return $permissions;
193
  }
194
195
  /**
196
   * Convert any permission labels to machine name.
197
   *
198
   * @param array &$permissions
199
   *   Array of permission names.
200
   */
201
  protected function convertPermissions(array &$permissions) {
202
    $all_permissions = $this->getAllPermissions();
203
204
    foreach ($all_permissions as $name => $definition) {
205
      $key = array_search($definition['title'], $permissions);
206
      if (FALSE !== $key) {
207
        $permissions[$key] = $name;
208
      }
209
    }
210
  }
211
212
  /**
213
   * Check to make sure that the array of permissions are valid.
214
   *
215
   * @param array $permissions
216
   *   Permissions to check.
217
   */
218
  protected function checkPermissions(array &$permissions) {
219
    $available = array_keys($this->getAllPermissions());
220
221
    foreach ($permissions as $permission) {
222
      if (!in_array($permission, $available)) {
223
        throw new \RuntimeException(sprintf('Invalid permission "%s".', $permission));
224
      }
225
    }
226
  }
227
228
  /**
229
   * {@inheritdoc}
230
   */
231
  public function userDelete(\stdClass $user) {
232
    user_cancel(array(), $user->uid, 'user_cancel_delete');
233
  }
234
235
  /**
236
   * {@inheritdoc}
237
   */
238
  public function userAddRole(\stdClass $user, $role_name) {
239
    // Allow both machine and human role names.
240
    $roles = user_role_names();
241
    $id = array_search($role_name, $roles);
242
    if (FALSE !== $id) {
243
      $role_name = $id;
244
    }
245
246
    if (!$role = user_role_load($role_name)) {
247
      throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
248
    }
249
250
    $account = \user_load($user->uid);
251
    $account->addRole($role->id());
252
    $account->save();
253
  }
254
255
  /**
256
   * {@inheritdoc}
257
   */
258
  public function validateDrupalSite() {
259
    if ('default' !== $this->uri) {
260
      // Fake the necessary HTTP headers that Drupal needs:
261
      $drupal_base_url = parse_url($this->uri);
262
      // If there's no url scheme set, add http:// and re-parse the url
263
      // so the host and path values are set accurately.
264
      if (!array_key_exists('scheme', $drupal_base_url)) {
265
        $drupal_base_url = parse_url($this->uri);
266
      }
267
      // Fill in defaults.
268
      $drupal_base_url += array(
269
        'path' => NULL,
270
        'host' => NULL,
271
        'port' => NULL,
272
      );
273
      $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
274
275
      if ($drupal_base_url['port']) {
276
        $_SERVER['HTTP_HOST'] .= ':' . $drupal_base_url['port'];
277
      }
278
      $_SERVER['SERVER_PORT'] = $drupal_base_url['port'];
279
280
      if (array_key_exists('path', $drupal_base_url)) {
281
        $_SERVER['PHP_SELF'] = $drupal_base_url['path'] . '/index.php';
282
      }
283
      else {
284
        $_SERVER['PHP_SELF'] = '/index.php';
285
      }
286
    }
287
    else {
288
      $_SERVER['HTTP_HOST'] = 'default';
289
      $_SERVER['PHP_SELF'] = '/index.php';
290
    }
291
292
    $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
293
    $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
294
    $_SERVER['REQUEST_METHOD']  = NULL;
295
296
    $_SERVER['SERVER_SOFTWARE'] = NULL;
297
    $_SERVER['HTTP_USER_AGENT'] = NULL;
298
299
    $conf_path = DrupalKernel::findSitePath(Request::createFromGlobals());
300
    $conf_file = $this->drupalRoot . "/$conf_path/settings.php";
301
    if (!file_exists($conf_file)) {
302
      throw new BootstrapException(sprintf('Could not find a Drupal settings.php file at "%s"', $conf_file));
303
    }
304
  }
305
306
  /**
307
   * {@inheritdoc}
308
   */
309
  public function termCreate(\stdClass $term) {
310
    $term->vid = $term->vocabulary_machine_name;
311
    $this->expandEntityFields('taxonomy_term', $term);
312
    $entity = Term::create((array) $term);
313
    $entity->save();
314
315
    $term->tid = $entity->id();
316
    return $term;
317
  }
318
319
  /**
320
   * {@inheritdoc}
321
   */
322
  public function termDelete(\stdClass $term) {
323
    $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...
324
    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...
325
      $term->delete();
326
    }
327
  }
328
329
  /**
330
   * {@inheritdoc}
331
   */
332
  public function getModuleList() {
333
    return array_keys(\Drupal::moduleHandler()->getModuleList());
334
  }
335
336
  /**
337
   * {@inheritdoc}
338
   */
339
  public function getExtensionPathList() {
340
    $paths = array();
341
342
    // Get enabled modules.
343
    foreach (\Drupal::moduleHandler()->getModuleList() as $module) {
344
      $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . $module->getPath();
345
    }
346
347
    return $paths;
348
  }
349
350
  /**
351
   * {@inheritdoc}
352
   */
353
  public function getEntityFieldTypes($entity_type) {
354
    $return = array();
355
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
356
    foreach ($fields as $field_name => $field) {
357
      if ($this->isField($entity_type, $field_name)) {
358
        $return[$field_name] = $field->getType();
359
      }
360
    }
361
    return $return;
362
  }
363
364
  /**
365
   * {@inheritdoc}
366
   */
367
  public function isField($entity_type, $field_name) {
368
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
369
    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...
370
  }
371
372
  /**
373
   * {@inheritdoc}
374
   */
375
  public function languageCreate(\stdClass $language) {
376
    $langcode = $language->langcode;
377
378
    // Enable a language only if it has not been enabled already.
379
    if (!ConfigurableLanguage::load($langcode)) {
380
      $created_language = ConfigurableLanguage::createFromLangcode($language->langcode);
381
      if (!$created_language) {
382
        throw new InvalidArgumentException("There is no predefined language with langcode '{$langcode}'.");
383
      }
384
      $created_language->save();
385
      return $language;
386
    }
387
388
    return FALSE;
389
  }
390
391
  /**
392
   * {@inheritdoc}
393
   */
394
  public function languageDelete(\stdClass $language) {
395
    $configurable_language = ConfigurableLanguage::load($language->langcode);
396
    $configurable_language->delete();
397
  }
398
399
  /**
400
   * {@inheritdoc}
401
   */
402
  public function clearStaticCaches() {
403
    drupal_static_reset();
404
    \Drupal::service('cache_tags.invalidator')->resetChecksums();
405
  }
406
407
  /**
408
   * {@inheritdoc}
409
   */
410
  public function configGet($name, $key = '') {
411
    return \Drupal::config($name)->get($key);
412
  }
413
414
  /**
415
   * {@inheritdoc}
416
   */
417
  public function configSet($name, $key, $value) {
418
    \Drupal::configFactory()->getEditable($name)
419
      ->set($key, $value)
420
      ->save();
421
  }
422
423
}
424