示例#1
1
 /**
  * {@inheritdoc}
  */
 public function preRender(&$element, $rendering_object)
 {
     $element += array('#prefix' => '<div class=" ' . implode(' ', $this->getClasses()) . '">', '#suffix' => '</div>', '#tree' => TRUE, '#parents' => array($this->group->group_name), '#default_tab' => '');
     if ($this->getSetting('id')) {
         $element['#id'] = Html::getId($this->getSetting('id'));
     }
     // By default tabs don't have titles but you can override it in the theme.
     if ($this->getLabel()) {
         $element['#title'] = SafeMarkup::checkPlain($this->getLabel());
     }
     $form_state = new \Drupal\Core\Form\FormState();
     if ($this->getSetting('direction') == 'vertical') {
         $element += array('#type' => 'vertical_tabs', '#theme_wrappers' => array('vertical_tabs'));
         $complete_form = array();
         $element = \Drupal\Core\Render\Element\VerticalTabs::processVerticalTabs($element, $form_state, $complete_form);
     } else {
         $element += array('#type' => 'horizontal_tabs', '#theme_wrappers' => array('horizontal_tabs'));
         $on_form = $this->context == 'form';
         $element = \Drupal\field_group\Element\HorizontalTabs::processHorizontalTabs($element, $form_state, $on_form);
     }
     // Make sure the group has 1 child. This is needed to succeed at form_pre_render_vertical_tabs().
     // Skipping this would force us to move all child groups to this array, making it an un-nestable.
     $element['group']['#groups'][$this->group->group_name] = array(0 => array());
     $element['group']['#groups'][$this->group->group_name]['#group_exists'] = TRUE;
     // Search for a tab that was marked as open. First one wins.
     foreach (\Drupal\Core\Render\Element::children($element) as $tab_name) {
         if (!empty($element[$tab_name]['#open'])) {
             $element[$this->group->group_name . '__active_tab']['#default_value'] = $tab_name;
             break;
         }
     }
 }
 /**
  * Tests the rediscovering.
  */
 public function testRediscover()
 {
     \Drupal::state()->set('menu_link_content_dynamic_route.routes', ['route_name_1' => new Route('/example-path')]);
     \Drupal::service('router.builder')->rebuild();
     // Set up a custom menu link pointing to a specific path.
     MenuLinkContent::create(['title' => '<script>alert("Welcome to the discovered jungle!")</script>', 'link' => [['uri' => 'internal:/example-path']], 'menu_name' => 'tools'])->save();
     $menu_tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
     $this->assertEqual(1, count($menu_tree));
     /** @var \Drupal\Core\Menu\MenuLinkTreeElement $tree_element */
     $tree_element = reset($menu_tree);
     $this->assertEqual('route_name_1', $tree_element->link->getRouteName());
     // Change the underlying route and trigger the rediscovering.
     \Drupal::state()->set('menu_link_content_dynamic_route.routes', ['route_name_2' => new Route('/example-path')]);
     \Drupal::service('router.builder')->rebuild();
     // Ensure that the new route name / parameters are captured by the tree.
     $menu_tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
     $this->assertEqual(1, count($menu_tree));
     /** @var \Drupal\Core\Menu\MenuLinkTreeElement $tree_element */
     $tree_element = reset($menu_tree);
     $this->assertEqual('route_name_2', $tree_element->link->getRouteName());
     $title = $tree_element->link->getTitle();
     $this->assertFalse($title instanceof TranslationWrapper);
     $this->assertIdentical('<script>alert("Welcome to the discovered jungle!")</script>', $title);
     $this->assertFalse(SafeMarkup::isSafe($title));
 }
 /**
  * Tests that mails for contact messages are correctly sent.
  */
 function testSendPersonalContactMessage()
 {
     // Ensure that the web user's email needs escaping.
     $mail = $this->webUser->getUsername() . '&escaped@example.com';
     $this->webUser->setEmail($mail)->save();
     $this->drupalLogin($this->webUser);
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertEscaped($mail);
     $message = $this->submitPersonalContact($this->contactUser);
     $mails = $this->drupalGetMails();
     $this->assertEqual(1, count($mails));
     $mail = $mails[0];
     $this->assertEqual($mail['to'], $this->contactUser->getEmail());
     $this->assertEqual($mail['from'], $this->config('system.site')->get('mail'));
     $this->assertEqual($mail['reply-to'], $this->webUser->getEmail());
     $this->assertEqual($mail['key'], 'user_mail');
     $variables = array('@site-name' => $this->config('system.site')->get('name'), '@subject' => $message['subject[0][value]'], '@recipient-name' => $this->contactUser->getDisplayName());
     $subject = PlainTextOutput::renderFromHtml(t('[@site-name] @subject', $variables));
     $this->assertEqual($mail['subject'], $subject, 'Subject is in sent message.');
     $this->assertTrue(strpos($mail['body'], 'Hello ' . $variables['@recipient-name']) !== FALSE, 'Recipient name is in sent message.');
     $this->assertTrue(strpos($mail['body'], $this->webUser->getDisplayName()) !== FALSE, 'Sender name is in sent message.');
     $this->assertTrue(strpos($mail['body'], $message['message[0][value]']) !== FALSE, 'Message body is in sent message.');
     // Check there was no problems raised during sending.
     $this->drupalLogout();
     $this->drupalLogin($this->adminUser);
     // Verify that the correct watchdog message has been logged.
     $this->drupalGet('/admin/reports/dblog');
     $placeholders = array('@sender_name' => $this->webUser->username, '@sender_email' => $this->webUser->getEmail(), '@recipient_name' => $this->contactUser->getUsername());
     $this->assertRaw(SafeMarkup::format('@sender_name (@sender_email) sent @recipient_name an email.', $placeholders));
     // Ensure an unescaped version of the email does not exist anywhere.
     $this->assertNoRaw($this->webUser->getEmail());
 }
