/** * {@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)))); }
/** * 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]))); } }
/** * 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)))); } }
/** * Creates a new entity * * @param string $entity_type * @param array $values * An array of settings. * Example: 'id' => 'foo'. * * @return \Drupal\Core\Entity\EntityInterface */ protected function createEntity($entity_type, $values) { $entity = \Drupal::service('entity_type.manager')->getStorage($entity_type)->create($values); $status = $entity->save(); $this->assertEqual($status, SAVED_NEW, SafeMarkup::format('Created %label entity %type.', ['%label' => $entity->getEntityType()->getLabel(), '%type' => $entity->id()])); return $entity; }
/** * Constructs a TargetValidationException object. * * @param string $message * The un-formatted message. * @param array $args * The formatting arguments. */ public function __construct($message = '', array $args = []) { $this->messageString = $message; $this->message = SafeMarkup::format($message, $args); $this->args = $args; $this->code = 0; }
/** * @covers ::validate */ public function testValidateNoMatchingFormats() { $this->filterUninstallValidator->expects($this->once())->method('getFilterDefinitionsByProvider')->willReturn(['test_filter_plugin1' => ['id' => 'test_filter_plugin1', 'provider' => 'filter_test'], 'test_filter_plugin2' => ['id' => 'test_filter_plugin2', 'provider' => 'filter_test'], 'test_filter_plugin3' => ['id' => 'test_filter_plugin3', 'provider' => 'filter_test'], 'test_filter_plugin4' => ['id' => 'test_filter_plugin4', 'provider' => 'filter_test']]); $filter_plugin_enabled = $this->getMockForAbstractClass('Drupal\\filter\\Plugin\\FilterBase', [['status' => TRUE], '', ['provider' => 'filter_test']]); $filter_plugin_disabled = $this->getMockForAbstractClass('Drupal\\filter\\Plugin\\FilterBase', [['status' => FALSE], '', ['provider' => 'filter_test']]); // The first format has 2 matching and enabled filters, but the loop breaks // after finding the first one. $filter_plugin_collection1 = $this->getMockBuilder('Drupal\\filter\\FilterPluginCollection')->disableOriginalConstructor()->getMock(); $filter_plugin_collection1->expects($this->exactly(3))->method('has')->willReturnMap([['test_filter_plugin1', FALSE], ['test_filter_plugin2', TRUE], ['test_filter_plugin3', TRUE], ['test_filter_plugin4', TRUE]]); $filter_plugin_collection1->expects($this->exactly(2))->method('get')->willReturnMap([['test_filter_plugin2', $filter_plugin_disabled], ['test_filter_plugin3', $filter_plugin_enabled], ['test_filter_plugin4', $filter_plugin_enabled]]); $filter_format1 = $this->getMock('Drupal\\filter\\FilterFormatInterface'); $filter_format1->expects($this->once())->method('filters')->willReturn($filter_plugin_collection1); $filter_format1->expects($this->once())->method('label')->willReturn('Filter Format 1 Label'); // The second filter format only has one matching and enabled filter. $filter_plugin_collection2 = $this->getMockBuilder('Drupal\\filter\\FilterPluginCollection')->disableOriginalConstructor()->getMock(); $filter_plugin_collection2->expects($this->exactly(4))->method('has')->willReturnMap([['test_filter_plugin1', FALSE], ['test_filter_plugin2', FALSE], ['test_filter_plugin3', FALSE], ['test_filter_plugin4', TRUE]]); $filter_plugin_collection2->expects($this->exactly(1))->method('get')->with('test_filter_plugin4')->willReturn($filter_plugin_enabled); $filter_format2 = $this->getMock('Drupal\\filter\\FilterFormatInterface'); $filter_format2->expects($this->once())->method('filters')->willReturn($filter_plugin_collection2); $filter_format2->expects($this->once())->method('label')->willReturn('Filter Format 2 Label'); $this->filterUninstallValidator->expects($this->once())->method('getEnabledFilterFormats')->willReturn(['test_filter_format1' => $filter_format1, 'test_filter_format2' => $filter_format2]); $expected = [SafeMarkup::format('Provides a filter plugin that is in use in the following filter formats: %formats', ['%formats' => implode(', ', ['Filter Format 1 Label', 'Filter Format 2 Label'])])]; $reasons = $this->filterUninstallValidator->validate($this->randomMachineName()); $this->assertSame($expected, $reasons); }
/** * {@inheritdoc} */ protected function doCreate(array $values) { // We have to determine the bundle first. $bundle = FALSE; if ($this->bundleKey) { if (!isset($values[$this->bundleKey])) { throw new EntityStorageException(SafeMarkup::format('Missing bundle for entity type @type', array('@type' => $this->entityTypeId))); } $bundle = $values[$this->bundleKey]; } $entity = new $this->entityClass(array(), $this->entityTypeId, $bundle); foreach ($entity as $name => $field) { if (isset($values[$name])) { $entity->{$name} = $values[$name]; } elseif (!array_key_exists($name, $values)) { $entity->get($name)->applyDefaultValue(); } unset($values[$name]); } // Set any passed values for non-defined fields also. foreach ($values as $name => $value) { $entity->{$name} = $value; } return $entity; }
/** * Tests fetchFields. */ public function testFetchFields() { $views_data = $this->getMockBuilder('Drupal\\views\\ViewsData')->disableOriginalConstructor()->getMock(); $views_data->expects($this->once())->method('get')->will($this->returnValue($this->viewsData())); $data_helper = new ViewsDataHelper($views_data); $expected = array('field' => array('age', 'created', 'job', 'name', 'status'), 'argument' => array('age', 'created', 'id', 'job'), 'filter' => array('created', 'id', 'job', 'name', 'status'), 'sort' => array('age', 'created', 'id', 'name', 'status'), 'area' => array('age', 'created', 'job'), 'header' => array('age', 'created', 'job'), 'footer' => array('age', 'created', 'job')); $handler_types = array('field', 'argument', 'filter', 'sort', 'area'); foreach ($handler_types as $handler_type) { $fields = $data_helper->fetchFields('views_test_data', $handler_type); $expected_keys = $expected[$handler_type]; array_walk($expected_keys, function (&$item) { $item = "views_test_data.{$item}"; }); $this->assertEquals($expected_keys, array_keys($fields), SafeMarkup::format('Handlers of type @handler_type are not listed as expected.', array('@handler_type' => $handler_type))); } // Check for subtype filtering, so header and footer. foreach (array('header', 'footer') as $sub_type) { $fields = $data_helper->fetchFields('views_test_data', 'area', FALSE, $sub_type); $expected_keys = $expected[$sub_type]; array_walk($expected_keys, function (&$item) { $item = "views_test_data.{$item}"; }); $this->assertEquals($expected_keys, array_keys($fields), SafeMarkup::format('Sub_type @sub_type is not filtered as expected.', array('@sub_type' => $sub_type))); } }
/** * {@inheritdoc} */ protected function validateArguments(array $arguments) { if (!in_array($arguments['extension'], $this->getToolkit()->getSupportedExtensions())) { throw new \InvalidArgumentException(SafeMarkup::format("Invalid extension (@value) specified for the image 'convert' operation", array('@value' => $arguments['extension']))); } return $arguments; }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); // Create user with content access permission to see if the view is // accessible. $this->authenticatedUser = $this->drupalCreateUser(); // Create "Article" and "Basic page" node bundles. $this->createNodeBundles(); try { // Install the module and also auto-enable the dependencies. $module = 'search_api_db_defaults'; $dependencies = $this->getModuleDependencies($module); $success = $this->container->get('module_installer')->install(array($module), TRUE); // Required after enabling a module using the module_installer service. $this->rebuildContainer(); // Assert if the module was successfully enabled. $this->assertTrue($success, SafeMarkup::format('Enabled search_api_db_defaults, including its dependencies: %modules', array('%modules' => implode(', ', $dependencies)))); } catch (UnmetDependenciesException $e) { // The exception message has all the details. $this->fail($e->getMessage()); } // Rebuild menu so our anonymous user can access the search view. $route_builder = $this->container->get('router.builder'); $route_builder->rebuild(); }
/** * 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']; } }
/** * 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); }
/** * 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 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])); } }
/** * 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))); } }
/** * 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()); } }
/** * 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']); } }
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.'); }
/** * Checks whether the request is not Soft Blocked. */ protected function assertNoSoftBlocked($account) { $this->drupalLoginLite($account); $this->assertNoText('This host is not allowed to log in', 'Soft-blocked notice does not display.'); $this->assertNoText(SafeMarkup::format('The user @user_name has been blocked due to failed login attempts.', ['@user_name' => $account->getUsername()]), 'User is not blocked.'); $this->assertFieldByName('form_id', 'user_login_form', 'Login form found.'); }
/** * {@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']]; } }
/** * 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']); } }
/** * {@inheritdoc} */ protected function validateArguments(array $arguments) { // Assure at least one dimension. if (empty($arguments['width']) && empty($arguments['height'])) { throw new \InvalidArgumentException("At least one dimension ('width' or 'height') must be provided to the image 'scale' operation"); } // Calculate one of the dimensions from the other target dimension, // ensuring the same aspect ratio as the source dimensions. If one of the // target dimensions is missing, that is the one that is calculated. If both // are specified then the dimension calculated is the one that would not be // calculated to be bigger than its target. $aspect = $this->getToolkit()->getHeight() / $this->getToolkit()->getWidth(); if ($arguments['width'] && !$arguments['height'] || $arguments['width'] && $arguments['height'] && $aspect < $arguments['height'] / $arguments['width']) { $arguments['height'] = (int) round($arguments['width'] * $aspect); } else { $arguments['width'] = (int) round($arguments['height'] / $aspect); } // Assure integers for all arguments. $arguments['width'] = (int) round($arguments['width']); $arguments['height'] = (int) round($arguments['height']); // Fail when width or height are 0 or negative. if ($arguments['width'] <= 0) { throw new \InvalidArgumentException(SafeMarkup::format("Invalid width (@value) specified for the image 'scale' operation", array('@value' => $arguments['width']))); } if ($arguments['height'] <= 0) { throw new \InvalidArgumentException(SafeMarkup::format("Invalid height (@value) specified for the image 'scale' operation", array('@value' => $arguments['height']))); } return $arguments; }
/** * 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]])); }
/** * 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()); }
/** * 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)); } } }
/** * 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.'); }
/** * Verifies that the default mobile meta tags can be removed. */ public function testRemovingDefaultMetaTags() { \Drupal::service('module_installer')->install(array('system_module_test')); $this->drupalGet(''); foreach ($this->defaultMetaTags as $name => $metatag) { $this->assertNoRaw($metatag, SafeMarkup::format('Default Mobile meta tag "@name" removed properly.', array('@name' => $name)), 'System'); } }
/** * Creates an exception for an extension and a list of configuration objects. * * @param $extension * The name of the extension that is being installed. * @param array $config_objects * A list of configuration objects that already exist in active * configuration, keyed by config collection. * * @return \Drupal\Core\Config\PreExistingConfigException */ public static function create($extension, array $config_objects) { $message = SafeMarkup::format('Configuration objects (@config_names) provided by @extension already exist in active configuration', array('@config_names' => implode(', ', static::flattenConfigObjects($config_objects)), '@extension' => $extension)); $e = new static($message); $e->configObjects = $config_objects; $e->extension = $extension; return $e; }
/** * {@inheritdoc} */ public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) { $ip = $request->getClientIp(); if ($this->banIpManager->isBanned($ip)) { return new Response(SafeMarkup::format('@ip has been banned', ['@ip' => $ip]), 403); } return $this->httpKernel->handle($request, $type, $catch); }
/** * Prints out test data. * * @param string|null $placeholder * A placeholder for the return string. * * @return string * The string for this route. */ public function testDefaults($placeholder = NULL) { if ($placeholder) { return ['#markup' => SafeMarkup::format("Sometimes there is a placeholder: '@placeholder'.", array('@placeholder' => $placeholder))]; } else { return ['#markup' => SafeMarkup::format('Sometimes there is no placeholder.')]; } }