/**
  * Executes a test set for a defined entity type.
  *
  * @param string $entity_type
  *   The entity type to run the tests with.
  */
 protected function assertDefaultValues($entity_type)
 {
     $entity = entity_create($entity_type);
     $this->assertEqual($entity->langcode->value, 'en', String::format('%entity_type: Default language', array('%entity_type' => $entity_type)));
     $this->assertTrue(Uuid::isValid($entity->uuid->value), String::format('%entity_type: Default UUID', array('%entity_type' => $entity_type)));
     $this->assertEqual($entity->name->getValue(), array(0 => array('value' => NULL)), 'Field has one empty value by default.');
 }
 /**
  * {@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(String::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;
 }
 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]), String::format('Found source string: %source', $args));
         // Make sure that the proper context was matched.
         $message = $context ? String::format('Context for %source is %context', $args) : String::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.');
 }
 /**
  * {@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(String::format("Invalid width (@value) specified for the image 'scale' operation", array('@value' => $arguments['width'])));
     }
     if ($arguments['height'] <= 0) {
         throw new \InvalidArgumentException(String::format("Invalid height (@value) specified for the image 'scale' operation", array('@value' => $arguments['height'])));
     }
     return $arguments;
 }
 /**
  * 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(String::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}
  */
 protected function validateArguments(array $arguments)
 {
     if (!in_array($arguments['extension'], $this->getToolkit()->getSupportedExtensions())) {
         throw new \InvalidArgumentException(String::format("Invalid extension (@value) specified for the image 'convert' operation", array('@value' => $arguments['extension'])));
     }
     return $arguments;
 }
 /**
  * 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' => l('Link', 'node/1'));
     // Setup a watchdog entry with one token.
     $entries[] = array('message' => '@token1', 'variables' => array('@token1' => $this->randomMachineName()), 'link' => l('Link', 'node/2'));
     // Setup a watchdog entry with two tokens.
     $entries[] = array('message' => '@token1 !token2', 'variables' => array('@token1' => $this->randomMachineName(), '!token2' => $this->randomMachineName()), 'link' => l('<object>Link</object>', 'node/2', array('html' => TRUE)));
     foreach ($entries as $entry) {
         $entry += array('type' => 'test-views', 'severity' => WATCHDOG_NOTICE);
         watchdog($entry['type'], $entry['message'], $entry['variables'], $entry['severity'], $entry['link']);
     }
     $view = Views::getView('test_dblog');
     $this->executeView($view);
     $view->initStyle();
     foreach ($entries as $index => $entry) {
         $this->assertEqual($view->style_plugin->getField($index, 'message'), String::format($entry['message'], $entry['variables']));
         $this->assertEqual($view->style_plugin->getField($index, 'link'), Xss::filterAdmin($entry['link']));
     }
     // Disable replacing variables and check that the tokens aren't replaced.
     $view->destroy();
     $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']);
     }
 }
 /**
  * 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 = crc32(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(String::format('No schema for @config_name', array('@config_name' => $name)));
         } elseif (is_array($errors)) {
             $text_errors = [];
             foreach ($errors as $key => $error) {
                 $text_errors[] = String::format('@key @error', array('@key' => $key, '@error' => $error));
             }
             throw new SchemaIncompleteException(String::format('Schema errors for @config_name with the following errors: @errors', array('@config_name' => $name, '@errors' => implode(', ', $text_errors))));
         }
     }
 }
 /**
  * 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), String::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), String::format('Sub_type @sub_type is not filtered as expected.', array('@sub_type' => $sub_type)));
     }
 }
 /**
  * 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, String::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))));
     }
 }
 /**
  * {@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 = $this->contentNegotiation->getContentType($request);
     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(String::format('No route found for the specified formats @formats.', array('@formats' => implode(' ', $acceptable_mime_types))));
 }
Beispiel #12
0
 /**
  * Identifies the children of an element array, optionally sorted by weight.
  *
  * The children of a element array are those key/value pairs whose key does
  * not start with a '#'. See drupal_render() for details.
  *
  * @param array $elements
  *   The element array whose children are to be identified. Passed by
  *   reference.
  * @param bool $sort
  *   Boolean to indicate whether the children should be sorted by weight.
  *
  * @return array
  *   The array keys of the element's children.
  */
 public static function children(array &$elements, $sort = FALSE)
 {
     // Do not attempt to sort elements which have already been sorted.
     $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
     // Filter out properties from the element, leaving only children.
     $children = array();
     $sortable = FALSE;
     foreach ($elements as $key => $value) {
         if ($key === '' || $key[0] !== '#') {
             if (is_array($value)) {
                 $children[$key] = $value;
                 if (isset($value['#weight'])) {
                     $sortable = TRUE;
                 }
             } elseif (isset($value)) {
                 trigger_error(String::format('"@key" is an invalid render array key', array('@key' => $key)), E_USER_ERROR);
             }
         }
     }
     // Sort the children if necessary.
     if ($sort && $sortable) {
         uasort($children, 'Drupal\\Component\\Utility\\SortArray::sortByWeightProperty');
         // Put the sorted children back into $elements in the correct order, to
         // preserve sorting if the same element is passed through
         // \Drupal\Core\Render\Element::children() twice.
         foreach ($children as $key => $child) {
             unset($elements[$key]);
             $elements[$key] = $child;
         }
         $elements['#sorted'] = TRUE;
     }
     return array_keys($children);
 }
 /**
  * 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($view['page[path]']));
     // 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', String::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);
 }
 /**
  * Tests configuration renaming.
  */
 public function testConfigurationRename()
 {
     $content_type = entity_create('node_type', array('type' => Unicode::strtolower($this->randomName(16)), 'name' => $this->randomName()));
     $content_type->save();
     $staged_type = $content_type->type;
     $active = $this->container->get('config.storage');
     $staging = $this->container->get('config.storage.staging');
     $config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id();
     // Emulate a staging operation.
     $this->copyConfig($active, $staging);
     // Change the machine name of the content type.
     $content_type->type = Unicode::strtolower($this->randomName(8));
     $content_type->save();
     $active_type = $content_type->type;
     $renamed_config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id();
     $this->assertTrue($active->exists($renamed_config_name), 'The content type has the new name in the active store.');
     $this->assertFalse($active->exists($config_name), "The content type's old name does not exist active store.");
     $this->configImporter()->reset();
     $this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('create')), 'There are no configuration items to create.');
     $this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('delete')), 'There are no configuration items to delete.');
     $this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('update')), 'There are no configuration items to update.');
     // We expect that changing the machine name of the content type will
     // rename five configuration entities: the node type, the body field
     // instance, two entity form displays, and the entity view display.
     // @see \Drupal\node\Entity\NodeType::postSave()
     $expected = array('node.type.' . $active_type . '::node.type.' . $staged_type, 'entity.form_display.node.' . $active_type . '.default::entity.form_display.node.' . $staged_type . '.default', 'entity.view_display.node.' . $active_type . '.default::entity.view_display.node.' . $staged_type . '.default', 'entity.view_display.node.' . $active_type . '.teaser::entity.view_display.node.' . $staged_type . '.teaser', 'field.instance.node.' . $active_type . '.body::field.instance.node.' . $staged_type . '.body');
     $renames = $this->configImporter()->getUnprocessedConfiguration('rename');
     $this->assertIdentical($expected, $renames);
     $this->drupalGet('admin/config/development/configuration');
     foreach ($expected as $rename) {
         $names = $this->configImporter()->getStorageComparer()->extractRenameNames($rename);
         $this->assertText(String::format('!source_name to !target_name', array('!source_name' => $names['old_name'], '!target_name' => $names['new_name'])));
         // Test that the diff link is present for each renamed item.
         $href = \Drupal::urlGenerator()->getPathFromRoute('config.diff', array('source_name' => $names['old_name'], 'target_name' => $names['new_name']));
         $this->assertLinkByHref($href);
         $hrefs[$rename] = $href;
     }
     // Ensure that the diff works for each renamed item.
     foreach ($hrefs as $rename => $href) {
         $this->drupalGet($href);
         $names = $this->configImporter()->getStorageComparer()->extractRenameNames($rename);
         $config_entity_type = \Drupal::service('config.manager')->getEntityTypeIdByName($names['old_name']);
         $entity_type = \Drupal::entityManager()->getDefinition($config_entity_type);
         $old_id = ConfigEntityStorage::getIDFromConfigName($names['old_name'], $entity_type->getConfigPrefix());
         $new_id = ConfigEntityStorage::getIDFromConfigName($names['new_name'], $entity_type->getConfigPrefix());
         // Because table columns can be on multiple lines, need to assert a regex
         // pattern rather than normal text.
         $id_key = $entity_type->getKey('id');
         $text = "{$id_key}: {$old_id}";
         $this->assertTextPattern('/\\-\\s+' . preg_quote($text, '/') . '/', "'-{$text}' found.");
         $text = "{$id_key}: {$new_id}";
         $this->assertTextPattern('/\\+\\s+' . preg_quote($text, '/') . '/', "'+{$text}' found.");
     }
     // Run the import.
     $this->drupalPostForm('admin/config/development/configuration', array(), t('Import all'));
     $this->assertText(t('There are no configuration changes.'));
     $this->assertFalse(entity_load('node_type', $active_type), 'The content no longer exists with the old name.');
     $content_type = entity_load('node_type', $staged_type);
     $this->assertIdentical($staged_type, $content_type->type);
 }
 /**
  * Adds a language.
  *
  * @param $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), String::format('Language %langcode added.', array('%langcode' => $langcode)));
 }
 /**
  * Converts a configuration collection name to a language code.
  *
  * @param string $collection
  *   The configuration collection name.
  *
  * @return string
  *   The language code of the collection.
  *
  * @throws \InvalidArgumentException
  *   Exception thrown if the provided collection name is not in the format
  *   "language.LANGCODE".
  *
  * @see self::createConfigCollectionName()
  */
 protected function getLangcodeFromCollectionName($collection)
 {
     preg_match('/^language\\.(.*)$/', $collection, $matches);
     if (!isset($matches[1])) {
         throw new \InvalidArgumentException(String::format('!collection is not a valid language override collection', array('!collection' => $collection)));
     }
     return $matches[1];
 }
 /**
  * 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' => String::format("Sometimes there is a placeholder: '@placeholder'.", array('@placeholder' => $placeholder))];
     } else {
         return ['#markup' => String::format('Sometimes there is no placeholder.')];
     }
 }
 /**
  * Verifies that the default mobile meta tags can be removed.
  */
 public function testRemovingDefaultMetaTags()
 {
     \Drupal::moduleHandler()->install(array('system_module_test'));
     $this->drupalGet('');
     foreach ($this->default_metatags as $name => $metatag) {
         $this->assertNoRaw($metatag, String::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 object names that have unmet dependencies
  *
  * @return \Drupal\Core\Config\PreExistingConfigException
  */
 public static function create($extension, array $config_objects)
 {
     $message = String::format('Configuration objects (@config_names) provided by @extension have unmet dependencies', array('@config_names' => implode(', ', $config_objects), '@extension' => $extension));
     $e = new static($message);
     $e->configObjects = $config_objects;
     $e->extension = $extension;
     return $e;
 }
 /**
  * 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 = String::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(String::format('Sorry @ip has been banned', ['@ip' => $ip]), 403);
     }
     return $this->httpKernel->handle($request, $type, $catch);
 }
Beispiel #22
0
 /**
  * {@inheritdoc}
  */
 public function fetch(FeedInterface $feed)
 {
     $feed_config = $feed->getConfigurationFor($this);
     if (is_file($feed_config['source'])) {
         return new FetcherResult($feed_config['source']);
     }
     // File does not exist.
     throw new \Exception(String::format('Resource is not a file: %source', array('%source' => $feed_config['source'])));
 }
 /**
  * Executes a test set for a defined entity type.
  *
  * @param string $entity_type_id
  *   The entity type to run the tests with.
  */
 protected function assertDefaultValues($entity_type_id)
 {
     $entity = entity_create($entity_type_id);
     $definition = $this->entityManager->getDefinition($entity_type_id);
     $langcode_key = $definition->getKey('langcode');
     $this->assertEqual($entity->{$langcode_key}->value, 'en', String::format('%entity_type: Default language', array('%entity_type' => $entity_type_id)));
     $this->assertTrue(Uuid::isValid($entity->uuid->value), String::format('%entity_type: Default UUID', array('%entity_type' => $entity_type_id)));
     $this->assertEqual($entity->name->getValue(), array(), 'Field has one empty value by default.');
 }
Beispiel #24
0
 /**
  * Assert that at set of links is properly parented.
  */
 function assertMenuLinkParents($links, $expected_hierarchy)
 {
     foreach ($expected_hierarchy as $id => $parent) {
         /* @var \Drupal\Core\Menu\MenuLinkInterface $menu_link_plugin  */
         $menu_link_plugin = $this->menuLinkManager->createInstance($links[$id]);
         $expected_parent = isset($links[$parent]) ? $links[$parent] : '';
         $this->assertEqual($menu_link_plugin->getParent(), $expected_parent, String::format('Menu link %id has parent of %parent, expected %expected_parent.', array('%id' => $id, '%parent' => $menu_link_plugin->getParent(), '%expected_parent' => $expected_parent)));
     }
 }
 /**
  * Tests that we get an exception when the length of the config prefix that is
  * returned by getConfigPrefix() exceeds the maximum defined prefix length.
  *
  * @covers ::getConfigPrefix
  */
 public function testConfigPrefixLengthExceeds()
 {
     $message_text = 'The configuration file name prefix @config_prefix exceeds the maximum character limit of @max_char.';
     // A provider length of 24 and config_prefix length of 59 (+1 for the .)
     // results in a config length of 84, which is too long.
     $definition = array('provider' => $this->randomMachineName(24), 'config_prefix' => $this->randomMachineName(59));
     $config_entity = $this->setUpConfigEntityType($definition);
     $this->setExpectedException('\\Drupal\\Core\\Config\\ConfigPrefixLengthException', String::format($message_text, array('@config_prefix' => $definition['provider'] . '.' . $definition['config_prefix'], '@max_char' => ConfigEntityType::PREFIX_LENGTH)));
     $this->assertEmpty($config_entity->getConfigPrefix());
 }
 /**
  * Tests unique random name generation.
  *
  * @see \Drupal\Component\Utility\Random::name()
  */
 public function testRandomNamesUniqueness()
 {
     $names = array();
     $random = new Random();
     for ($i = 0; $i <= 10; $i++) {
         $str = $random->name(1, TRUE);
         $this->assertFalse(isset($names[$str]), String::format('Generated duplicate random name !name', array('!name' => $str)));
         $names[$str] = TRUE;
     }
 }
Beispiel #27
0
 /**
  * {@inheritdoc}
  */
 public function render(ResultRow $values)
 {
     $value = $this->getValue($values);
     if ($this->options['replace_variables']) {
         $variables = unserialize($this->getvalue($values, 'variables'));
         return String::format($value, (array) $variables);
     } else {
         return $this->sanitizeValue($value);
     }
 }
 /**
  * Asserts correct field access grants for a field.
  */
 public function assertFieldAccess($field, $viewer, $target, $view, $edit)
 {
     $field_definition = $this->getMock('Drupal\\Core\\Field\\FieldDefinitionInterface');
     $field_definition->expects($this->any())->method('getName')->will($this->returnValue($field));
     $this->items->expects($this->any())->method('getEntity')->will($this->returnValue($this->{$target}));
     foreach (array('view' => $view, 'edit' => $edit) as $operation => $result) {
         $message = String::format("User @field field access returns @result with operation '@op' for @account accessing @target", array('@field' => $field, '@result' => !isset($result) ? 'null' : ($result ? 'true' : 'false'), '@op' => $operation, '@account' => $viewer, '@target' => $target));
         $this->assertSame($result, $this->accessControlHandler->fieldAccess($operation, $field_definition, $this->{$viewer}, $this->items), $message);
     }
 }
 /**
  * Provides a form to edit options for this plugin.
  *
  * @see \Drupal\views\Plugin\views\PluginBase::defineOptions().
  */
 public function buildOptionsForm(&$form, FormStateInterface $form_state)
 {
     $description_top = t('The handler for this item is broken or missing. The following details are available:');
     foreach ($this->definition['original_configuration'] as $key => $value) {
         if (is_scalar($value)) {
             $items[] = String::format('@key: @value', array('@key' => $key, '@value' => $value));
         }
     }
     $description_bottom = t('Enabling the appropriate module will may solve this issue. Otherwise, check to see if there is a module update available.');
     $form['description'] = array('#type' => 'container', '#attributes' => array('class' => array('form-item', 'description')), 'description_top' => array('#markup' => '<p>' . $description_top . '</p>'), 'detail_list' => array('#theme' => 'item_list', '#items' => $items), 'description_bottom' => array('#markup' => '<p>' . $description_bottom . '</p>'));
 }
 /**
  * Tests dependencies on the migration of aggregator feeds & items.
  */
 public function testAggregatorMigrateDependencies()
 {
     /** @var \Drupal\migrate\entity\Migration $migration */
     $migration = entity_load('migration', 'd6_aggregator_item');
     $dumps = array($this->getDumpDirectory() . '/Drupal6AggregatorItem.php');
     $this->prepare($migration, $dumps);
     $executable = new MigrateExecutable($migration, $this);
     $this->startCollectingMessages();
     $executable->import();
     $this->assertEqual($this->migrateMessages['error'], array(String::format('Migration @id did not meet the requirements', array('@id' => $migration->id()))));
     $this->collectMessages = FALSE;
 }