Completed
Pull Request — master (#157)
by
unknown
01:35
created

Drupal8::convertPermissions()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
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\Driver\Wrapper\Entity\DriverEntityWrapperInterface;
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\EntityInterface;
13
use Drupal\taxonomy\Entity\Term;
14
use Drupal\taxonomy\TermInterface;
15
use Symfony\Component\HttpFoundation\Request;
16
use Drupal\Driver\Plugin\DriverFieldPluginManager;
17
use Drupal\Driver\Wrapper\Field\DriverFieldDrupal8;
18
use Drupal\Driver\Wrapper\Entity\DriverEntityDrupal8;
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
    $entity = $this->getNewEntity('node');
62
    $entity->setFields((array) $node);
63
    $entity->save();
64
    $node->nid = $entity->id();
65
    return $node;
66
  }
67
68
  /**
69
   * {@inheritdoc}
70
   */
71
  public function nodeDelete($node) {
72
    $nid = $node instanceof NodeInterface ? $node->id() : $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...
73
    $entity = $this->getNewEntity('node');
74
    $entity->load($nid);
75
    $entity->delete();
76
  }
77
78
  /**
79
   * {@inheritdoc}
80
   */
81
  public function runCron() {
82
    return \Drupal::service('cron')->run();
83
  }
84
85
  /**
86
   * {@inheritdoc}
87
   */
88
  public function userCreate(\stdClass $user) {
89
    // @todo determine if this needs to be here. It disrupts the new kernel
90
    // tests.
91
    $this->validateDrupalSite();
92
93
    $entity = $this->getNewEntity('user');
94
    $entity->setFields((array) $user);
95
    $entity->save();
96
    $user->uid = $entity->id();
97
    return $user;
98
  }
99
100
  /**
101
   * {@inheritdoc}
102
   */
103
  public function roleCreate(array $permissions) {
104
    // Generate a random machine name & label.
105
    $id = strtolower($this->random->name(8, TRUE));
106
    $label = trim($this->random->name(8, TRUE));
107
108
    $entity = $this->getNewEntity('role');
109
    $entity->set('id', $id);
110
    $entity->set('label', $label);
111
    $entity->grantPermissions($permissions);
0 ignored issues
show
Documentation Bug introduced by
The method grantPermissions does not exist on object<Drupal\Driver\Wra...ty\DriverEntityDrupal8>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
112
    $entity->save();
113
    return $entity->id();
114
  }
115
116
  /**
117
   * {@inheritdoc}
118
   */
119
  public function roleDelete($role_name) {
120
    $role = $this->getNewEntity('role');
121
    $role->load($role_name);
122
    $role->delete();
123
  }
124
125
  /**
126
   * {@inheritdoc}
127
   */
128
  public function processBatch() {
129
    $this->validateDrupalSite();
130
    $batch =& batch_get();
131
    $batch['progressive'] = FALSE;
132
    batch_process();
133
  }
134
135
  /**
136
   * {@inheritdoc}
137
   */
138
  public function userDelete(\stdClass $user) {
139
    // Not using user_cancel here leads to an error when batch_process()
140
    // is subsequently called.
141
    user_cancel(array(), $user->uid, 'user_cancel_delete');
142
    //$entity = $this->getNewEntity('user');
143
    //$entity->load($user->uid);
144
    //$entity->delete();
145
  }
146
147
  /**
148
   * {@inheritdoc}
149
   */
150
  public function userAddRole(\stdClass $user, $role_name) {
151
    $uid = $user->uid;
152
    $user = $this->getNewEntity('user');
153
    $user->load($uid);
154
    $user->addRole($role_name);
0 ignored issues
show
Documentation Bug introduced by
The method addRole does not exist on object<Drupal\Driver\Wra...ty\DriverEntityDrupal8>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
155
    $user->save();
156
  }
157
158
  /**
159
   * {@inheritdoc}
160
   */
161
  public function validateDrupalSite() {
162
    if ('default' !== $this->uri) {
163
      // Fake the necessary HTTP headers that Drupal needs:
164
      $drupal_base_url = parse_url($this->uri);
165
      // If there's no url scheme set, add http:// and re-parse the url
166
      // so the host and path values are set accurately.
167
      if (!array_key_exists('scheme', $drupal_base_url)) {
168
        $drupal_base_url = parse_url($this->uri);
169
      }
170
      // Fill in defaults.
171
      $drupal_base_url += array(
172
        'path' => NULL,
173
        'host' => NULL,
174
        'port' => NULL,
175
      );
176
      $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
177
178
      if ($drupal_base_url['port']) {
179
        $_SERVER['HTTP_HOST'] .= ':' . $drupal_base_url['port'];
180
      }
181
      $_SERVER['SERVER_PORT'] = $drupal_base_url['port'];
182
183
      if (array_key_exists('path', $drupal_base_url)) {
184
        $_SERVER['PHP_SELF'] = $drupal_base_url['path'] . '/index.php';
185
      }
186
      else {
187
        $_SERVER['PHP_SELF'] = '/index.php';
188
      }
189
    }
190
    else {
191
      $_SERVER['HTTP_HOST'] = 'default';
192
      $_SERVER['PHP_SELF'] = '/index.php';
193
    }
194
195
    $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
196
    $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
197
    $_SERVER['REQUEST_METHOD'] = NULL;
198
199
    $_SERVER['SERVER_SOFTWARE'] = NULL;
200
    $_SERVER['HTTP_USER_AGENT'] = NULL;
201
202
    $conf_path = DrupalKernel::findSitePath(Request::createFromGlobals());
203
    $conf_file = $this->drupalRoot . "/$conf_path/settings.php";
204
    if (!file_exists($conf_file)) {
205
      throw new BootstrapException(sprintf('Could not find a Drupal settings.php file at "%s"', $conf_file));
206
    }
207
    $drushrc_file = $this->drupalRoot . "/$conf_path/drushrc.php";
208
    if (file_exists($drushrc_file)) {
209
      require_once $drushrc_file;
210
    }
211
  }
