/**
  * Gets the global context repository.
  *
  * @return \Drupal\Core\Plugin\Context\ContextRepositoryInterface
  *   The context repository.
  */
 public function getGlobalContextRepository()
 {
     if (empty($this->contextRepository)) {
         $this->contextRepository = \Drupal::service('context.repository');
     }
     return $this->contextRepository;
 }
 /**
  * {@inheritdoc}
  */
 public function nextMail()
 {
     // Get the current mail spool row and update the internal pointer to the
     // next row.
     $return = each($this->mails);
     // If we're done, return false.
     if (!$return) {
         return FALSE;
     }
     $spool_data = $return['value'];
     // Store this spool row as processed.
     $this->processed[$spool_data->msid] = $spool_data;
     $entity = entity_load($spool_data->entity_type, $spool_data->entity_id);
     if (!$entity) {
         // If the entity load failed, set the processed status done and proceed with
         // the next mail.
         $this->processed[$spool_data->msid]->result = array('status' => SpoolStorageInterface::STATUS_DONE, 'error' => TRUE);
         return $this->nextMail();
     }
     if ($spool_data->data) {
         $subscriber = $spool_data->data;
     } else {
         $subscriber = simplenews_subscriber_load_by_mail($spool_data->mail);
     }
     if (!$subscriber) {
         // If loading the subscriber failed, set the processed status done and
         // proceed with the next mail.
         $this->processed[$spool_data->msid]->result = array('status' => SpoolStorageInterface::STATUS_DONE, 'error' => TRUE);
         return $this->nextMail();
     }
     $mail = new MailEntity($entity, $subscriber, \Drupal::service('simplenews.mail_cache'));
     // Set the langcode langcode.
     $this->processed[$spool_data->msid]->langcode = $mail->getEntity()->language()->getId();
     return $mail;
 }
Example #3
0
 /**
  * Tests the "popular content" block.
  */
 function testPopularContentBlock()
 {
     // Clear the block cache to load the Statistics module's block definitions.
     $this->container->get('plugin.manager.block')->clearCachedDefinitions();
     // Visit a node to have something show up in the block.
     $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->blockingUser->id()));
     $this->drupalGet('node/' . $node->id());
     // Manually calling statistics.php, simulating ajax behavior.
     $nid = $node->id();
     $post = http_build_query(array('nid' => $nid));
     $headers = array('Content-Type' => 'application/x-www-form-urlencoded');
     global $base_url;
     $stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
     $client = \Drupal::service('http_client_factory')->fromOptions(['config/curl' => [CURLOPT_TIMEOUT => 10]]);
     $client->post($stats_path, array('headers' => $headers, 'body' => $post));
     // Configure and save the block.
     $this->drupalPlaceBlock('statistics_popular_block', array('label' => 'Popular content', 'top_day_num' => 3, 'top_all_num' => 3, 'top_last_num' => 3));
     // Get some page and check if the block is displayed.
     $this->drupalGet('user');
     $this->assertText('Popular content', 'Found the popular content block.');
     $this->assertText("Today's", "Found today's popular content.");
     $this->assertText('All time', 'Found the all time popular content.');
     $this->assertText('Last viewed', 'Found the last viewed popular content.');
     // statistics.module doesn't use node entities, prevent the node language
     // from being added to the options.
     $this->assertRaw(\Drupal::l($node->label(), $node->urlInfo('canonical', ['language' => NULL])), 'Found link to visited node.');
 }
 /**
  * Gets the logger for a specific channel.
  *
  * @param string $channel
  *   The name of the channel. Can be any string, but the general practice is
  *   to use the name of the subsystem calling this.
  *
  * @return \Psr\Log\LoggerInterface
  *   The logger for the given channel.
  *
  * @todo Require the use of injected services:
  *   https://www.drupal.org/node/2733703
  */
 protected function getLogger($channel)
 {
     if (!$this->loggerFactory) {
         $this->loggerFactory = \Drupal::service('logger.factory');
     }
     return $this->loggerFactory->get($channel);
 }
 /**
  * Confirm the config defaults show on the translations page.
  */
 public function testConfigTranslationsExist()
 {
     // Ensure the config shows on the admin form.
     $this->drupalGet('admin/config/regional/config-translation');
     $this->assertResponse(200);
     $this->assertText(t('Metatag defaults'));
     // Load the main metatag_defaults config translation page.
     $this->drupalGet('admin/config/regional/config-translation/metatag_defaults');
     $this->assertResponse(200);
     // @todo Update this to confirm the H1 is loaded.
     $this->assertRaw(t('Metatag defaults'));
     // Load all of the Metatag defaults.
     $defaults = \Drupal::configFactory()->listAll('metatag.metatag_defaults');
     /** @var \Drupal\Core\Config\ConfigManagerInterface $config_manager */
     $config_manager = \Drupal::service('config.manager');
     // Confirm each of the configs is available on the translation form.
     foreach ($defaults as $config_name) {
         if ($config_entity = $config_manager->loadConfigEntityByName($config_name)) {
             $this->assertText($config_entity->label());
         }
     }
     // Confirm that each config translation page can be loaded.
     foreach ($defaults as $config_name) {
         if ($config_entity = $config_manager->loadConfigEntityByName($config_name)) {
             $this->drupalGet('admin/config/search/metatag/' . $config_entity->id() . '/translate');
             $this->assertResponse(200);
         } else {
             $this->error('Unable to load a Metatag default config: ' . $config_name);
         }
     }
 }
 /**
  * Tests that local actions/tasks are being converted into blocks.
  */
 public function testUpdateHookN()
 {
     $this->runUpdates();
     /** @var \Drupal\block\BlockInterface $block_storage */
     $block_storage = \Drupal::entityManager()->getStorage('block');
     /* @var \Drupal\block\BlockInterface[] $help_blocks */
     $help_blocks = $block_storage->loadByProperties(['theme' => 'bartik', 'region' => 'help']);
     $this->assertRaw('Because your site has custom theme(s) installed, we had to set local actions and tasks blocks into the content region. Please manually review the block configurations and remove the removed variables from your templates.');
     // Disable maintenance mode.
     // @todo Can be removed once maintenance mode is automatically turned off
     // after updates in https://www.drupal.org/node/2435135.
     \Drupal::state()->set('system.maintenance_mode', FALSE);
     // We finished updating so we can log in the user now.
     $this->drupalLogin($this->rootUser);
     $page = Node::create(['type' => 'page', 'title' => 'Page node']);
     $page->save();
     // Ensures that blocks inside help region has been moved to content region.
     foreach ($help_blocks as $block) {
         $new_block = $block_storage->load($block->id());
         $this->assertEqual($new_block->getRegion(), 'content');
     }
     // Local tasks are visible on the node page.
     $this->drupalGet('node/' . $page->id());
     $this->assertText(t('Edit'));
     // Local actions are visible on the content listing page.
     $this->drupalGet('admin/content');
     $action_link = $this->cssSelect('.action-links');
     $this->assertTrue($action_link);
     $this->drupalGet('admin/structure/block/list/seven');
     /** @var \Drupal\Core\Config\StorageInterface $config_storage */
     $config_storage = \Drupal::service('config.storage');
     $this->assertTrue($config_storage->exists('block.block.test_theme_local_tasks'), 'Local task block has been created for the custom theme.');
     $this->assertTrue($config_storage->exists('block.block.test_theme_local_actions'), 'Local action block has been created for the custom theme.');
 }
