/** * Tests tablesort_init(). */ function testTableSortInit() { // Test simple table headers. $headers = array('foo', 'bar', 'baz'); // Reset $request->query to prevent parameters from Simpletest and Batch API // ending up in $ts['query']. $expected_ts = array('name' => 'foo', 'sql' => '', 'sort' => 'asc', 'query' => array()); $request = Request::createFromGlobals(); $request->query->replace(array()); \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => Html::escape(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Simple table headers sorted correctly.'); // Test with simple table headers plus $_GET parameters that should _not_ // override the default. $request = Request::createFromGlobals(); $request->query->replace(array('order' => 'bar')); \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => Html::escape(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Simple table headers plus non-overriding $_GET parameters sorted correctly.'); // Test with simple table headers plus $_GET parameters that _should_ // override the default. $request = Request::createFromGlobals(); $request->query->replace(array('sort' => 'DESC', 'alpha' => 'beta')); \Drupal::getContainer()->get('request_stack')->push($request); $expected_ts['sort'] = 'desc'; $expected_ts['query'] = array('alpha' => 'beta'); $ts = tablesort_init($headers); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => Html::escape(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Simple table headers plus $_GET parameters sorted correctly.'); // Test complex table headers. $headers = array('foo', array('data' => '1', 'field' => 'one', 'sort' => 'asc', 'colspan' => 1), array('data' => '2', 'field' => 'two', 'sort' => 'desc')); // Reset $_GET from previous assertion. $request = Request::createFromGlobals(); $request->query->replace(array('order' => '2')); \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $expected_ts = array('name' => '2', 'sql' => 'two', 'sort' => 'desc', 'query' => array()); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => Html::escape(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Complex table headers sorted correctly.'); // Test complex table headers plus $_GET parameters that should _not_ // override the default. $request = Request::createFromGlobals(); $request->query->replace(array('order' => 'bar')); \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $expected_ts = array('name' => '1', 'sql' => 'one', 'sort' => 'asc', 'query' => array()); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => Html::escape(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Complex table headers plus non-overriding $_GET parameters sorted correctly.'); // Test complex table headers plus $_GET parameters that _should_ // override the default. $request = Request::createFromGlobals(); $request->query->replace(array('order' => '1', 'sort' => 'ASC', 'alpha' => 'beta')); \Drupal::getContainer()->get('request_stack')->push($request); $expected_ts = array('name' => '1', 'sql' => 'one', 'sort' => 'asc', 'query' => array('alpha' => 'beta')); $ts = tablesort_init($headers); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => Html::escape(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Complex table headers plus $_GET parameters sorted correctly.'); }
/** * Tests the generation of all system site information tokens. */ public function testSystemSiteTokenReplacement() { $url_options = array('absolute' => TRUE, 'language' => $this->interfaceLanguage); $slogan = '<blink>Slogan</blink>'; $safe_slogan = Xss::filterAdmin($slogan); // Set a few site variables. $config = $this->config('system.site'); $config->set('name', '<strong>Drupal<strong>')->set('slogan', $slogan)->set('mail', '*****@*****.**')->save(); // Generate and test tokens. $tests = array(); $tests['[site:name]'] = Html::escape($config->get('name')); $tests['[site:slogan]'] = $safe_slogan; $tests['[site:mail]'] = $config->get('mail'); $tests['[site:url]'] = \Drupal::url('<front>', [], $url_options); $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', \Drupal::url('<front>', [], $url_options)); $tests['[site:login-url]'] = \Drupal::url('user.page', [], $url_options); $base_bubbleable_metadata = new BubbleableMetadata(); $metadata_tests = []; $metadata_tests['[site:name]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site')); $metadata_tests['[site:slogan]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site')); $metadata_tests['[site:mail]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site')); $bubbleable_metadata = clone $base_bubbleable_metadata; $metadata_tests['[site:url]'] = $bubbleable_metadata->addCacheContexts(['url.site']); $metadata_tests['[site:url-brief]'] = $bubbleable_metadata; $metadata_tests['[site:login-url]'] = $bubbleable_metadata; // 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) { $bubbleable_metadata = new BubbleableMetadata(); $output = $this->tokenService->replace($input, array(), array('langcode' => $this->interfaceLanguage->getId()), $bubbleable_metadata); $this->assertEqual($output, $expected, new FormattableMarkup('System site information token %token replaced.', ['%token' => $input])); $this->assertEqual($bubbleable_metadata, $metadata_tests[$input]); } }
/** * 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>' . Html::escape($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'); }
/** * 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'] === Html::escape($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()))); }
/** * Test for autocomplete processing. * * Tests that processing does not crash when the entity types of the * referenced entity and of the entity the field is attached to are different. */ public function testEntityReferenceRevisionsAutocompleteProcessing() { $admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer nodes', 'administer blocks', 'create article content', 'administer content types', 'administer node fields', 'administer node display', 'administer node form display', 'edit any article content')); $this->drupalLogin($admin_user); // Create a custom block content bundle. $this->createBlockContentType(array('type' => 'customblockcontent', 'name' => 'Custom Block Content')); // Create entity reference revisions field attached to article. static::fieldUIAddNewField('admin/structure/types/manage/article', 'entity_reference_revisions', 'Entity reference revisions', 'entity_reference_revisions', array('settings[target_type]' => 'block_content', 'cardinality' => '-1'), array('settings[handler_settings][target_bundles][customblockcontent]' => TRUE)); // Create custom block. $block_label = $this->randomMachineName(); $block_content = $this->randomString(); $edit = array('info[0][value]' => $block_label, 'body[0][value]' => $block_content, 'revision' => TRUE); $this->drupalPostForm('block/add', $edit, t('Save')); $block = $this->drupalGetBlockByInfo($block_label); // Create an article. $title = $this->randomMachineName(); $edit = array('title[0][value]' => $title, 'body[0][value]' => 'Revision 1', 'field_entity_reference_revisions[0][target_id]' => $block_label . ' (' . $block->id() . ')', 'revision' => TRUE); $this->drupalPostForm('node/add/article', $edit, t('Save and publish')); $this->assertText($title); $this->assertText(Html::escape($block_content)); // Check if the block content is not deleted since there is no composite // relationship. $node = $this->drupalGetNodeByTitle($edit['title[0][value]']); $node = Node::load($node->id()); $node->delete(); $this->assertNotNull(BlockContent::load($block->id())); }
/** * 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] = Html::escape($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.'); }
/** * 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[Html::escape('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.alias_cleaner')->cleanString($input); $this->assertEqual($output, $expected, t("Drupal::service('pathauto.alias_cleaner')->cleanString('@input') expected '@expected', actual '@output'", array('@input' => $input, '@expected' => $expected, '@output' => $output))); } }
/** * 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()); } }
/** * {@inheritdoc} */ public function buildOptionsForm(&$form, FormStateInterface $form_state) { parent::buildOptionsForm($form, $form_state); $form['help']['#markup'] = Html::escape($this->t('Note: You can change how search keys are parsed under "Advanced" > "Query settings".')); $fields = $this->getFulltextFields(); if (!empty($fields)) { $form['fields'] = array( '#type' => 'select', '#title' => $this->t('Searched fields'), '#description' => $this->t('Select the fields that will be searched. If no fields are selected, all available fulltext fields will be searched.'), '#options' => $fields, '#size' => min(4, count($fields)), '#multiple' => TRUE, '#default_value' => $this->options['fields'], ); $form['conjunction'] = array( '#title' => $this->t('Operator'), '#description' => $this->t('Determines how multiple keywords entered for the search will be combined.'), '#type' => 'radios', '#options' => array( 'AND' => $this->t('Contains all of these words'), 'OR' => $this->t('Contains any of these words'), ), '#default_value' => $this->options['conjunction'], ); } else { $form['fields'] = array( '#type' => 'value', '#value' => array(), ); } }
/** * Returns a string representation of the attribute. * * While __toString only returns the value in a string form, render() * contains the name of the attribute as well. * * @return string * The string representation of the attribute. */ public function render() { $value = (string) $this; if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) { return Html::escape($this->name) . '="' . $value . '"'; } }
/** * Test a gallery embedded in a view row that is dependent on the Juicebox * cache. */ public function testSubRequestDependent() { $node = $this->node; $xml_path = 'juicebox/xml/field/node/' . $node->id() . '/' . $this->instFieldName . '/_custom'; $xml_url = \Drupal::url('juicebox.xml_field', array('entityType' => 'node', 'entityId' => $node->id(), 'fieldName' => $this->instFieldName, 'displayName' => '_custom')); // Get the urls to the test image and thumb derivative used by default. $uri = \Drupal\file\Entity\File::load($node->{$this->instFieldName}[0]->target_id)->getFileUri(); $test_image_url = entity_load('image_style', 'juicebox_medium')->buildUrl($uri); $test_thumb_url = entity_load('image_style', 'juicebox_square_thumb')->buildUrl($uri); // Check for correct embed markup. This will also prime the cache. $content = $this->drupalGet('juicebox_test_row_formatter'); $this->assertRaw(trim(json_encode(array('configUrl' => $xml_url)), '{}"'), 'Gallery setting found in Drupal.settings.'); $this->assertRaw('id="node--' . $node->id() . '--' . str_replace('_', '-', $this->instFieldName) . '---custom"', 'Embed code wrapper found.'); $this->assertRaw(Html::escape($test_image_url), 'Test image found in embed code'); // Extract the xml-source values from the XML. $matches = array(); // In the pattern below we have to use four (yeah, FOUR) backslashes to // match a SINGLE literal backslash. Our source will contain an encoded // (JSON) "&" character as "\u0026", but we don't want the regex to confuse // that with an actaul "&" char in the pattern itself. preg_match('|xml-source-path=([a-z1-9_-]+)\\\\u0026xml-source-id=([a-z1-9-]+)|', $content, $matches); $this->assertNotNull($matches[1], 'xml-source-path value found in Drupal.settings.'); $this->assertNotNull($matches[2], 'xml-source-id value found in Drupal.settings.'); // Check for correct XML. This example is dependent on a sub-request XML // lookup, so everything below would fail without that feature. $this->drupalGet($xml_path, array('query' => array('xml-source-path' => $matches[1], 'xml-source-id' => $matches[2]))); $this->assertRaw('<?xml version="1.0" encoding="UTF-8"?>', 'Valid XML detected.'); $this->assertRaw('imageURL="' . Html::escape($test_image_url), 'Test image found in XML.' . $test_image_url); $this->assertRaw('thumbURL="' . Html::escape($test_thumb_url), 'Test thumbnail found in XML.' . $test_thumb_url); $this->assertRaw('backgroundcolor="green"', 'Custom background setting from pseudo field instance config found in XML.'); }
/** * Lists all instances of fields on any views. * * @return array * The Views fields report page. */ public function nodeMarkup($node, $key = 'default') { $node = Node::load($node); $builded_entity = entity_view($node, $key); $markup = drupal_render($builded_entity); $links = array(); $links['default'] = array( 'title' => 'Default', 'url' => Url::fromRoute('ds_devel.markup', array('node' => $node->id())), ); $view_modes = \Drupal::entityManager()->getViewModes('node'); foreach ($view_modes as $id => $info) { if (!empty($info['status'])) { $links[] = array( 'title' => $info['label'], 'url' => Url::fromRoute('ds_devel.markup_view_mode', array('node' => $node->id(), 'key' => $id)), ); } } $build['links'] = array( '#theme' => 'links', '#links' => $links, '#prefix' => '<div>', '#suffix' => '</div><hr />', ); $build['markup'] = [ '#markup' => '<code><pre>' . Html::escape($markup) . '</pre></code>', '#allowed_tags' => ['code', 'pre'], ]; return $build; }
/** * Get album images by $node->id(). * @todo move function so it is easily accessible. */ public function getAlbumImages($nid, $limit = 10) { $images = array(); $column = isset($_GET['field']) ? \Drupal\Component\Utility\Html::escape($_GET['field']) : ''; $sort = isset($_GET['sort']) ? \Drupal\Component\Utility\Html::escape($_GET['sort']) : ''; $term = _photos_order_value($column, $sort, $limit, array('column' => 'p.wid', 'sort' => 'asc')); $query = db_select('file_managed', 'f') ->extend('Drupal\Core\Database\Query\PagerSelectExtender'); $query->join('photos_image', 'p', 'p.fid = f.fid'); $query->join('users_field_data', 'u', 'f.uid = u.uid'); $query->join('node', 'n', 'n.nid = p.pid'); $query->fields('f', array('uri', 'filemime', 'created', 'filename', 'filesize')); $query->fields('p'); $query->fields('u', array('uid', 'name')); $query->condition('p.pid', $nid); $query->limit($term['limit']); $query->orderBy($term['order']['column'], $term['order']['sort']); $query->addTag('node_access'); $result = $query->execute(); foreach ($result as $data) { // @todo create new function to return image object. $images[] = photos_get_info(0, $data); } if (isset($images[0]->fid)) { $node = \Drupal::entityManager()->getStorage('node')->load($nid); $images[0]->info = array( 'pid' => $node->id(), 'title' => $node->getTitle(), 'uid' => $node->getOwnerId() ); if (isset($node->album['cover'])) { $images[0]->info['cover'] = $node->album['cover']; } } return $images; }
/** * Retrieves an options list of available trackers. * * @return string[] * An associative array mapping the IDs of all available tracker plugins to * their labels. */ public function getOptionsList() { $options = array(); foreach ($this->getDefinitions() as $plugin_id => $plugin_definition) { $options[$plugin_id] = Html::escape($plugin_definition['label']); } return $options; }
/** * Tests the autocomplete method. * * @param string $string * The string entered into the autocomplete. * @param array $suggestions * The array of expected suggestions. * * @see \Drupal\block\Controller\CategoryAutocompleteController::autocomplete() * * @dataProvider providerTestAutocompleteSuggestions */ public function testAutocompleteSuggestions($string, $suggestions) { $suggestions = array_map(function ($suggestion) { return array('value' => $suggestion, 'label' => Html::escape($suggestion)); }, $suggestions); $result = $this->autocompleteController->autocomplete(new Request(array('q' => $string))); $this->assertSame($suggestions, json_decode($result->getContent(), TRUE)); }
/** * Asserts that an array of elements is rendered properly. * * @param array $elements * The render element array to test. * @param string $expected_html * The expected markup. * @param string $message * Assertion message. */ protected function assertElements(array $elements, $expected_html, $message) { $actual_html = (string) \Drupal::service('renderer')->renderRoot($elements); $out = '<table><tr>'; $out .= '<td valign="top"><pre>' . Html::escape($expected_html) . '</pre></td>'; $out .= '<td valign="top"><pre>' . Html::escape($actual_html) . '</pre></td>'; $out .= '</tr></table>'; $this->verbose($out); $this->assertIdentical($actual_html, $expected_html, Html::escape($message)); }
/** * Validates the language editing element. */ public function validateCommon(array $form, FormStateInterface $form_state) { // Ensure sane field values for langcode and name. if (!isset($form['langcode_view']) && !preg_match('@^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$@', $form_state->getValue('langcode'))) { $form_state->setErrorByName('langcode', $this->t('%field must be a valid language tag as <a href=":url">defined by the W3C</a>.', array('%field' => $form['langcode']['#title'], ':url' => 'http://www.w3.org/International/articles/language-tags/'))); } if ($form_state->getValue('label') != Html::escape($form_state->getValue('label'))) { $form_state->setErrorByName('label', $this->t('%field cannot contain any markup.', array('%field' => $form['label']['#title']))); } }
/** * Returns a block theme demo page. * * @param string $theme * The name of the theme. * * @return array * A #type 'page' render array containing the block region demo. */ public function demo($theme) { $page = ['#title' => Html::escape($this->themeHandler->getName($theme)), '#type' => 'page', '#attached' => array('drupalSettings' => ['path' => ['currentPathIsAdmin' => TRUE]], 'library' => array('block/drupal.block.admin'))]; // Show descriptions in each visible page region, nothing else. $visible_regions = $this->getVisibleRegionNames($theme); foreach (array_keys($visible_regions) as $region) { $page[$region]['block_description'] = array('#type' => 'inline_template', '#template' => '<div class="block-region demo-block">{{ region_name }}</div>', '#context' => array('region_name' => $visible_regions[$region])); } return $page; }
/** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $form = parent::buildConfigurationForm($form, $form_state); $options = array_map(function (RoleInterface $role) { return Html::escape($role->label()); }, user_roles()); $form['default'] = array('#type' => 'radios', '#title' => $this->t('Which users should be indexed?'), '#default_value' => $this->configuration['default'], '#options' => array(1 => $this->t('All but those from one of the selected roles'), 0 => $this->t('Only those from the selected roles'))); $form['roles'] = array('#type' => 'select', '#title' => $this->t('Roles'), '#default_value' => array_combine($this->configuration['roles'], $this->configuration['roles']), '#options' => $options, '#size' => min(4, count($options)), '#multiple' => TRUE); return $form; }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items) { $elements = array(); foreach ($items as $delta => $item) { // The text value has no text format assigned to it, so the user input // should equal the output, including newlines. $elements[$delta] = array('#markup' => nl2br(Html::escape($item->value))); } return $elements; }
/** * Tests an import with an incomplete rewinding. */ public function testImportWithFailingRewind() { $exception_message = $this->getRandomGenerator()->string(); $source = $this->getMock('Drupal\\migrate\\Plugin\\MigrateSourceInterface'); $source->expects($this->once())->method('rewind')->will($this->throwException(new \Exception($exception_message))); $this->migration->expects($this->any())->method('getSourcePlugin')->will($this->returnValue($source)); // Ensure that a message with the proper message was added. $this->message->expects($this->once())->method('display')->with("Migration failed with source plugin exception: " . Html::escape($exception_message)); $result = $this->executable->import(); $this->assertEquals(MigrationInterface::RESULT_FAILED, $result); }
/** * Retrieves suggestions for block category autocompletion. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return \Symfony\Component\HttpFoundation\JsonResponse * A JSON response containing autocomplete suggestions. */ public function autocomplete(Request $request) { $typed_category = $request->query->get('q'); $matches = array(); foreach ($this->blockManager->getCategories() as $category) { if (stripos($category, $typed_category) === 0) { $matches[] = array('value' => $category, 'label' => Html::escape($category)); } } return new JsonResponse($matches); }
/** * @file * Save Breadcrumb CSS to file */ function at_core_submit_breadcrumb($values, $theme, $generated_files_path) { $breadcrumb_css = ''; if (!empty($values['settings_breadcrumb_separator'])) { $css = '.breadcrumb li:before {content: "' . Html::escape($values['settings_breadcrumb_separator']) . '"}'; } if (!empty($css)) { $file_name = 'breadcrumb.css'; $filepath = $generated_files_path . '/' . $file_name; file_unmanaged_save_data($css, $filepath, FILE_EXISTS_REPLACE); } }
public function submitForm(array &$form, FormStateInterface $form_state) { if (isset($form)) { if (isset($form['#token'])) { $collection_name = Html::escape($form['searchblox_collection']['#value']); \Drupal::state()->set('searchblox_collection', $collection_name); $response = new RedirectResponse(\Drupal::url('searchblox.step3')); $response->send(); return; } } }
function testFieldFormSingle() { $field_storage = $this->fieldStorageSingle; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; entity_create('field_storage_config', $field_storage)->save(); entity_create('field_config', $this->field)->save(); entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')->setComponent($field_name)->save(); // Display creation form. $this->drupalGet('entity_test/add'); // Create token value expected for description. $token_description = Html::escape($this->config('system.site')->get('name')) . '_description'; $this->assertText($token_description, 'Token replacement for description is displayed'); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed'); $this->assertNoField("{$field_name}[1][value]", 'No extraneous widget is displayed'); // Check that hook_field_widget_form_alter() does not believe this is the // default value form. $this->assertNoText('From hook_field_widget_form_alter(): Default form is true.', 'Not default value form in hook_field_widget_form_alter().'); // Submit with invalid value (field-level validation). $edit = array("{$field_name}[0][value]" => -1); $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $this->field['label'])), 'Field validation fails with invalid input.'); // TODO : check that the correct field is flagged for error. // Create an entity $value = mt_rand(1, 127); $edit = array("{$field_name}[0][value]" => $value); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created'); $entity = entity_load('entity_test', $id); $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was saved'); // Display edit form. $this->drupalGet('entity_test/manage/' . $id . '/edit'); $this->assertFieldByName("{$field_name}[0][value]", $value, 'Widget is displayed with the correct default value'); $this->assertNoField("{$field_name}[1][value]", 'No extraneous widget is displayed'); // Update the entity. $value = mt_rand(1, 127); $edit = array("{$field_name}[0][value]" => $value); $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText(t('entity_test @id has been updated.', array('@id' => $id)), 'Entity was updated'); $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id)); $entity = entity_load('entity_test', $id); $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was updated'); // Empty the field. $value = ''; $edit = array("{$field_name}[0][value]" => $value); $this->drupalPostForm('entity_test/manage/' . $id . '/edit', $edit, t('Save')); $this->assertText(t('entity_test @id has been updated.', array('@id' => $id)), 'Entity was updated'); $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id)); $entity = entity_load('entity_test', $id); $this->assertTrue($entity->{$field_name}->isEmpty(), 'Field was emptied'); }
/** * {@inheritdoc} */ public function cartDetails(OrderInterface $order, array $form, FormStateInterface $form_state) { $build['#attached']['library'][] = 'uc_payment_pack/cod.styles'; $build['policy'] = array('#prefix' => '<p>', '#markup' => Html::escape($this->configuration['policy']), '#suffix' => '</p>'); if (($max = $this->configuration['max_order']) > 0 && is_numeric($max)) { $build['eligibility'] = array('#prefix' => '<p>', '#markup' => $this->t('Orders totalling more than @amount are <b>not eligible</b> for COD.', ['@amount' => uc_currency_format($max)]), '#suffix' => '</p>'); } if ($this->configuration['delivery_date']) { $build += $this->deliveryDateForm($order); } return $build; }
/** * Tests the generation of all system site information tokens. */ public function testSystemSiteTokenReplacement() { // The use of the \Drupal::url() method requires the url_alias table to exist. $this->installSchema('system', 'url_alias'); $url_options = array('absolute' => TRUE, 'language' => $this->interfaceLanguage); $slogan = '<blink>Slogan</blink>'; $safe_slogan = Xss::filterAdmin($slogan); // Set a few site variables. $config = $this->config('system.site'); $config->set('name', '<strong>Drupal<strong>')->set('slogan', $slogan)->set('mail', '*****@*****.**')->save(); // Generate and test sanitized tokens. $tests = array(); $tests['[site:name]'] = Html::escape($config->get('name')); $tests['[site:slogan]'] = $safe_slogan; $tests['[site:mail]'] = $config->get('mail'); $tests['[site:url]'] = \Drupal::url('<front>', [], $url_options); $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', \Drupal::url('<front>', [], $url_options)); $tests['[site:login-url]'] = \Drupal::url('user.page', [], $url_options); $base_bubbleable_metadata = new BubbleableMetadata(); $metadata_tests = []; $metadata_tests['[site:name]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site')); $metadata_tests['[site:slogan]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site')); $metadata_tests['[site:mail]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site')); $bubbleable_metadata = clone $base_bubbleable_metadata; $metadata_tests['[site:url]'] = $bubbleable_metadata->addCacheContexts(['url.site']); $metadata_tests['[site:url-brief]'] = $bubbleable_metadata; $metadata_tests['[site:login-url]'] = $bubbleable_metadata; // 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) { $bubbleable_metadata = new BubbleableMetadata(); $output = $this->tokenService->replace($input, array(), array('langcode' => $this->interfaceLanguage->getId()), $bubbleable_metadata); $this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input))); $this->assertEqual($bubbleable_metadata, $metadata_tests[$input]); } // Generate and test unsanitized tokens. $tests['[site:name]'] = $config->get('name'); $tests['[site:slogan]'] = $config->get('slogan'); foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array(), array('langcode' => $this->interfaceLanguage->getId(), 'sanitize' => FALSE), $bubbleable_metadata); $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input))); } // Check that the results of Token::generate are sanitized properly. This // does NOT test the cleanliness of every token -- just that the $sanitize // flag is being passed properly through the call stack and being handled // correctly by a 'known' token, [site:slogan]. $raw_tokens = array('slogan' => '[site:slogan]'); $generated = $this->tokenService->generate('site', $raw_tokens, [], [], $bubbleable_metadata); $this->assertEqual($generated['[site:slogan]'], $safe_slogan, 'Token sanitized.'); $generated = $this->tokenService->generate('site', $raw_tokens, array(), array('sanitize' => FALSE), $bubbleable_metadata); $this->assertEqual($generated['[site:slogan]'], $slogan, 'Unsanitized token generated properly.'); }
/** * Tests the permission filter handler. * * @todo Fix the different commented out tests by fixing the many to one * handler handling with the NOT operator. */ public function testFilterPermission() { $this->setupPermissionTestData(); $column_map = array('uid' => 'uid'); $view = Views::getView('test_filter_permission'); // Filter by a non existing permission. $view->initHandlers(); $view->filter['permission']->value = array('non_existent_permission'); $this->executeView($view); $this->assertEqual(count($view->result), 4, 'A non existent permission is not filtered so everything is the result.'); $expected[] = array('uid' => 1); $expected[] = array('uid' => 2); $expected[] = array('uid' => 3); $expected[] = array('uid' => 4); $this->assertIdenticalResultset($view, $expected, $column_map); $view->destroy(); // Filter by a permission. $view->initHandlers(); $view->filter['permission']->value = array('administer permissions'); $this->executeView($view); $this->assertEqual(count($view->result), 2); $expected = array(); $expected[] = array('uid' => 3); $expected[] = array('uid' => 4); $this->assertIdenticalResultset($view, $expected, $column_map); $view->destroy(); // Filter by another permission of a role with multiple permissions. $view->initHandlers(); $view->filter['permission']->value = array('administer users'); $this->executeView($view); $this->assertEqual(count($view->result), 1); $expected = array(); $expected[] = array('uid' => 4); $this->assertIdenticalResultset($view, $expected, $column_map); $view->destroy(); $view->initDisplay(); $view->initHandlers(); $view->filter['permission']->getValueOptions(); // Test the value options. $value_options = $view->filter['permission']->getValueOptions(); $permission_by_module = []; $permissions = \Drupal::service('user.permissions')->getPermissions(); foreach ($permissions as $name => $permission) { $permission_by_module[$permission['provider']][$name] = $permission; } foreach (array('system' => 'System', 'user' => 'User') as $module => $title) { $expected = array_map(function ($permission) { return Html::escape(strip_tags($permission['title'])); }, $permission_by_module[$module]); $this->assertEqual($expected, $value_options[$title], 'Ensure the all permissions are available'); } }
/** * Helper function to test \Drupal\Core\Mail\MailFormatHelper::htmlToText(). * * @param $html * The source HTML string to be converted. * @param $text * The expected result of converting $html to text. * @param $message * A text message to display in the assertion message. * @param $allowed_tags * (optional) An array of allowed tags, or NULL to default to the full * set of tags supported by * \Drupal\Core\Mail\MailFormatHelper::htmlToText(). */ protected function assertHtmlToText($html, $text, $message, $allowed_tags = NULL) { preg_match_all('/<([a-z0-6]+)/', Unicode::strtolower($html), $matches); $tested_tags = implode(', ', array_unique($matches[1])); $message .= ' (' . $tested_tags . ')'; $result = MailFormatHelper::htmlToText($html, $allowed_tags); $pass = $this->assertEqual($result, $text, Html::escape($message)); $verbose = 'html = <pre>' . $this->stringToHtml($html) . '</pre><br />' . 'result = <pre>' . $this->stringToHtml($result) . '</pre><br />' . 'expected = <pre>' . $this->stringToHtml($text) . '</pre>'; $this->verbose($verbose); if (!$pass) { $this->pass("Previous test verbose info:<br />{$verbose}"); } }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $element = array(); $link = $this->getSetting('link'); foreach ($items as $delta => $item) { if ($link) { $element[$delta] = array('#type' => 'link', '#title' => $item->input, '#url' => Url::fromUri($item->input), '#options' => array('attributes' => array('class' => array('youtube-url', 'youtube-url--' . Html::getClass($item->video_id))), 'html' => TRUE)); } else { $element[$delta] = array('#markup' => Html::escape($item->input)); } } return $element; }