示例#4
0
 /**
  * Test enable/disable of countries.
  */
 public function testCountryUI()
 {
     $this->drupalLogin($this->drupalCreateUser(array('administer countries', 'administer store')));
     // Testing all countries is too much, so we just enable a random selection
     // of 8 countries. All countries will then be tested at some point.
     $countries = \Drupal::service('country_manager')->getAvailableList();
     $country_ids = array_rand($countries, 8);
     $last_country = array_pop($country_ids);
     // Loop over the first seven.
     foreach ($country_ids as $country_id) {
         // Verify this country isn't already enabled.
         $this->drupalGet('admin/store/config/country');
         $this->assertLinkByHref('admin/store/config/country/' . $country_id . '/enable', 0, SafeMarkup::format('%country is not enabled by default.', ['%country' => $countries[$country_id]]));
         // Enable this country.
         $this->drupalGet('admin/store/config/country/' . $country_id . '/enable');
         $this->assertText(t('The country @country has been enabled.', ['@country' => $countries[$country_id]]));
         $this->assertLinkByHref('admin/store/config/country/' . $country_id . '/disable', 0, SafeMarkup::format('%country is now enabled.', ['%country' => $countries[$country_id]]));
     }
     // Verify that last random country doesn't show up as available.
     $this->drupalGet('admin/store/config/store');
     $this->assertNoOption('edit-uc-store-country', $last_country, SafeMarkup::format('%country not listed in uc_address select country field.', ['%country' => $countries[$last_country]]));
     // Enable the last country.
     $this->drupalGet('admin/store/config/country/' . $last_country . '/enable');
     $this->assertText(t('The country @country has been enabled.', ['@country' => $countries[$last_country]]));
     $this->assertLinkByHref('admin/store/config/country/' . $last_country . '/disable', 0, SafeMarkup::format('%country is now enabled.', ['%country' => $countries[$last_country]]));
     // Verify that last random country now shows up as available.
     $this->drupalGet('admin/store/config/store');
     $this->assertOption('edit-uc-store-country', $last_country, SafeMarkup::format('%country is listed in uc_address select country field.', ['%country' => $countries[$last_country]]));
     // Disable the last country using the operations button.
     $this->drupalGet('admin/store/config/country');
     $this->clickLink('Disable', 7);
     // The 8th Disable link.
     $this->assertText(t('The country @country has been disabled.', ['@country' => $countries[$last_country]]));
     $this->assertLinkByHref('admin/store/config/country/' . $last_country . '/enable', 0, SafeMarkup::format('%country is now disabled.', ['%country' => $countries[$last_country]]));
 }