Example #7
0
 /**
  * Encapsulates the creation of the action's LazyPluginCollection.
  *
  * @return \Drupal\Component\Plugin\LazyPluginCollection
  *   The action's plugin collection.
  */
 protected function getPluginCollection()
 {
     if (!$this->pluginCollection) {
         $this->pluginCollection = new ActionPluginCollection(\Drupal::service('plugin.manager.action'), $this->plugin, $this->configuration);
     }
     return $this->pluginCollection;
 }
 /**
  * Tests that the correct MigrateCckField plugins are used.
  */
 public function testPluginSelection()
 {
     $plugin_manager = \Drupal::service('plugin.manager.migrate.cckfield');
     $this->assertIdentical('Drupal\\file\\Plugin\\migrate\\cckfield\\d6\\FileField', get_class($plugin_manager->createInstance('filefield', ['core' => 6])));
     try {
         // If this test passes, createInstance will raise a
         // PluginNotFoundException and we'll never reach fail().
         $plugin_manager->createInstance('filefield', ['core' => 7]);
         $this->fail('Expected Drupal\\Component\\Plugin\\Exception\\PluginNotFoundException.');
     } catch (PluginNotFoundException $e) {
         $this->assertIdentical($e->getMessage(), "Plugin ID 'filefield' was not found.");
     }
     $this->assertIdentical('Drupal\\file\\Plugin\\migrate\\cckfield\\d7\\ImageField', get_class($plugin_manager->createInstance('image', ['core' => 7])));
     $this->assertIdentical('Drupal\\file\\Plugin\\migrate\\cckfield\\d7\\FileField', get_class($plugin_manager->createInstance('file', ['core' => 7])));
     $this->assertIdentical('Drupal\\migrate_cckfield_plugin_manager_test\\Plugin\\migrate\\cckfield\\D6FileField', get_class($plugin_manager->createInstance('file', ['core' => 6])));
     $this->assertIdentical('Drupal\\text\\Plugin\\migrate\\cckfield\\TextField', get_class($plugin_manager->createInstance('text', ['core' => 6])));
     $this->assertIdentical('Drupal\\text\\Plugin\\migrate\\cckfield\\TextField', get_class($plugin_manager->createInstance('text', ['core' => 7])));
     // Test fallback when no core version is specified.
     $this->assertIdentical('Drupal\\migrate_cckfield_plugin_manager_test\\Plugin\\migrate\\cckfield\\D6NoCoreVersionSpecified', get_class($plugin_manager->createInstance('d6_no_core_version_specified', ['core' => 6])));
     try {
         // If this test passes, createInstance will raise a
         // PluginNotFoundException and we'll never reach fail().
         $plugin_manager->createInstance('d6_no_core_version_specified', ['core' => 7]);
         $this->fail('Expected Drupal\\Component\\Plugin\\Exception\\PluginNotFoundException.');
     } catch (PluginNotFoundException $e) {
         $this->assertIdentical($e->getMessage(), "Plugin ID 'd6_no_core_version_specified' was not found.");
     }
 }
 /**
  * Creates a node, then tests the tokens generated from it.
  */
 function testNodeTokenReplacement()
 {
     $url_options = array('absolute' => TRUE, 'language' => $this->interfaceLanguage);
     // Create a user and a node.
     $account = $this->createUser();
     /* @var $node \Drupal\node\NodeInterface */
     $node = entity_create('node', array('type' => 'article', 'tnid' => 0, 'uid' => $account->id(), 'title' => '<blink>Blinking Text</blink>', 'body' => array(array('value' => $this->randomMachineName(32), 'summary' => $this->randomMachineName(16), 'format' => 'plain_text'))));
     $node->save();
     // Generate and test sanitized tokens.
     $tests = array();
     $tests['[node:nid]'] = $node->id();
     $tests['[node:vid]'] = $node->getRevisionId();
     $tests['[node:type]'] = 'article';
     $tests['[node:type-name]'] = 'Article';
     $tests['[node:title]'] = SafeMarkup::checkPlain($node->getTitle());
     $tests['[node:body]'] = $node->body->processed;
     $tests['[node:summary]'] = $node->body->summary_processed;
     $tests['[node:langcode]'] = SafeMarkup::checkPlain($node->language()->getId());
     $tests['[node:url]'] = $node->url('canonical', $url_options);
     $tests['[node:edit-url]'] = $node->url('edit-form', $url_options);
     $tests['[node:author]'] = SafeMarkup::checkPlain($account->getUsername());
     $tests['[node:author:uid]'] = $node->getOwnerId();
     $tests['[node:author:name]'] = SafeMarkup::checkPlain($account->getUsername());
     $tests['[node:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getCreatedTime(), array('langcode' => $this->interfaceLanguage->getId()));
     $tests['[node:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getChangedTime(), array('langcode' => $this->interfaceLanguage->getId()));
     // Test to make sure that we generated something for each token.
     $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
     foreach ($tests as $input => $expected) {
         $output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->getId()));
         $this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced.', array('%token' => $input)));
     }
     // Generate and test unsanitized tokens.
     $tests['[node:title]'] = $node->getTitle();
     $tests['[node:body]'] = $node->body->value;
     $tests['[node:summary]'] = $node->body->summary;
     $tests['[node:langcode]'] = $node->language()->getId();
     $tests['[node:author:name]'] = $account->getUsername();
     foreach ($tests as $input => $expected) {
         $output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->getId(), 'sanitize' => FALSE));
         $this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced.', array('%token' => $input)));
     }
     // Repeat for a node without a summary.
     $node = entity_create('node', array('type' => 'article', 'uid' => $account->id(), 'title' => '<blink>Blinking Text</blink>', 'body' => array(array('value' => $this->randomMachineName(32), 'format' => 'plain_text'))));
     $node->save();
     // Generate and test sanitized token - use full body as expected value.
     $tests = array();
     $tests['[node:summary]'] = $node->body->processed;
     // Test to make sure that we generated something for each token.
     $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated for node without a summary.');
     foreach ($tests as $input => $expected) {
         $output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->interfaceLanguage));
         $this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced for node without a summary.', array('%token' => $input)));
     }
     // Generate and test unsanitized tokens.
     $tests['[node:summary]'] = $node->body->value;
     foreach ($tests as $input => $expected) {
         $output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->interfaceLanguage, 'sanitize' => FALSE));
         $this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced for node without a summary.', array('%token' => $input)));
     }
 }
 /**
  * Merges an info file into a package's info file.
  *
  * @param string $package_info
  *   The Yaml encoded package info.
  * @param string $info_file_uri
  *   The info file's URI.
  */
 protected function mergeInfoFile($package_info, $info_file_uri)
 {
     $package_info = Yaml::decode($package_info);
     /** @var \Drupal\Core\Extension\InfoParserInterface $existing_info */
     $existing_info = \Drupal::service('info_parser')->parse($info_file_uri);
     return Yaml::encode($this->featuresManager->mergeInfoArray($existing_info, $package_info));
 }
