Completed
Pull Request — master (#114)
by
unknown
05:04
created

Drupal8::isBaseField()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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