示例#5
0
 /**
  * Test front page functionality.
  */
 public function testDrupalFrontPage()
 {
     // Create a promoted node to test the <title> tag on the front page view.
     $settings = array('title' => $this->randomMachineName(8), 'promote' => 1);
     $this->drupalCreateNode($settings);
     $this->drupalGet('');
     $this->assertTitle('Home | Drupal');
     $this->assertText(t('On front page.'), 'Path is the front page.');
     $this->drupalGet('node');
     $this->assertText(t('On front page.'), 'Path is the front page.');
     $this->drupalGet($this->nodePath);
     $this->assertNoText(t('On front page.'), 'Path is not the front page.');
     // Change the front page to an invalid path.
     $edit = array('site_frontpage' => '/kittens');
     $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
     $this->assertText(t("The path '@path' is either invalid or you do not have access to it.", array('@path' => $edit['site_frontpage'])));
     // Change the front page to a path without a starting slash.
     $edit = ['site_frontpage' => $this->nodePath];
     $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
     $this->assertRaw(SafeMarkup::format("The path '%path' has to start with a slash.", ['%path' => $edit['site_frontpage']]));
     // Change the front page to a valid path.
     $edit['site_frontpage'] = '/' . $this->nodePath;
     $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
     $this->assertText(t('The configuration options have been saved.'), 'The front page path has been saved.');
     $this->drupalGet('');
     $this->assertText(t('On front page.'), 'Path is the front page.');
     $this->drupalGet('node');
     $this->assertNoText(t('On front page.'), 'Path is not the front page.');
     $this->drupalGet($this->nodePath);
     $this->assertText(t('On front page.'), 'Path is the front page.');
 }
 /**
  * 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)));
     }
 }
示例#7
0
 /**
  * {@inheritdoc}
  */
 public function import(Row $row, array $old_destination_id_values = array())
 {
     $file = $row->getSourceProperty($this->configuration['source_path_property']);
     $destination = $row->getDestinationProperty($this->configuration['destination_path_property']);
     $source = $this->configuration['source_base_path'] . $file;
     // Ensure the source file exists, if it's a local URI or path.
     if ($this->isLocalUri($source) && !file_exists($source)) {
         throw new MigrateException(SafeMarkup::format('File @source does not exist.', ['@source' => $source]));
     }
     // If the start and end file is exactly the same, there is nothing to do.
     if ($this->isLocationUnchanged($source, $destination)) {
         return parent::import($row, $old_destination_id_values);
     }
     $replace = $this->getOverwriteMode($row);
     $success = $this->writeFile($source, $destination, $replace);
     if (!$success) {
         $dir = $this->getDirectory($destination);
         if (file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {
             $success = $this->writeFile($source, $destination, $replace);
         } else {
             throw new MigrateException(SafeMarkup::format('Could not create directory @dir', ['@dir' => $dir]));
         }
     }
     if ($success) {
         return parent::import($row, $old_destination_id_values);
     } else {
         throw new MigrateException(SafeMarkup::format('File %source could not be copied to %destination.', ['%source' => $source, '%destination' => $destination]));
     }
 }
示例#8
0
 /**
  * Tests that the database was properly loaded.
  */
 public function testDatabaseLoaded()
 {
     foreach (['user', 'node', 'system', 'update_test_schema'] as $module) {
         $this->assertEqual(drupal_get_installed_schema_version($module), 8000, SafeMarkup::format('Module @module schema is 8000', ['@module' => $module]));
     }
     // Ensure that all {router} entries can be unserialized. If they cannot be
     // unserialized a notice will be thrown by PHP.
     $result = \Drupal::database()->query("SELECT name, route from {router}")->fetchAllKeyed(0, 1);
     // For the purpose of fetching the notices and displaying more helpful error
     // messages, let's override the error handler temporarily.
     set_error_handler(function ($severity, $message, $filename, $lineno) {
         throw new \ErrorException($message, 0, $severity, $filename, $lineno);
     });
     foreach ($result as $route_name => $route) {
         try {
             unserialize($route);
         } catch (\Exception $e) {
             $this->fail(sprintf('Error "%s" while unserializing route %s', $e->getMessage(), Html::escape($route_name)));
         }
     }
     restore_error_handler();
     // Before accessing the site we need to run updates first or the site might
     // be broken.
     $this->runUpdates();
     $this->assertEqual(\Drupal::config('system.site')->get('name'), 'Site-Install');
     $this->drupalGet('<front>');
     $this->assertText('Site-Install');
     // Ensure that the database tasks have been run during set up. Neither MySQL
     // nor SQLite make changes that are testable.
     $database = $this->container->get('database');
     if ($database->driver() == 'pgsql') {
         $this->assertEqual('on', $database->query("SHOW standard_conforming_strings")->fetchField());
         $this->assertEqual('escape', $database->query("SHOW bytea_output")->fetchField());
     }
 }
 /**
  * Form element #after_build callback: output the old form build-id.
  */
 function form_test_storage_page_cache_old_build_id($form)
 {
     if (isset($form['#build_id_old'])) {
         $form['test_build_id_old']['#markup'] = SafeMarkup::checkPlain($form['#build_id_old']);
     }
     return $form;
 }
示例#10
0
 /**
  * {@inheritdoc}
  */
 public function getOutput()
 {
     $image = array('#theme' => 'image', '#uri' => $this->get('url'), '#alt' => $this->get('alt'));
     $output = '<h2 class="tour-tip-label" id="tour-tip-' . $this->get('ariaId') . '-label">' . SafeMarkup::checkPlain($this->get('label')) . '</h2>';
     $output .= '<p class="tour-tip-image" id="tour-tip-' . $this->get('ariaId') . '-contents">' . drupal_render($image) . '</p>';
     return array('#markup' => $output);
 }
 /**
  * Returns the plugin ID for a given toolkit and operation.
  *
  * @param \Drupal\Core\ImageToolkit\ImageToolkitInterface $toolkit
  *   The toolkit instance.
  * @param string $operation
  *   The operation (e.g. "crop").
  *
  * @return string
  *   The plugin ID.
  *
  * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
  *   When no plugin is available.
  */
 protected function getToolkitOperationPluginId(ImageToolkitInterface $toolkit, $operation)
 {
     $toolkit_id = $toolkit->getPluginId();
     $definitions = $this->getDefinitions();
     $definitions = array_filter($definitions, function ($definition) use($toolkit_id, $operation) {
         return $definition['toolkit'] == $toolkit_id && $definition['operation'] == $operation;
     });
     if (!$definitions) {
         // If this image toolkit plugin is a derivative and returns no operation,
         // try once again with its base plugin.
         $base_toolkit_id = $toolkit->getBaseId();
         if ($toolkit_id != $base_toolkit_id && !empty($base_toolkit_id)) {
             $base_toolkit = $this->toolkitManager->createInstance($base_toolkit_id);
             return $this->getToolkitOperationPluginId($base_toolkit, $operation);
         }
         $message = SafeMarkup::format("No image operation plugin for '@toolkit' toolkit and '@operation' operation.", array('@toolkit' => $toolkit_id, '@operation' => $operation));
         throw new PluginNotFoundException($toolkit_id . '.' . $operation, $message);
     } else {
         // Pickup the first plugin found.
         // @todo In https://www.drupal.org/node/2110591 we'll return here the UI
         //   selected plugin or the first found if missed.
         $definition = reset($definitions);
         return $definition['id'];
     }
 }
 /**
  * {@inheritdoc}
  */
 public function filter(RouteCollection $collection, Request $request)
 {
     // Generates a list of Symfony formats matching the acceptable MIME types.
     // @todo replace by proper content negotiation library.
     $acceptable_mime_types = $request->getAcceptableContentTypes();
     $acceptable_formats = array_filter(array_map(array($request, 'getFormat'), $acceptable_mime_types));
     $primary_format = $request->getRequestFormat();
     foreach ($collection as $name => $route) {
         // _format could be a |-delimited list of supported formats.
         $supported_formats = array_filter(explode('|', $route->getRequirement('_format')));
         if (empty($supported_formats)) {
             // No format restriction on the route, so it always matches. Move it to
             // the end of the collection by re-adding it.
             $collection->add($name, $route);
         } elseif (in_array($primary_format, $supported_formats)) {
             // Perfect match, which will get a higher priority by leaving the route
             // on top of the list.
         } elseif (in_array('*/*', $acceptable_mime_types) || array_intersect($acceptable_formats, $supported_formats)) {
             // Move it to the end of the list.
             $collection->add($name, $route);
         } else {
             // Remove the route if it does not match at all.
             $collection->remove($name);
         }
     }
     if (count($collection)) {
         return $collection;
     }
     // We do not throw a
     // \Symfony\Component\Routing\Exception\ResourceNotFoundException here
     // because we don't want to return a 404 status code, but rather a 406.
     throw new NotAcceptableHttpException(SafeMarkup::format('No route found for the specified formats @formats.', array('@formats' => implode(' ', $acceptable_mime_types))));
 }
示例#13
0
 /**
  * Test that standard paths works with multiple patterns.
  *
  * @dataProvider getMatchPathData
  */
 public function testMatchPath($patterns, $paths)
 {
     foreach ($paths as $path => $expected_result) {
         $actual_result = $this->pathMatcher->matchPath($path, $patterns);
         $this->assertEquals($actual_result, $expected_result, SafeMarkup::format('Tried matching the path <code>@path</code> to the pattern <pre>@patterns</pre> - expected @expected, got @actual.', array('@path' => $path, '@patterns' => $patterns, '@expected' => var_export($expected_result, TRUE), '@actual' => var_export($actual_result, TRUE))));
     }
 }
 /**
  * Tests the formatter settings page for the Boolean formatter.
  */
 function testBooleanFormatterSettings()
 {
     // List the options we expect to see on the settings form. Omit the one
     // with the Unicode check/x characters, which does not appear to work
     // well in WebTestBase.
     $options = array('Yes / No', 'True / False', 'On / Off', 'Enabled / Disabled', '1 / 0', 'Custom');
     // Define what the "default" option should look like, depending on the
     // field settings.
     $default = 'Field settings (@on / @off)';
     // For several different values of the field settings, test that the
     // options, including default, are shown correctly.
     $settings = array(array('Yes', 'No'), array('On', 'Off'), array('TRUE', 'FALSE'));
     foreach ($settings as $values) {
         // Set up the field settings.
         $this->drupalGet('admin/structure/types/manage/' . $this->bundle . '/fields/node.' . $this->bundle . '.' . $this->fieldName);
         $this->drupalPostForm(NULL, array('settings[on_label]' => $values[0], 'settings[off_label]' => $values[1]), 'Save settings');
         // Open the Manage Display page and trigger the field settings form.
         $this->drupalGet('admin/structure/types/manage/' . $this->bundle . '/display');
         $this->drupalPostAjaxForm(NULL, array(), $this->fieldName . '_settings_edit');
         // Test that the settings options are present in the correct format.
         foreach ($options as $string) {
             $this->assertText($string);
         }
         $this->assertText(SafeMarkup::format($default, array('@on' => $values[0], '@off' => $values[1])));
     }
 }
示例#15
0
 /**
  * Tests the integration.
  */
 public function testIntegration()
 {
     // Remove the watchdog entries added by the potential batch process.
     $this->container->get('database')->truncate('watchdog')->execute();
     $entries = array();
     // Setup a watchdog entry without tokens.
     $entries[] = array('message' => $this->randomMachineName(), 'variables' => array('link' => \Drupal::l('Link', new Url('<front>'))));
     // Setup a watchdog entry with one token.
     $entries[] = array('message' => '@token1', 'variables' => array('@token1' => $this->randomMachineName(), 'link' => \Drupal::l('Link', new Url('<front>'))));
     // Setup a watchdog entry with two tokens.
     $entries[] = array('message' => '@token1 !token2', 'variables' => array('@token1' => $this->randomMachineName(), '!token2' => $this->randomMachineName(), 'link' => \Drupal::l(SafeMarkup::set('<object>Link</object>'), new Url('<front>'))));
     $logger_factory = $this->container->get('logger.factory');
     foreach ($entries as $entry) {
         $entry += array('type' => 'test-views', 'severity' => RfcLogLevel::NOTICE);
         $logger_factory->get($entry['type'])->log($entry['severity'], $entry['message'], $entry['variables']);
     }
     $view = Views::getView('test_dblog');
     $this->executeView($view);
     $view->initStyle();
     foreach ($entries as $index => $entry) {
         $this->assertEqual($view->style_plugin->getField($index, 'message'), SafeMarkup::format($entry['message'], $entry['variables']));
         $this->assertEqual($view->style_plugin->getField($index, 'link'), Xss::filterAdmin($entry['variables']['link']));
     }
     // Disable replacing variables and check that the tokens aren't replaced.
     $view->destroy();
     $view->storage->invalidateCaches();
     $view->initHandlers();
     $this->executeView($view);
     $view->initStyle();
     $view->field['message']->options['replace_variables'] = FALSE;
     foreach ($entries as $index => $entry) {
         $this->assertEqual($view->style_plugin->getField($index, 'message'), $entry['message']);
     }
 }
示例#16
0
 /**
  * Tests inline templates.
  */
 public function testInlineTemplate()
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = $this->container->get('renderer');
     /** @var \Drupal\Core\Template\TwigEnvironment $environment */
     $environment = \Drupal::service('twig');
     $this->assertEqual($environment->renderInline('test-no-context'), 'test-no-context');
     $this->assertEqual($environment->renderInline('test-with-context {{ llama }}', array('llama' => 'muuh')), 'test-with-context muuh');
     $element = array();
     $unsafe_string = '<script>alert(\'Danger! High voltage!\');</script>';
     $element['test'] = array('#type' => 'inline_template', '#template' => 'test-with-context <label>{{ unsafe_content }}</label>', '#context' => array('unsafe_content' => $unsafe_string));
     $this->assertEqual($renderer->renderRoot($element), 'test-with-context <label>' . SafeMarkup::checkPlain($unsafe_string) . '</label>');
     // Enable twig_auto_reload and twig_debug.
     $settings = Settings::getAll();
     $settings['twig_debug'] = TRUE;
     $settings['twig_auto_reload'] = TRUE;
     new Settings($settings);
     $this->container = $this->kernel->rebuildContainer();
     \Drupal::setContainer($this->container);
     $element = array();
     $element['test'] = array('#type' => 'inline_template', '#template' => 'test-with-context {{ llama }}', '#context' => array('llama' => 'muuh'));
     $element_copy = $element;
     // Render it twice so that twig caching is triggered.
     $this->assertEqual($renderer->renderRoot($element), 'test-with-context muuh');
     $this->assertEqual($renderer->renderRoot($element_copy), 'test-with-context muuh');
 }
