3 namespace Drupal\Driver\Cores;
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;
18 class Drupal8 extends AbstractCore {
23 public function bootstrap() {
24 // Validate, and prepare environment for Drupal bootstrap.
25 if (!defined('DRUPAL_ROOT')) {
26 define('DRUPAL_ROOT', $this->drupalRoot);
31 $autoloader = require DRUPAL_ROOT . '/autoload.php';
32 require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
33 $this->validateDrupalSite();
35 $request = Request::createFromGlobals();
36 $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
38 $kernel->prepareLegacyRequest($request);
40 // Initialise an anonymous session. required for the bootstrap.
41 \Drupal::service('session_manager')->start();
47 public function clearCache() {
48 // Need to change into the Drupal root directory or the registry explodes.
49 drupal_flush_all_caches();
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'.");
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.");
64 // Default status to 1 if not set.
65 if (!isset($node->status)) {
68 // If 'author' is set, remap it to 'uid'.
69 if (isset($node->author)) {
70 $user = user_load_by_name($node->author);
72 $node->uid = $user->id();
75 $this->expandEntityFields('node', $node);
76 $entity = entity_create('node', (array) $node);
79 $node->nid = $entity->id();
87 public function nodeDelete($node) {
88 $node = $node instanceof NodeInterface ? $node : Node::load($node->nid);
89 if ($node instanceof NodeInterface) {
97 public function runCron() {
98 return \Drupal::service('cron')->run();
104 public function userCreate(\stdClass $user) {
105 $this->validateDrupalSite();
107 // Default status to TRUE if not explicitly creating a blocked user.
108 if (!isset($user->status)) {
112 // Clone user object, otherwise user_save() changes the password to the
114 $this->expandEntityFields('user', $user);
115 $account = entity_create('user', (array) $user);
119 $user->uid = $account->id();
125 public function roleCreate(array $permissions) {
126 // Generate a random, lowercase machine name.
127 $rid = strtolower($this->random->name(8, TRUE));
129 // Generate a random label.
130 $name = trim($this->random->name(8, TRUE));
132 // Convert labels to machine names.
133 $this->convertPermissions($permissions);
135 // Check the all the permissions strings are valid.
136 $this->checkPermissions($permissions);
139 $role = entity_create('user_role', array(
143 $result = $role->save();
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);
153 throw new \RuntimeException(sprintf('Failed to create a role with "%s" permission(s).', implode(', ', $permissions)));
159 public function roleDelete($role_name) {
160 $role = user_role_load($role_name);
163 throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
172 public function processBatch() {
173 $this->validateDrupalSite();
174 $batch =& batch_get();
175 $batch['progressive'] = FALSE;
180 * Retrieve all permissions.
183 * Array of all defined permissions.
185 protected function getAllPermissions() {
186 $permissions = &drupal_static(__FUNCTION__);
188 if (!isset($permissions)) {
189 $permissions = \Drupal::service('user.permissions')->getPermissions();
196 * Convert any permission labels to machine name.
198 * @param array &$permissions
199 * Array of permission names.
201 protected function convertPermissions(array &$permissions) {
202 $all_permissions = $this->getAllPermissions();
204 foreach ($all_permissions as $name => $definition) {
205 $key = array_search($definition['title'], $permissions);
206 if (FALSE !== $key) {
207 $permissions[$key] = $name;
213 * Check to make sure that the array of permissions are valid.
215 * @param array $permissions
216 * Permissions to check.
218 protected function checkPermissions(array &$permissions) {
219 $available = array_keys($this->getAllPermissions());
221 foreach ($permissions as $permission) {
222 if (!in_array($permission, $available)) {
223 throw new \RuntimeException(sprintf('Invalid permission "%s".', $permission));
231 public function userDelete(\stdClass $user) {
232 user_cancel(array(), $user->uid, 'user_cancel_delete');
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);
246 if (!$role = user_role_load($role_name)) {
247 throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
250 $account = \user_load($user->uid);
251 $account->addRole($role->id());
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);
268 $drupal_base_url += array(
273 $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
275 if ($drupal_base_url['port']) {
276 $_SERVER['HTTP_HOST'] .= ':' . $drupal_base_url['port'];
278 $_SERVER['SERVER_PORT'] = $drupal_base_url['port'];
280 if (array_key_exists('path', $drupal_base_url)) {
281 $_SERVER['PHP_SELF'] = $drupal_base_url['path'] . '/index.php';
284 $_SERVER['PHP_SELF'] = '/index.php';
288 $_SERVER['HTTP_HOST'] = 'default';
289 $_SERVER['PHP_SELF'] = '/index.php';
292 $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
293 $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
294 $_SERVER['REQUEST_METHOD'] = NULL;
296 $_SERVER['SERVER_SOFTWARE'] = NULL;
297 $_SERVER['HTTP_USER_AGENT'] = NULL;
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));
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);
315 $term->tid = $entity->id();
322 public function termDelete(\stdClass $term) {
323 $term = $term instanceof TermInterface ? $term : Term::load($term->tid);
324 if ($term instanceof TermInterface) {
332 public function getModuleList() {
333 return array_keys(\Drupal::moduleHandler()->getModuleList());
339 public function getExtensionPathList() {
342 // Get enabled modules.
343 foreach (\Drupal::moduleHandler()->getModuleList() as $module) {
344 $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . $module->getPath();
353 public function getEntityFieldTypes($entity_type) {
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();
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);
375 public function languageCreate(\stdClass $language) {
376 $langcode = $language->langcode;
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}'.");
384 $created_language->save();
394 public function languageDelete(\stdClass $language) {
395 $configurable_language = ConfigurableLanguage::load($language->langcode);
396 $configurable_language->delete();
402 public function clearStaticCaches() {
403 drupal_static_reset();
404 \Drupal::service('cache_tags.invalidator')->resetChecksums();
410 public function configGet($name, $key = '') {
411 return \Drupal::config($name)->get($key);
417 public function configSet($name, $key, $value) {
418 \Drupal::configFactory()->getEditable($name)