Example #11
0
 /**
  * {@inheritdoc}
  */
 public function render(ResultRow $values)
 {
     $value = parent::render($values);
     switch ($value) {
         case LocalTaskItemInterface::STATUS_PENDING:
             $label = t('Untranslated');
             $icon = drupal_get_path('module', 'tmgmt') . '/icons/ready.svg';
             break;
         case LocalTaskItemInterface::STATUS_COMPLETED:
             $label = t('Translated');
             $icon = drupal_get_path('module', 'tmgmt') . '/icons/gray-check.svg';
             break;
         case LocalTaskItemInterface::STATUS_REJECTED:
             $label = t('Rejected');
             $icon = drupal_get_path('module', 'tmgmt') . '/icons/rejected.svg';
             break;
         case LocalTaskItemInterface::STATUS_CLOSED:
             $label = t('Completed');
             $icon = 'core/misc/icons/73b355/check.svg';
             break;
         default:
             $label = t('Untranslated');
             $icon = drupal_get_path('module', 'tmgmt') . '/icons/ready.svg';
     }
     $element = ['#type' => 'inline_template', '#template' => '<img src="{{ icon }}" title="{{ label }}"><span></span></img>', '#context' => array('icon' => file_create_url($icon), 'label' => $label)];
     return \Drupal::service('renderer')->render($element);
 }
 /**
  * Tests user selection by roles.
  */
 function testUserSelectionByRole()
 {
     $field_definition = FieldConfig::loadByName('user', 'user', 'user_reference');
     $handler_settings = $field_definition->getSetting('handler_settings');
     $handler_settings['filter']['role'] = array($this->role1->id() => $this->role1->id(), $this->role2->id() => 0);
     $handler_settings['filter']['type'] = 'role';
     $field_definition->setSetting('handler_settings', $handler_settings);
     $field_definition->save();
     $user1 = $this->createUser(array('name' => 'aabb'));
     $user1->addRole($this->role1->id());
     $user1->save();
     $user2 = $this->createUser(array('name' => 'aabbb'));
     $user2->addRole($this->role1->id());
     $user2->save();
     $user3 = $this->createUser(array('name' => 'aabbbb'));
     $user3->addRole($this->role2->id());
     $user3->save();
     /** @var \Drupal\Core\Entity\EntityAutocompleteMatcher $autocomplete */
     $autocomplete = \Drupal::service('entity.autocomplete_matcher');
     $matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabb');
     $this->assertEqual(count($matches), 2);
     $users = array();
     foreach ($matches as $match) {
         $users[] = $match['label'];
     }
     $this->assertTrue(in_array($user1->label(), $users));
     $this->assertTrue(in_array($user2->label(), $users));
     $this->assertFalse(in_array($user3->label(), $users));
     $matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabbbb');
     $this->assertEqual(count($matches), 0, '');
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->typedConfig = \Drupal::service('config.typed');
     $this->blockManager = \Drupal::service('plugin.manager.block');
     $this->installEntitySchema('block_content');
 }
 /**
  * Checks views field access for a given entity type and field name.
  *
  * To use this method, set up an entity of type $entity_type_id, with field
  * $field_name. Create an entity instance that contains content $field_content
  * in that field.
  *
  * This method will check that a user with permission can see the content in a
  * view, and a user without access permission on that field cannot.
  *
  * @param string $entity_type_id
  *   The entity type ID.
  * @param string $field_name
  *   The field name.
  * @param string $field_content
  *   The expected field content.
  */
 protected function assertFieldAccess($entity_type_id, $field_name, $field_content)
 {
     \Drupal::state()->set('views_field_access_test-field', $field_name);
     $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
     $view_id = $this->randomMachineName();
     $data_table = $entity_type->getDataTable();
     // Use the data table as long as the field is not 'uuid'. This is the only
     // column that can only be obtained from the base table.
     $base_table = $data_table && $field_name !== 'uuid' ? $data_table : $entity_type->getBaseTable();
     $entity = View::create(['id' => $view_id, 'base_table' => $base_table, 'display' => ['default' => ['display_plugin' => 'default', 'id' => 'default', 'display_options' => ['fields' => [$field_name => ['table' => $base_table, 'field' => $field_name, 'id' => $field_name, 'plugin_id' => 'field']]]]]]);
     $entity->save();
     /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
     $account_switcher = \Drupal::service('account_switcher');
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = \Drupal::service('renderer');
     $account_switcher->switchTo($this->userWithAccess);
     $executable = Views::getView($view_id);
     $build = $executable->preview();
     $this->setRawContent($renderer->renderRoot($build));
     $this->assertText($field_content);
     $this->assertTrue(isset($executable->field[$field_name]));
     $account_switcher->switchTo($this->userWithoutAccess);
     $executable = Views::getView($view_id);
     $build = $executable->preview();
     $this->setRawContent($renderer->renderRoot($build));
     $this->assertNoText($field_content);
     $this->assertFalse(isset($executable->field[$field_name]));
     \Drupal::state()->delete('views_field_access_test-field');
 }
 /**
  * Checks that special characters are correctly escaped.
  *
  * @see https://www.drupal.org/node/1211668
  */
 function testFeedIconEscaping()
 {
     $variables = array('#theme' => 'feed_icon', '#url' => 'node', '#title' => '<>&"\'');
     $text = \Drupal::service('renderer')->renderRoot($variables);
     preg_match('/title="(.*?)"/', $text, $matches);
     $this->assertEqual($matches[1], 'Subscribe to &amp;&quot;&#039;', 'feed_icon template escapes reserved HTML characters.');
 }
 /**
  * Returns the URL generator service.
  *
  * @return \Drupal\Core\Routing\UrlGeneratorInterface
  *   The URL generator service.
  */
 protected function getUrlGenerator()
 {
     if (!$this->urlGenerator) {
         $this->urlGenerator = \Drupal::service('url_generator');
     }
     return $this->urlGenerator;
 }