示例#17
0
 /**
  * Simulates submission of a form using GET instead of POST.
  *
  * Forms that use the GET method cannot be submitted with
  * WebTestBase::drupalPostForm(), which explicitly uses POST to submit the
  * form. So this method finds the form, verifies that it has input fields and
  * a submit button matching the inputs to this method, and then calls
  * WebTestBase::drupalGet() to simulate the form submission to the 'action'
  * URL of the form (if set, or the current URL if not).
  *
  * See WebTestBase::drupalPostForm() for more detailed documentation of the
  * function parameters.
  *
  * @param string $path
  *   Location of the form to be submitted: either a Drupal path, absolute
  *   path, or NULL to use the current page.
  * @param array $edit
  *   Form field data to submit. Unlike drupalPostForm(), this does not support
  *   file uploads.
  * @param string $submit
  *   Value of the submit button to submit clicking. Unlike drupalPostForm(),
  *   this does not support AJAX.
  * @param string $form_html_id
  *   (optional) HTML ID of the form, to disambiguate.
  */
 protected function submitGetForm($path, $edit, $submit, $form_html_id = NULL)
 {
     if (isset($path)) {
         $this->drupalGet($path);
     }
     if ($this->parse()) {
         // Iterate over forms to find one that matches $edit and $submit.
         $edit_save = $edit;
         $xpath = '//form';
         if (!empty($form_html_id)) {
             $xpath .= "[@id='" . $form_html_id . "']";
         }
         $forms = $this->xpath($xpath);
         foreach ($forms as $form) {
             // Try to set the fields of this form as specified in $edit.
             $edit = $edit_save;
             $post = array();
             $upload = array();
             $submit_matches = $this->handleForm($post, $edit, $upload, $submit, $form);
             if (!$edit && $submit_matches) {
                 // Everything matched, so "submit" the form.
                 $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : NULL;
                 $this->drupalGet($action, array('query' => $post));
                 return;
             }
         }
         // We have not found a form which contained all fields of $edit and
         // the submit button.
         foreach ($edit as $name => $value) {
             $this->fail(SafeMarkup::format('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
         }
         $this->assertTrue($submit_matches, format_string('Found the @submit button', array('@submit' => $submit)));
         $this->fail(format_string('Found the requested form fields at @path', array('@path' => $path)));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $form['help'] = array('#markup' => t('By default, only the "Free order" payment method is listed here. To see additional payment methods you must <a href="@install">install additional modules</a>. The "Payment Method Pack" module that comes with Ubercart provides "Check" and "COD" payment methods. The "Credit Card" module that comes with Ubercart provides a credit card payment method, although you will need an additional module to provide a payment gateway for your credit card. For more information about payment methods and settings please read the <a href="@doc">Ubercart Documentation</a>.', ['@install' => Url::fromRoute('system.modules_list')->toString(), '@doc' => Url::fromUri('http://www.drupal.org/documentation/modules/ubercart')->toString()]));
     $form['methods'] = array('#type' => 'table', '#header' => array(t('Payment method'), t('List position'), t('Operations')), '#tabledrag' => array(array('action' => 'order', 'relationship' => 'sibling', 'group' => 'uc-payment-method-weight')));
     foreach ($this->paymentMethodManager->getDefinitions() as $id => $method) {
         $form['methods'][$id]['#attributes']['class'][] = 'draggable';
         $form['methods'][$id]['status'] = array('#type' => 'checkbox', '#title' => SafeMarkup::checkPlain($method['name']), '#default_value' => $method['checkout']);
         $form['methods'][$id]['weight'] = array('#type' => 'weight', '#title' => t('Weight for @title', array('@title' => $method['name'])), '#title_display' => 'invisible', '#default_value' => $method['weight'], '#attributes' => array('class' => array('uc-payment-method-weight')));
         if (empty($method['no_gateway'])) {
             $gateways = _uc_payment_gateway_list($id, TRUE);
             $options = array();
             foreach ($gateways as $gateway_id => $gateway) {
                 $options[$gateway_id] = $gateway['title'];
             }
             if ($options) {
                 $form['methods'][$id]['status']['#title'] .= ' (' . t('includes %gateways', array('%gateways' => implode(', ', $options))) . ')';
             }
         }
         $links = array();
         if (!empty($method['settings_form'])) {
             $links['settings'] = array('title' => t('Settings'), 'url' => Url::fromRoute('uc_payment.method_settings', ['method' => $id]));
         }
         // $links['conditions'] = array(
         //   'title' => t('Conditions'),
         //   'url' => Url::fromRoute('admin/store/config/payment/manage/uc_payment_method_', ['method' => $id]),
         // );
         $form['methods'][$id]['settings'] = array('#type' => 'operations', '#links' => $links);
     }
     return parent::buildForm($form, $form_state);
 }
示例#19
0
 /**
  * Assert that a trail exists in the internal browser.
  *
  * @param array $trail
  *   An associative array whose keys are expected breadcrumb link paths and
  *   whose values are expected breadcrumb link texts (not sanitized).
  */
 protected function assertBreadcrumbParts($trail)
 {
     // Compare paths with actual breadcrumb.
     $parts = $this->getBreadcrumbParts();
     $pass = TRUE;
     // There may be more than one breadcrumb on the page. If $trail is empty
     // this test would go into an infinite loop, so we need to check that too.
     while ($trail && !empty($parts)) {
         foreach ($trail as $path => $title) {
             // If the path is empty, generate the path from the <front> route.  If
             // the path does not start with a leading slash, then run it through
             // Url::fromUri('base:')->toString() to get the correct base
             // prepended.
             if ($path == '') {
                 $url = Url::fromRoute('<front>')->toString();
             } elseif ($path[0] != '/') {
                 $url = Url::fromUri('base:' . $path)->toString();
             } else {
                 $url = $path;
             }
             $part = array_shift($parts);
             $pass = $pass && $part['href'] === $url && $part['text'] === SafeMarkup::checkPlain($title);
         }
     }
     // No parts must be left, or an expected "Home" will always pass.
     $pass = $pass && empty($parts);
     $this->assertTrue($pass, format_string('Breadcrumb %parts found on @path.', array('%parts' => implode(' » ', $trail), '@path' => $this->getUrl())));
 }
示例#20
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL)
 {
     $current_path = $request->attributes->get('_system_path');
     $current_url = Url::createFromRequest($request);
     $devel_config = $this->config('devel.settings');
     $form['queries'] = array('#type' => 'fieldset', '#title' => t('Query log'));
     $description = t('Display a log of the database queries needed to generate the current page, and the execution time for each. Also, queries which are repeated during a single page view are summed in the # column, and printed in red since they are candidates for caching.');
     $form['queries']['query_display'] = array('#type' => 'checkbox', '#title' => t('Display query log'), '#default_value' => $devel_config->get('query_display'), '#description' => $description);
     $form['queries']['settings'] = array('#type' => 'container', '#states' => array('invisible' => array('input[name="query_display"]' => array('checked' => FALSE))));
     $form['queries']['settings']['query_sort'] = array('#type' => 'radios', '#title' => t('Sort query log'), '#default_value' => $devel_config->get('query_sort'), '#options' => array(t('by source'), t('by duration')), '#description' => t('The query table can be sorted in the order that the queries were executed or by descending duration.'));
     $form['queries']['settings']['execution'] = array('#type' => 'textfield', '#title' => t('Slow query highlighting'), '#default_value' => $devel_config->get('execution'), '#size' => 4, '#maxlength' => 4, '#description' => t('Enter an integer in milliseconds. Any query which takes longer than this many milliseconds will be highlighted in the query log. This indicates a possibly inefficient query, or a candidate for caching.'));
     $form['api_url'] = array('#type' => 'textfield', '#title' => t('API Site'), '#default_value' => $devel_config->get('api_url'), '#description' => t('The base URL for your developer documentation links. You might change this if you run <a href="!url">api.module</a> locally.', array('!url' => Url::fromUri('http://drupal.org/project/api')->toString())));
     $form['timer'] = array('#type' => 'checkbox', '#title' => t('Display page timer'), '#default_value' => $devel_config->get('timer'), '#description' => t('Display page execution time in the query log box.'));
     $form['memory'] = array('#type' => 'checkbox', '#title' => t('Display memory usage'), '#default_value' => $devel_config->get('memory'), '#description' => t('Display how much memory is used to generate the current page. This will show memory usage when devel_init() is called and when devel_exit() is called.'));
     $form['redirect_page'] = array('#type' => 'checkbox', '#title' => t('Display redirection page'), '#default_value' => $devel_config->get('redirect_page'), '#description' => t('When a module executes drupal_goto(), the query log and other developer information is lost. Enabling this setting presents an intermediate page to developers so that the log can be examined before continuing to the destination page.'));
     $form['page_alter'] = array('#type' => 'checkbox', '#title' => t('Display $page array'), '#default_value' => $devel_config->get('page_alter'), '#description' => t('Display $page array from <a href="http://api.drupal.org/api/function/hook_page_alter/7">hook_page_alter()</a> in the messages area of each page.'));
     $form['raw_names'] = array('#type' => 'checkbox', '#title' => t('Display machine names of permissions and modules'), '#default_value' => $devel_config->get('raw_names'), '#description' => t('Display the language-independent machine names of the permissions in mouse-over hints on the !Permissions page and the module base file names on the @Permissions and !Modules pages.', array('!Permissions' => $this->l(t('Permissions'), Url::fromRoute('user.admin_permissions')), '@Permissions' => t('Permissions'), '!Modules' => $this->l(t('Modules'), Url::fromRoute('system.modules_list')))));
     $error_handlers = devel_get_handlers();
     $form['error_handlers'] = array('#type' => 'select', '#title' => t('Error handlers'), '#options' => array(DEVEL_ERROR_HANDLER_NONE => t('None'), DEVEL_ERROR_HANDLER_STANDARD => t('Standard Drupal'), DEVEL_ERROR_HANDLER_BACKTRACE_DPM => t('Krumo backtrace in the message area'), DEVEL_ERROR_HANDLER_BACKTRACE_KRUMO => t('Krumo backtrace above the rendered page')), '#multiple' => TRUE, '#default_value' => empty($error_handlers) ? DEVEL_ERROR_HANDLER_NONE : $error_handlers, '#description' => SafeMarkup::set(t('Select the error handler(s) to use, in case you <a href="@choose">choose to show errors on screen</a>.', array('@choose' => $this->url('system.logging_settings'))) . '<ul>' . '<li>' . t('<em>None</em> is a good option when stepping through the site in your debugger.') . '</li>' . '<li>' . t('<em>Standard Drupal</em> does not display all the information that is often needed to resolve an issue.') . '</li>' . '<li>' . t('<em>Krumo backtrace</em> displays nice debug information when any type of error is noticed, but only to users with the %perm permission.', array('%perm' => t('Access developer information'))) . '</li></ul>' . t('Depending on the situation, the theme, the size of the call stack and the arguments, etc., some handlers may not display their messages, or display them on the subsequent page. Select <em>Standard Drupal</em> <strong>and</strong> <em>Krumo backtrace above the rendered page</em> to maximize your chances of not missing any messages.') . '<br />' . t('Demonstrate the current error handler(s):') . ' ' . $this->l('notice', $current_url, array('query' => array('demo' => 'notice'))) . ', ' . $this->l('notice+warning', $current_url, array('query' => array('demo' => 'warning'))) . ', ' . $this->l('notice+warning+error', $current_url, array('query' => array('demo' => 'error'))) . ' ' . t('(The presentation of the @error is determined by PHP.)', array('@error' => 'error'))));
     $form['error_handlers']['#size'] = count($form['error_handlers']['#options']);
     if ($request->query->has('demo')) {
         if ($request->getMethod() == 'GET') {
             $this->demonstrateErrorHandlers($request->query->get('demo'));
         }
         $request->query->remove('demo');
     }
     $options = array('default', 'blue', 'green', 'orange', 'white', 'disabled');
     $form['krumo_skin'] = array('#type' => 'radios', '#title' => t('Krumo display'), '#description' => t('Select a skin for your debug messages or select <em>disabled</em> to display object and array output in standard PHP format.'), '#options' => array_combine($options, $options), '#default_value' => $devel_config->get('krumo_skin'));
     $form['rebuild_theme'] = array('#type' => 'checkbox', '#title' => t('Rebuild the theme information like the registry'), '#description' => t('While creating new templates, change the $theme.info.yml and theme_ overrides the theme information needs to be rebuilt.'), '#default_value' => $devel_config->get('rebuild_theme'));
     $form['use_uncompressed_jquery'] = array('#type' => 'checkbox', '#title' => t('Use uncompressed jQuery'), '#default_value' => $devel_config->get('use_uncompressed_jquery'), '#description' => t("Use a human-readable version of jQuery instead of the minified version that ships with Drupal, to make JavaScript debugging easier."));
     return parent::buildForm($form, $form_state);
 }
/**
 * Returns HTML for a single local action link.
 *
 * @param array $variables
 *   An associative array containing:
 *   - element: A render element containing:
 *     - #link: A menu link array with 'title', 'href', and 'localized_options'
 *       keys.
 *
 * @return string
 *   The constructed HTML.
 *
 * @see theme_menu_local_action()
 *
 * @ingroup theme_functions
 */
function bootstrap_preprocess_menu_local_action(&$variables)
{
    $link = $variables['element']['#link'];
    $link += array('localized_options' => array());
    $link['localized_options']['set_active_class'] = TRUE;
    $icon = _bootstrap_iconize_text($link['title']);
    $options = isset($link['localized_options']) ? $link['localized_options'] : array();
    if (isset($link['url'])) {
        // Turn link into a mini-button and colorize based on title.
        if ($class = _bootstrap_colorize_text($link['title'])) {
            if (!isset($options['attributes']['class'])) {
                $options['attributes']['class'] = array();
            }
            $string = is_string($options['attributes']['class']);
            if ($string) {
                $options['attributes']['class'] = explode(' ', $options['attributes']['class']);
            }
            $options['attributes']['class'][] = 'btn';
            $options['attributes']['class'][] = 'btn-xs';
            $options['attributes']['class'][] = 'btn-' . $class;
            if ($string) {
                $options['attributes']['class'] = implode(' ', $options['attributes']['class']);
            }
        }
        $variables['link'] = array('#type' => 'link', '#title' => SafeMarkup::format($icon . '@text', array('@text' => $link['title'])), '#options' => $options, '#url' => $link['url']);
    } else {
        $variables['link'] = array('#type' => 'link', '#title' => $link['title'], '#options' => $options, '#url' => $link['url']);
    }
}
示例#22
0
 /**
  * {@inheritdoc}
  */
 public function preprocessElement(Element $element, Variables $variables)
 {
     $link = $element->getProperty('link');
     $link += ['localized_options' => []];
     $link['localized_options']['set_active_class'] = TRUE;
     $icon = Bootstrap::glyphiconFromString($link['title']);
     $options = isset($link['localized_options']) ? $link['localized_options'] : [];
     if (isset($link['url'])) {
         // Turn link into a mini-button and colorize based on title.
         $class = Bootstrap::cssClassFromString($link['title'], 'default');
         if (!isset($options['attributes']['class'])) {
             $options['attributes']['class'] = [];
         }
         $string = is_string($options['attributes']['class']);
         if ($string) {
             $options['attributes']['class'] = explode(' ', $options['attributes']['class']);
         }
         $options['attributes']['class'][] = 'btn';
         $options['attributes']['class'][] = 'btn-xs';
         $options['attributes']['class'][] = 'btn-' . $class;
         if ($string) {
             $options['attributes']['class'] = implode(' ', $options['attributes']['class']);
         }
         $variables['link'] = ['#type' => 'link', '#title' => SafeMarkup::format(\Drupal::service('renderer')->render($icon) . '@text', ['@text' => $link['title']]), '#options' => $options, '#url' => $link['url']];
     } else {
         $variables['link'] = ['#type' => 'link', '#title' => $link['title'], '#options' => $options, '#url' => $link['url']];
     }
 }
示例#23
0
 /**
  * Test pathauto_cleanstring().
  */
 public function testCleanString()
 {
     $config = $this->config('pathauto.settings');
     $tests = array();
     $config->set('ignore_words', ', in, is,that, the  , this, with, ');
     $config->set('max_component_length', 35);
     $config->set('transliterate', TRUE);
     $config->save();
     \Drupal::service('pathauto.manager')->resetCaches();
     // Test the 'ignored words' removal.
     $tests['this'] = 'this';
     $tests['this with that'] = 'this-with-that';
     $tests['this thing with that thing'] = 'thing-thing';
     // Test length truncation and duplicate separator removal.
     $tests[' - Pathauto is the greatest - module ever in Drupal hiarticle - '] = 'pathauto-greatest-module-ever';
     // Test that HTML tags are removed.
     $tests['This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.'] = 'text-has-html-tags';
     $tests[(string) SafeMarkup::checkPlain('This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.')] = 'text-has-html-tags';
     // Transliteration.
     $tests['ľščťžýáíéňô'] = 'lsctzyaieno';
     foreach ($tests as $input => $expected) {
         $output = \Drupal::service('pathauto.manager')->cleanString($input);
         $this->assertEqual($output, $expected, t("Drupal::service('pathauto.manager')->cleanString('@input') expected '@expected', actual '@output'", array('@input' => $input, '@expected' => $expected, '@output' => $output)));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
 {
     /* @var $instance \Drupal\mailchimp_lists\Plugin\Field\FieldType\MailchimpListsSubscription */
     $instance = $items[0];
     $subscribe_default = $instance->getSubscribe();
     $email = NULL;
     if (!empty($instance->getEntity())) {
         $email = mailchimp_lists_load_email($instance, $instance->getEntity(), FALSE);
         if ($email) {
             $subscribe_default = mailchimp_is_subscribed($instance->getFieldDefinition()->getSetting('mc_list_id'), $email);
         }
     }
     $element += array('#title' => SafeMarkup::checkPlain($element['#title']), '#type' => 'fieldset');
     $element['subscribe'] = array('#title' => t('Subscribe'), '#type' => 'checkbox', '#default_value' => $subscribe_default ? TRUE : $this->fieldDefinition->isRequired(), '#required' => $this->fieldDefinition->isRequired(), '#disabled' => $this->fieldDefinition->isRequired());
     $form_id = $form_state->getFormObject()->getFormId();
     if ($this->fieldDefinition->getSetting('show_interest_groups') || $form_id == 'field_ui_field_edit_form') {
         $mc_list = mailchimp_get_list($instance->getFieldDefinition()->getSetting('mc_list_id'));
         $element['interest_groups'] = array('#type' => 'fieldset', '#title' => SafeMarkup::checkPlain($instance->getFieldDefinition()->getSetting('interest_groups_title')), '#weight' => 100, '#states' => array('invisible' => array(':input[name="' . $instance->getFieldDefinition()->getName() . '[0][value][subscribe]"]' => array('checked' => FALSE))));
         if ($form_id == 'field_ui_field_edit_form') {
             $element['interest_groups']['#states']['invisible'] = array(':input[name="field[settings][show_interest_groups]"]' => array('checked' => FALSE));
         }
         $groups_default = $instance->getInterestGroups();
         if ($groups_default == NULL) {
             $groups_default = array();
         }
         if ($mc_list['stats']['group_count']) {
             $element['interest_groups'] += mailchimp_interest_groups_form_elements($mc_list, $groups_default, $email);
         }
     }
     return array('value' => $element);
 }
 /**
  * Checks that configuration complies with its schema on config save.
  *
  * @param \Drupal\Core\Config\ConfigCrudEvent $event
  *   The configuration event.
  *
  * @throws \Drupal\Core\Config\Schema\SchemaIncompleteException
  *   Exception thrown when configuration does not match its schema.
  */
 public function onConfigSave(ConfigCrudEvent $event)
 {
     // Only validate configuration if in the default collection. Other
     // collections may have incomplete configuration (for example language
     // overrides only). These are not valid in themselves.
     $saved_config = $event->getConfig();
     if ($saved_config->getStorage()->getCollectionName() != StorageInterface::DEFAULT_COLLECTION) {
         return;
     }
     $name = $saved_config->getName();
     $data = $saved_config->get();
     $checksum = hash('crc32b', serialize($data));
     $exceptions = array('config_schema_test.noschema', 'config_schema_test.someschema', 'config_schema_test.schema_data_types', 'config_schema_test.no_schema_data_types', 'config_test.dynamic.system');
     if (!in_array($name, $exceptions) && !isset($this->checked[$name . ':' . $checksum])) {
         $this->checked[$name . ':' . $checksum] = TRUE;
         $errors = $this->checkConfigSchema($this->typedManager, $name, $data);
         if ($errors === FALSE) {
             throw new SchemaIncompleteException("No schema for {$name}");
         } elseif (is_array($errors)) {
             $text_errors = [];
             foreach ($errors as $key => $error) {
                 $text_errors[] = SafeMarkup::format('@key @error', array('@key' => $key, '@error' => $error));
             }
             throw new SchemaIncompleteException("Schema errors for {$name} with the following errors: " . implode(', ', $text_errors));
         }
     }
 }
示例#26
0
 /**
  * Tests the menu functionality.
  */
 function testMenus()
 {
     $this->drupalPlaceBlock('system_menu_block:main');
     // Create a view with a page display and a menu link in the Main Menu.
     $view = array();
     $view['label'] = $this->randomMachineName(16);
     $view['id'] = strtolower($this->randomMachineName(16));
     $view['description'] = $this->randomMachineName(16);
     $view['page[create]'] = 1;
     $view['page[title]'] = $this->randomMachineName(16);
     $view['page[path]'] = $this->randomMachineName(16);
     $view['page[link]'] = 1;
     $view['page[link_properties][menu_name]'] = 'main';
     $view['page[link_properties][title]'] = $this->randomMachineName(16);
     $this->drupalPostForm('admin/structure/views/add', $view, t('Save and edit'));
     // Make sure there is a link to the view from the front page (where we
     // expect the main menu to display).
     $this->drupalGet('');
     $this->assertResponse(200);
     $this->assertLink($view['page[link_properties][title]']);
     $this->assertLinkByHref(Url::fromUri('base:' . $view['page[path]'])->toString());
     // Make sure the link is associated with the main menu.
     /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
     $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
     /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
     $link = $menu_link_manager->createInstance('views_view:views.' . $view['id'] . '.page_1');
     $url = $link->getUrlObject();
     $this->assertEqual($url->getRouteName(), 'view.' . $view['id'] . '.page_1', SafeMarkup::format('Found a link to %path in the main menu', array('%path' => $view['page[path]'])));
     $metadata = $link->getMetaData();
     $this->assertEqual(array('view_id' => $view['id'], 'display_id' => 'page_1'), $metadata);
 }
 /**
  * Assert sorting by field and property.
  */
 public function testSort()
 {
     // Add text field to entity, to sort by.
     entity_create('field_storage_config', array('field_name' => 'field_text', 'entity_type' => 'node', 'type' => 'text', 'entity_types' => array('node')))->save();
     entity_create('field_config', array('label' => 'Text Field', 'field_name' => 'field_text', 'entity_type' => 'node', 'bundle' => 'article', 'settings' => array(), 'required' => FALSE))->save();
     // Build a set of test data.
     $node_values = array('published1' => array('type' => 'article', 'status' => 1, 'title' => 'Node published1 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 1))), 'published2' => array('type' => 'article', 'status' => 1, 'title' => 'Node published2 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 2))));
     $nodes = array();
     $node_labels = array();
     foreach ($node_values as $key => $values) {
         $node = Node::create($values);
         $node->save();
         $nodes[$key] = $node;
         $node_labels[$key] = SafeMarkup::checkPlain($node->label());
     }
     $selection_options = array('target_type' => 'node', 'handler' => 'default', 'handler_settings' => array('target_bundles' => array(), 'sort' => array('field' => 'field_text.value', 'direction' => 'DESC')));
     $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);
     // Not only assert the result, but make sure the keys are sorted as
     // expected.
     $result = $handler->getReferenceableEntities();
     $expected_result = array($nodes['published2']->id() => $node_labels['published2'], $nodes['published1']->id() => $node_labels['published1']);
     $this->assertIdentical($result['article'], $expected_result, 'Query sorted by field returned expected values.');
     // Assert sort by base field.
     $selection_options['handler_settings']['sort'] = array('field' => 'nid', 'direction' => 'ASC');
     $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);
     $result = $handler->getReferenceableEntities();
     $expected_result = array($nodes['published1']->id() => $node_labels['published1'], $nodes['published2']->id() => $node_labels['published2']);
     $this->assertIdentical($result['article'], $expected_result, 'Query sorted by property returned expected values.');
 }
 public function testFileParsing()
 {
     $filename = drupal_get_path('module', 'locale') . '/tests/locale_test.js';
     // Parse the file to look for source strings.
     _locale_parse_js_file($filename);
     // Get all of the source strings that were found.
     $strings = $this->container->get('locale.storage')->getStrings(array('type' => 'javascript', 'name' => $filename));
     $source_strings = array();
     foreach ($strings as $string) {
         $source_strings[$string->source] = $string->context;
     }
     $etx = LOCALE_PLURAL_DELIMITER;
     // List of all strings that should be in the file.
     $test_strings = array('Standard Call t' => '', 'Whitespace Call t' => '', 'Single Quote t' => '', "Single Quote \\'Escaped\\' t" => '', 'Single Quote Concat strings t' => '', 'Double Quote t' => '', "Double Quote \\\"Escaped\\\" t" => '', 'Double Quote Concat strings t' => '', 'Context !key Args t' => 'Context string', 'Context Unquoted t' => 'Context string unquoted', 'Context Single Quoted t' => 'Context string single quoted', 'Context Double Quoted t' => 'Context string double quoted', "Standard Call plural{$etx}Standard Call @count plural" => '', "Whitespace Call plural{$etx}Whitespace Call @count plural" => '', "Single Quote plural{$etx}Single Quote @count plural" => '', "Single Quote \\'Escaped\\' plural{$etx}Single Quote \\'Escaped\\' @count plural" => '', "Double Quote plural{$etx}Double Quote @count plural" => '', "Double Quote \\\"Escaped\\\" plural{$etx}Double Quote \\\"Escaped\\\" @count plural" => '', "Context !key Args plural{$etx}Context !key Args @count plural" => 'Context string', "Context Unquoted plural{$etx}Context Unquoted @count plural" => 'Context string unquoted', "Context Single Quoted plural{$etx}Context Single Quoted @count plural" => 'Context string single quoted', "Context Double Quoted plural{$etx}Context Double Quoted @count plural" => 'Context string double quoted');
     // Assert that all strings were found properly.
     foreach ($test_strings as $str => $context) {
         $args = array('%source' => $str, '%context' => $context);
         // Make sure that the string was found in the file.
         $this->assertTrue(isset($source_strings[$str]), SafeMarkup::format('Found source string: %source', $args));
         // Make sure that the proper context was matched.
         $message = $context ? SafeMarkup::format('Context for %source is %context', $args) : SafeMarkup::format('Context for %source is blank', $args);
         $this->assertTrue(isset($source_strings[$str]) && $source_strings[$str] === $context, $message);
     }
     $this->assertEqual(count($source_strings), count($test_strings), 'Found correct number of source strings.');
 }
