本文整理汇总了PHP中Drupal\Component\Utility\String::format方法的典型用法代码示例。如果您正苦于以下问题:PHP String::format方法的具体用法?PHP String::format怎么用?PHP String::format使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Component\Utility\String
的用法示例。
在下文中一共展示了String::format方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: assertDefaultValues
/**
* 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.');
}
示例2: doCreate
/**
* {@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;
}
示例3: testFileParsing
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.');
}
示例4: validateArguments
/**
* {@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;
}
示例5: submitGetForm
/**
* 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)));
}
}
示例6: validateArguments
/**
* {@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;
}
示例7: testIntegration
/**
* 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']);
}
}
示例8: onConfigSave
/**
* 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))));
}
}
}
示例9: testFetchFields
/**
* 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)));
}
}
示例10: testMatchPath
/**
* 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))));
}
}
示例11: filter
/**
* {@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))));
}
示例12: children
/**
* 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);
}
示例13: testMenus
/**
* 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);
}
示例14: testConfigurationRename
/**
* 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);
}
示例15: addLanguage
/**
* 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)));
}