Example #17
0
 /**
  * Creates an event type config.
  *
  * @param \Drupal\Core\Config\Entity\ConfigEntityInterface
  *   An entity type.
  *
  * @return \Drupal\rng\EventTypeInterface
  *   An event type config.
  */
 function createEventType(ConfigEntityInterface $entity_type)
 {
     $event_type = EventType::create(['label' => 'Event Type A', 'entity_type' => $entity_type->getEntityType()->getBundleOf(), 'bundle' => $entity_type->id(), 'mirror_operation_to_event_manage' => 'update']);
     $event_type->save();
     \Drupal::service('router.builder')->rebuildIfNeeded();
     return $event_type;
 }
 /**
  * {@inheritdoc}
  */
 public static function preDelete(EntityStorageInterface $storage, array $entities)
 {
     $registration_storage = \Drupal::entityManager()->getStorage('registration');
     /** @var \Drupal\rng\EventManagerInterface $event_manager */
     $event_manager = \Drupal::service('rng.event_manager');
     /** @var \Drupal\rng\RegistrationTypeInterface $registration_type */
     foreach ($entities as $registration_type) {
         // Remove entity field references in
         // $event->{EventManagerInterface::FIELD_REGISTRATION_TYPE}
         $event_types = $event_manager->getEventTypes();
         foreach ($event_types as $entity_type => $bundles) {
             $event_storage = \Drupal::entityManager()->getStorage($entity_type);
             foreach ($bundles as $bundle => $event_type) {
                 $bundle_key = \Drupal::entityManager()->getDefinition($entity_type)->getKey('bundle');
                 $ids = $event_storage->getQuery()->condition($bundle_key, $bundle)->condition(EventManagerInterface::FIELD_REGISTRATION_TYPE, $registration_type->id())->execute();
                 foreach ($ids as $id) {
                     $event_manager->getMeta($event_storage->load($id))->removeRegistrationType($registration_type->id())->save();
                 }
             }
         }
         // Remove registrations.
         $ids = $registration_storage->getQuery()->condition('type', $registration_type->id())->execute();
         $registrations = $registration_storage->loadMultiple($ids);
         $registration_storage->delete($registrations);
     }
     parent::preDelete($storage, $entities);
 }
 /**
  * Tests the calculateDependencies method.
  */
 public function testCalculateDependencies()
 {
     $comment_type = entity_create('comment_type', array('id' => 'comment', 'label' => 'Comment settings', 'description' => 'Comment settings', 'target_entity_type_id' => 'node'));
     $comment_type->save();
     $content_type = entity_create('node_type', array('type' => $this->randomMachineName(), 'name' => $this->randomString()));
     $content_type->save();
     $field_storage = entity_create('field_storage_config', array('field_name' => Unicode::strtolower($this->randomMachineName()), 'entity_type' => 'node', 'type' => 'comment'));
     $field_storage->save();
     entity_create('field_config', array('field_storage' => $field_storage, 'bundle' => $content_type->id(), 'label' => $this->randomMachineName() . '_label', 'description' => $this->randomMachineName() . '_description', 'settings' => array('comment_type' => $comment_type->id())))->save();
     entity_create('field_config', array('field_storage' => FieldStorageConfig::loadByName('node', 'body'), 'bundle' => $content_type->id(), 'label' => $this->randomMachineName() . '_body', 'settings' => array('display_summary' => TRUE)))->save();
     $expected = [];
     $expected['test_field_get_entity'] = ['module' => ['comment', 'node', 'user']];
     // Tests dependencies of relationships.
     $expected['test_relationship_dependency'] = ['module' => ['comment', 'node', 'user']];
     $expected['test_plugin_dependencies'] = ['module' => ['comment', 'views_test_data'], 'content' => ['RowTest', 'StaticTest', 'StyleTest']];
     $expected['test_argument_dependency'] = ['config' => ['core.entity_view_mode.node.teaser', 'field.storage.node.body'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['node', 'search', 'text', 'user']];
     foreach ($this::$testViews as $view_id) {
         $view = Views::getView($view_id);
         $dependencies = $view->calculateDependencies();
         $this->assertEqual($expected[$view_id], $dependencies);
         $config = $this->config('views.view.' . $view_id);
         \Drupal::service('config.storage.staging')->write($view_id, $config->get());
     }
     // Ensure that dependencies are calculated on the display level.
     $expected_display['default'] = ['config' => ['core.entity_view_mode.node.teaser'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['core', 'node', 'search', 'user', 'views']];
     $expected_display['page'] = ['config' => ['field.storage.node.body'], 'module' => ['core', 'text', 'views']];
     $view = Views::getView('test_argument_dependency');
     $view->initDisplay();
     foreach ($view->displayHandlers as $display) {
         // Calculate the dependencies each display has.
         $this->assertEqual($expected_display[$display->getPluginId()], $display->calculateDependencies());
     }
 }
Example #20
0
 public function preRender(&$values)
 {
     $uids = array();
     $this->items = array();
     $permission_names = \Drupal::service('user.permissions')->getPermissions();
     $rids = array();
     foreach ($values as $result) {
         $user_rids = $this->getEntity($result)->getRoles();
         $uid = $this->getValue($result);
         foreach ($user_rids as $rid) {
             $rids[$rid][] = $uid;
         }
     }
     if ($rids) {
         $roles = $this->roleStorage->loadMultiple(array_keys($rids));
         foreach ($rids as $rid => $role_uids) {
             foreach ($roles[$rid]->getPermissions() as $permission) {
                 foreach ($role_uids as $uid) {
                     $this->items[$uid][$permission]['permission'] = $permission_names[$permission]['title'];
                 }
             }
         }
         foreach ($uids as $uid) {
             if (isset($this->items[$uid])) {
                 ksort($this->items[$uid]);
             }
         }
     }
 }
Example #21
0
 /**
  * Check that the directory can be used for backup.
  *
  * @throws \BackupMigrate\Core\Exception\BackupMigrateException
  */
 protected function checkDirectory()
 {
     // @TODO: Figure out if the file is or might be accessible via the web.
     $dir = $this->confGet('directory');
     $is_private = strpos($dir, 'private://') === 0;
     // Attempt to create/prepare the directory if it is in the private directory
     if ($is_private) {
         if (!file_prepare_directory($dir, FILE_CREATE_DIRECTORY && FILE_MODIFY_PERMISSIONS)) {
             throw new BackupMigrateException("The backup file could not be saved to '%dir' because the directory could not be created or cannot be written to. Please make sure your private files directory is writable by the web server.", ['%dir' => $dir]);
         }
     } else {
         // If the file is local to the server.
         $real = \Drupal::service('file_system')->realpath($dir);
         if ($real) {
             // If the file is within the docroot.
             $in_root = strpos($real, DRUPAL_ROOT) === 0;
             if ($in_root && !$is_private) {
                 throw new BackupMigrateException("The backup file could not be saved to '%dir' because that directory may be publicly accessible via the web. Please save your backups to the private file directory or a directory outside of the web root.", ['%dir' => $dir]);
             }
         }
     }
     // Do the regular exists/writable checks
     parent::checkDirectory();
     // @TODO: Warn if the realpath cannot be resolved (because we cannot determine if the file is publicly accessible)
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL)
 {
     $config = $this->config('easychart.settings');
     $load_defaults = FALSE;
     // Get defaults.
     foreach ($this->getDefaults() as $default) {
         // Verify default options.
         $default_value = $config->get($default);
         if (empty($default_value)) {
             // Set flag to true.
             $load_defaults = TRUE;
             $form['#attached']['drupalSettings']['easychart'][$default] = TRUE;
         }
     }
     if ($load_defaults) {
         $form['#attached']['library'][] = 'easychart/easychart.defaults';
         $form['#attached']['library'][] = 'easychart/lib.easycharts.full';
     }
     $options = $config->get('options');
     $form['options'] = ['#type' => 'textarea', '#title' => $this->t('Available options'), '#description' => $this->t('These Highcharts options will be configurable in the Easychart interface when creating/editing a chart. See <a href="@url" target="_blank">http://api.highcharts.com/highcharts</a> for all available options.', array('@url' => Url::fromUri('http://api.highcharts.com/highcharts')->toUriString())), '#default_value' => $options, '#attributes' => array('class' => array('easychart-options')), '#rows' => 15];
     $form['templates'] = ['#type' => 'textarea', '#title' => t('Available templates'), '#default_value' => $config->get('templates'), '#description' => t("These templates will be selectable in the Easychart interface when creating/editing a chart."), '#attributes' => array('class' => array('easychart-templates')), '#rows' => 15];
     $form['presets'] = ['#type' => 'textarea', '#title' => t('Presets'), '#default_value' => $config->get('presets'), '#description' => $this->t('Presets for every Easychart chart. If these preset are also mentioned in the available options, they will be shown, but not editable.'), '#attributes' => array('class' => array('easychart-presets')), '#rows' => 10];
     $interval = array(3600, 10800, 21600, 32400, 43200, 86400, 172800);
     $form['url_update_frequency'] = ['#type' => 'select', '#title' => t('Update frequency'), '#options' => array(0 => t('Never')) + array_map([\Drupal::service('date.formatter'), 'formatInterval'], array_combine($interval, $interval)), '#default_value' => $config->get('url_update_frequency'), '#description' => $this->t('When to update the data for charts using a CSV URL.'), '#rows' => 10];
     $form['actions']['reset'] = ['#type' => 'submit', '#value' => t('Reset to defaults'), '#submit' => array('::resetForm'), '#limit_validation_errors' => array(), '#weight' => 100];
     return parent::buildForm($form, $form_state);
 }
 /**
  * Tests migration of syslog variables to syslog.settings.yml.
  */
 public function testSyslogSettings()
 {
     $config = $this->config('syslog.settings');
     $this->assertIdentical('drupal', $config->get('identity'));
     $this->assertIdentical('128', $config->get('facility'));
     $this->assertConfigSchema(\Drupal::service('config.typed'), 'syslog.settings', $config->get());
 }
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     /** @var \Drupal\currency\ConfigImporterInterface $config_importer */
     $config_importer = \Drupal::service('currency.config_importer');
     $config_importer->importCurrency('EUR');
 }
 /**
  * Assert translations JS is added before drupal.js, because it depends on it.
  */
 public function testLocaleTranslationJsDependencies()
 {
     // User to add and remove language.
     $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'translate interface'));
     // Add custom language.
     $this->drupalLogin($admin_user);
     // Code for the language.
     $langcode = 'es';
     // The English name for the language.
     $name = $this->randomMachineName(16);
     // The domain prefix.
     $prefix = $langcode;
     $edit = array('predefined_langcode' => 'custom', 'langcode' => $langcode, 'label' => $name, 'direction' => LanguageInterface::DIRECTION_LTR);
     $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
     // Set path prefix.
     $edit = array("prefix[{$langcode}]" => $prefix);
     $this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
     // This forces locale.admin.js string sources to be imported, which contains
     // the next translation.
     $this->drupalGet($prefix . '/admin/config/regional/translate');
     // Translate a string in locale.admin.js to our new language.
     $strings = \Drupal::service('locale.storage')->getStrings(array('source' => 'Show description', 'type' => 'javascript', 'name' => 'core/modules/locale/locale.admin.js'));
     $string = $strings[0];
     $this->drupalPostForm(NULL, ['string' => 'Show description'], t('Filter'));
     $edit = ['strings[' . $string->lid . '][translations][0]' => $this->randomString(16)];
     $this->drupalPostForm(NULL, $edit, t('Save translations'));
     // Calculate the filename of the JS including the translations.
     $js_translation_files = \Drupal::state()->get('locale.translation.javascript');
     $js_filename = $prefix . '_' . $js_translation_files[$prefix] . '.js';
     // Assert translations JS is included before drupal.js.
     $this->assertTrue(strpos($this->content, $js_filename) < strpos($this->content, 'core/misc/drupal.js'), 'Translations are included before Drupal.t.');
 }
 /**
  * Tests migration of menu links.
  */
 public function testMenuLinks()
 {
     $this->executeMigration('menu_links');
     $this->assertEntity(469, 'Bing', static::MENU_NAME, 'Bing', TRUE, FALSE, ['attributes' => ['title' => 'Bing']], 'http://bing.com', 0);
     $this->assertEntity(467, 'Google', static::MENU_NAME, 'Google', TRUE, FALSE, ['attributes' => ['title' => 'Google']], 'http://google.com', 0);
     $this->assertEntity(468, 'Yahoo', static::MENU_NAME, 'Yahoo', TRUE, FALSE, ['attributes' => ['title' => 'Yahoo']], 'http://yahoo.com', 0);
     $menu_link_tree_service = \Drupal::service('menu.link_tree');
     $parameters = new MenuTreeParameters();
     $tree = $menu_link_tree_service->load(static::MENU_NAME, $parameters);
     $this->assertEqual(2, count($tree));
     $children = 0;
     $google_found = FALSE;
     foreach ($tree as $menu_link_tree_element) {
         $children += $menu_link_tree_element->hasChildren;
         if ($menu_link_tree_element->link->getUrlObject()->toString() == 'http://bing.com') {
             $this->assertEqual(reset($menu_link_tree_element->subtree)->link->getUrlObject()->toString(), 'http://google.com');
             $google_found = TRUE;
         }
     }
     $this->assertEqual(1, $children);
     $this->assertTrue($google_found);
     // Now find the custom link under a system link.
     $parameters->root = 'system.admin_structure';
     $tree = $menu_link_tree_service->load(static::MENU_NAME, $parameters);
     $found = FALSE;
     foreach ($tree as $menu_link_tree_element) {
         $this->pass($menu_link_tree_element->link->getUrlObject()->toString());
         if ($menu_link_tree_element->link->getTitle() == 'custom link test') {
             $found = TRUE;
             break;
         }
     }
     $this->assertTrue($found);
 }