示例#29
0
 /**
  * Adds a language.
  *
  * @param string $langcode
  *   The language code of the language to add.
  */
 protected function addLanguage($langcode)
 {
     $edit = array('predefined_langcode' => $langcode);
     $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
     $this->container->get('language_manager')->reset();
     $this->assertTrue(\Drupal::languageManager()->getLanguage($langcode), SafeMarkup::format('Language %langcode added.', array('%langcode' => $langcode)));
 }
 /**
  * {@inheritdoc}
  */
 public function viewElements(FieldItemListInterface $items)
 {
     $elements = array();
     $output_as_link = $this->getSetting('link');
     foreach ($this->getEntitiesToView($items) as $delta => $entity) {
         $label = $entity->label();
         // If the link is to be displayed and the entity has a uri, display a
         // link.
         if ($output_as_link && !$entity->isNew()) {
             try {
                 $uri = $entity->urlInfo();
             } catch (UndefinedLinkTemplateException $e) {
                 // This exception is thrown by \Drupal\Core\Entity\Entity::urlInfo()
                 // and it means that the entity type doesn't have a link template nor
                 // a valid "uri_callback", so don't bother trying to output a link for
                 // the rest of the referenced entities.
                 $output_as_link = FALSE;
             }
         }
         if ($output_as_link && isset($uri) && !$entity->isNew()) {
             $elements[$delta] = ['#type' => 'link', '#title' => $label, '#url' => $uri, '#options' => $uri->getOptions()];
             if (!empty($items[$delta]->_attributes)) {
                 $elements[$delta]['#options'] += array('attributes' => array());
                 $elements[$delta]['#options']['attributes'] += $items[$delta]->_attributes;
                 // Unset field item attributes since they have been included in the
                 // formatter output and shouldn't be rendered in the field template.
                 unset($items[$delta]->_attributes);
             }
         } else {
             $elements[$delta] = array('#markup' => SafeMarkup::checkPlain($label));
         }
         $elements[$delta]['#cache']['tags'] = $entity->getCacheTags();
     }
     return $elements;
 }