Completed
Pull Request — master (#76)
by
unknown
02:19
created

Drupal8::configGet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
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\field\Entity\FieldStorageConfig;
13
use Drupal\language\Entity\ConfigurableLanguage;
14
use Drupal\node\Entity\Node;
15
use Drupal\node\NodeInterface;
16
use Drupal\taxonomy\Entity\Term;
17
use Drupal\taxonomy\TermInterface;
18
use Symfony\Component\HttpFoundation\Request;
19
20
/**
21
 * Drupal 8 core.
22
 */
23
class Drupal8 extends AbstractCore {
24
25
  /**
26
   * {@inheritdoc}
27
   */
28
  public function bootstrap() {
29
    // Validate, and prepare environment for Drupal bootstrap.
30
    if (!defined('DRUPAL_ROOT')) {
31
      define('DRUPAL_ROOT', $this->drupalRoot);
32
    }
33
34
    // Bootstrap Drupal.
35
    chdir(DRUPAL_ROOT);
36
    $autoloader = require DRUPAL_ROOT . '/autoload.php';
37
    require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
38
    $this->validateDrupalSite();
39
40
    $request = Request::createFromGlobals();
41
    $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
42
    $kernel->boot();
43
    $kernel->prepareLegacyRequest($request);
44
45
    // Initialise an anonymous session. required for the bootstrap.
46
    \Drupal::service('session_manager')->start();
47
  }
48
49
  /**
50
   * {@inheritdoc}
51
   */
52
  public function clearCache() {
53
    // Need to change into the Drupal root directory or the registry explodes.
54
    drupal_flush_all_caches();
55
  }
56
57
  /**
58
   * {@inheritdoc}
59
   */
60
  public function nodeCreate($node) {
61
    // Default status to 1 if not set.
62
    if (!isset($node->status)) {
63
      $node->status = 1;
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 = entity_create('node', (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
  }
302
303
  /**
304
   * {@inheritdoc}
305
   */
306
  public function termCreate(\stdClass $term) {
307
    $term->vid = $term->vocabulary_machine_name;
308
    $this->expandEntityFields('taxonomy_term', $term);
309
    $entity = Term::create((array) $term);
310
    $entity->save();
311
312
    $term->tid = $entity->id();
313
    return $term;
314
  }
315
316
  /**
317
   * {@inheritdoc}
318
   */
319
  public function termDelete(\stdClass $term) {
320
    $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...
321
    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...
322
      $term->delete();
323
    }
324
  }
325
326
  /**
327
   * {@inheritdoc}
328
   */
329
  public function getModuleList() {
330
    return array_keys(\Drupal::moduleHandler()->getModuleList());
331
  }
332
333
  /**
334
   * {@inheritdoc}
335
   */
336
  public function getExtensionPathList() {
337
    $paths = array();
338
339
    // Get enabled modules.
340
    foreach (\Drupal::moduleHandler()->getModuleList() as $module) {
341
      $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . $module->getPath();
342
    }
343
344
    return $paths;
345
  }
346
347
  /**
348
   * {@inheritdoc}
349
   */
350
  public function getEntityFieldTypes($entity_type) {
351
    $return = array();
352
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
353
    foreach ($fields as $field_name => $field) {
354
      if ($this->isField($entity_type, $field_name)) {
355
        $return[$field_name] = $field->getType();
356
      }
357
    }
358
    return $return;
359
  }
360
361
  /**
362
   * {@inheritdoc}
363
   */
364
  public function isField($entity_type, $field_name) {
365
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
366
    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...
367
  }
368
369
  /**
370
   * {@inheritdoc}
371
   */
372
  public function languageCreate(\stdClass $language) {
373
    $langcode = $language->langcode;
374
375
    // Enable a language only if it has not been enabled already.
376
    if (!ConfigurableLanguage::load($langcode)) {
377
      $created_language = ConfigurableLanguage::createFromLangcode($language->langcode);
378
      if (!$created_language) {
379
        throw new InvalidArgumentException("There is no predefined language with langcode '{$langcode}'.");
380
      }
381
      $created_language->save();
382
      return $language;
383
    }
384
385
    return FALSE;
386
  }
387
388
  /**
389
   * {@inheritdoc}
390
   */
391
  public function languageDelete(\stdClass $language) {
392
    $configurable_language = ConfigurableLanguage::load($language->langcode);
393
    $configurable_language->delete();
394
  }
395
396
  /**
397
   * {@inheritdoc}
398
   */
399
  public function clearStaticCaches() {
400
    drupal_static_reset();
401
    \Drupal::service('cache_tags.invalidator')->resetChecksums();
402
  }
403
404
  /**
405
   * {@inheritdoc}
406
   */
407
  public function configGet($name, $key = '') {
408
    return \Drupal::config($name)->get($key);
409
  }
410
411
  /**
412
   * {@inheritdoc}
413
   */
414
  public function configSet($name, $key, $value) {
415
    \Drupal::configFactory()->getEditable($name)
416
      ->set($key, $value)
417
      ->save();
418
  }
419
420
}
421