Example #27
0
 /**
  * Tests configuration events.
  */
 function testConfigEvents()
 {
     $name = 'config_events_test.test';
     $config = new Config($name, \Drupal::service('config.storage'), \Drupal::service('event_dispatcher'), \Drupal::service('config.typed'));
     $config->set('key', 'initial');
     \Drupal::state()->get('config_events_test.event', FALSE);
     $this->assertIdentical(\Drupal::state()->get('config_events_test.event', array()), array(), 'No events fired by creating a new configuration object');
     $config->save();
     $event = \Drupal::state()->get('config_events_test.event', array());
     $this->assertIdentical($event['event_name'], ConfigEvents::SAVE);
     $this->assertIdentical($event['current_config_data'], array('key' => 'initial'));
     $this->assertIdentical($event['raw_config_data'], array('key' => 'initial'));
     $this->assertIdentical($event['original_config_data'], array());
     $config->set('key', 'updated')->save();
     $event = \Drupal::state()->get('config_events_test.event', array());
     $this->assertIdentical($event['event_name'], ConfigEvents::SAVE);
     $this->assertIdentical($event['current_config_data'], array('key' => 'updated'));
     $this->assertIdentical($event['raw_config_data'], array('key' => 'updated'));
     $this->assertIdentical($event['original_config_data'], array('key' => 'initial'));
     $config->delete();
     $event = \Drupal::state()->get('config_events_test.event', array());
     $this->assertIdentical($event['event_name'], ConfigEvents::DELETE);
     $this->assertIdentical($event['current_config_data'], array());
     $this->assertIdentical($event['raw_config_data'], array());
     $this->assertIdentical($event['original_config_data'], array('key' => 'updated'));
 }
 /**
  * Contrast operations test.
  */
 public function doTestContrastOperations()
 {
     $image_factory = $this->container->get('image.factory');
     $image_toolkit_id = $image_factory->getToolkitId();
     // Test on the PNG test image.
     $test_file = drupal_get_path('module', 'simpletest') . '/files/image-test.png';
     $original_uri = file_unmanaged_copy($test_file, 'public://', FILE_EXISTS_RENAME);
     $generated_uri = 'public://styles/image_effects_test/public/' . \Drupal::service('file_system')->basename($original_uri);
     // Test data.
     $test_data = ['0' => [$this->red, $this->green, $this->transparent, $this->blue], '-50' => [$image_toolkit_id === 'imagemagick' ? array(180, 75, 75, 0) : array(159, 95, 95, 0), $image_toolkit_id === 'imagemagick' ? array(75, 180, 75, 0) : array(95, 159, 95, 0), $this->transparent, $image_toolkit_id === 'imagemagick' ? array(75, 75, 180, 0) : array(95, 95, 159, 0)], '-100' => [$image_toolkit_id === 'imagemagick' ? array(128, 128, 128, 0) : array(127, 127, 127, 0), $image_toolkit_id === 'imagemagick' ? array(128, 128, 128, 0) : array(127, 127, 127, 0), $this->transparent, $image_toolkit_id === 'imagemagick' ? array(128, 128, 128, 0) : array(127, 127, 127, 0)], '50' => [array(255, 0, 0, 0), array(0, 255, 0, 0), $this->transparent, array(0, 0, 255, 0)], '100' => [array(255, 0, 0, 0), array(0, 255, 0, 0), $this->transparent, array(0, 0, 255, 0)]];
     foreach ($test_data as $key => $colors) {
         // Add contrast effect to the test image style.
         $effect = ['id' => 'image_effects_contrast', 'data' => ['level' => $key]];
         $uuid = $this->addEffectToTestStyle($effect);
         // Load Image Style.
         $image_style = ImageStyle::load('image_effects_test');
         // Check that ::applyEffect generates image with expected contrast.
         $image_style->createDerivative($original_uri, $image_style->buildUri($original_uri));
         $image = $image_factory->get($generated_uri, 'gd');
         $this->assertTrue($this->colorsAreEqual($colors[0], $this->getPixelColor($image, 0, 0)));
         $this->assertTrue($this->colorsAreEqual($colors[1], $this->getPixelColor($image, 39, 0)));
         $this->assertTrue($this->colorsAreEqual($colors[2], $this->getPixelColor($image, 0, 19)));
         $this->assertTrue($this->colorsAreEqual($colors[3], $this->getPixelColor($image, 39, 19)));
         // Remove effect.
         $uuid = $this->removeEffectFromTestStyle($uuid);
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installConfig(['system']);
     $this->installConfig(['field']);
     $this->installConfig(['text']);
     $this->installConfig(['address']);
     $this->installEntitySchema('entity_test');
     ConfigurableLanguage::createFromLangcode('zh-hant')->save();
     // The address module is never installed, so the importer doesn't run
     // automatically. Instead, we manually import the address formats we need.
     $country_codes = ['AD', 'SV', 'TW', 'US', 'ZZ'];
     $importer = \Drupal::service('address.address_format_importer');
     $importer->importEntities($country_codes);
     $importer->importTranslations(['zh-hant']);
     $this->entityType = 'entity_test';
     $this->bundle = $this->entityType;
     $this->fieldName = Unicode::strtolower($this->randomMachineName());
     $field_storage = FieldStorageConfig::create(['field_name' => $this->fieldName, 'entity_type' => $this->entityType, 'type' => 'address']);
     $field_storage->save();
     $field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => $this->bundle, 'label' => $this->randomMachineName()]);
     $field->save();
     $values = ['targetEntityType' => $this->entityType, 'bundle' => $this->bundle, 'mode' => 'default', 'status' => TRUE];
     $this->display = \Drupal::entityTypeManager()->getStorage('entity_view_display')->create($values);
     $this->display->setComponent($this->fieldName, ['type' => 'address_default', 'settings' => []]);
     $this->display->save();
 }
Example #30
0
 /**
  * {@inheritdoc}
  */
 public function applyDefaultValue($notify = TRUE)
 {
     // Default to one field item with a generated UUID.
     $uuid = \Drupal::service('uuid');
     $this->setValue(array('value' => $uuid->generate()), $notify);
     return $this;
 }