212
213
  /**
214
   * {@inheritdoc}
215
   */
216
  public function termCreate(\stdClass $term) {
217
    $entity = $this->getNewEntity('taxonomy_term');
218
    $entity->setFields((array) $term);
219
    $entity->save();
220
    $term->tid = $entity->id();
221
    return $term;
222
  }
223
224
  /**
225
   * {@inheritdoc}
226
   */
227
  public function termDelete(\stdClass $term) {
228
    $entity = $this->getNewEntity('taxonomy_term');
229
    $entity->load($term->tid);
230
    $entity->delete();
231
  }
232
233
  /**
234
   * {@inheritdoc}
235
   */
236
  public function getModuleList() {
237
    return array_keys(\Drupal::moduleHandler()->getModuleList());
238
  }
239
240
  /**
241
   * {@inheritdoc}
242
   */
243
  public function getExtensionPathList() {
244
    $paths = array();
245
246
    // Get enabled modules.
247
    foreach (\Drupal::moduleHandler()->getModuleList() as $module) {
248
      $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . $module->getPath();
249
    }
250
251
    return $paths;
252
  }
253
254
  /**
255
   * {@inheritdoc}
256
   */
257
  public function getEntityFieldTypes($entity_type) {
258
    $return = array();
259
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
260
    foreach ($fields as $field_name => $field) {
261
      if ($this->isField($entity_type, $field_name)) {
262
        $return[$field_name] = $field->getType();
263
      }
264
    }
265
    return $return;
266
  }
267
268
  /**
269
   * Get a new driver entity wrapper.
270
   *
271
   * @return \Drupal\Driver\Wrapper\Entity\DriverEntityWrapperInterface;
0 ignored issues
show
Documentation introduced by
The doc-type \Drupal\Driver\Wrapper\E...EntityWrapperInterface; could not be parsed: Expected "|" or "end of type", but got ";" at position 58. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
272
   */
273
  public function getNewEntity($type, $bundle = NULL) {
274
    $entity = new DriverEntityDrupal8($type, $bundle);
275
    return $entity;
276
  }
277
278
  /**
279
   * {@inheritdoc}
280
   */
281
  public function isField($entity_type, $field_name) {
282
    $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
283
    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...
284
  }
285
286
  /**
287
   * {@inheritdoc}
288
   */
289
  public function languageCreate(\stdClass $language) {
290
    $langcode = $language->langcode;
291
292
    // Enable a language only if it has not been enabled already.
293
    if (!ConfigurableLanguage::load($langcode)) {
294
      $entity = $this->getNewEntity('configurable_language');
295
      $entity->set('id', $langcode);
296
      $entity->set('label', $langcode);
297
      $entity->save();
298
      return $language;
299
    }
300
301
    return FALSE;
302
  }
303
304
  /**
305
   * {@inheritdoc}
306
   */
307
  public function languageDelete(\stdClass $language) {
308
    $configurable_language = ConfigurableLanguage::load($language->langcode);
309
    $configurable_language->delete();
310
  }
311
312
  /**
313
   * {@inheritdoc}
314
   */
315
  public function clearStaticCaches() {
316
    drupal_static_reset();
317
    \Drupal::service('cache_tags.invalidator')->resetChecksums();
318
  }
319
320
  /**
321
   * {@inheritdoc}
322
   */
323
  public function configGet($name, $key = '') {
324
    return \Drupal::config($name)->get($key);
325
  }
326
327
  /**
328
   * {@inheritdoc}
329
   */
330
  public function configSet($name, $key, $value) {
331
    \Drupal::configFactory()->getEditable($name)
332
      ->set($key, $value)
333
      ->save();
334
  }
335
336
  /**
337
   * {@inheritdoc}
338
   */
339
  public function entityCreate($entity_type, $entity) {
340
    $entityWrapped = $this->getNewEntity($entity_type);
341
    $entityWrapped->setFields((array) $entity);
342
    $entityWrapped->save();
343
    $entity->id = $entityWrapped->id();
344
    return $entity;
345
  }
346
347
  /**
348
   * {@inheritdoc}
349
   */
350
  public function entityDelete($entity_type, $entity) {
351
    $eid = $entity instanceof EntityInterface ? $entity->id() : $entity->id;
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Entity\EntityInterface 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...
352
    $entity = $this->getNewEntity($entity_type);
353
    $entity->load($eid);
354
    $entity->delete();
355
  }
356
357
}
358