本文整理汇总了PHP中Drupal\Component\Utility\SafeMarkup::checkPlain方法的典型用法代码示例。如果您正苦于以下问题:PHP SafeMarkup::checkPlain方法的具体用法?PHP SafeMarkup::checkPlain怎么用?PHP SafeMarkup::checkPlain使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Component\Utility\SafeMarkup
的用法示例。
在下文中一共展示了SafeMarkup::checkPlain方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: preRender
/**
* {@inheritdoc}
*/
public function preRender(&$element, $rendering_object)
{
$element += array('#prefix' => '<div class=" ' . implode(' ', $this->getClasses()) . '">', '#suffix' => '</div>', '#tree' => TRUE, '#parents' => array($this->group->group_name), '#default_tab' => '');
if ($this->getSetting('id')) {
$element['#id'] = Html::getId($this->getSetting('id'));
}
// By default tabs don't have titles but you can override it in the theme.
if ($this->getLabel()) {
$element['#title'] = SafeMarkup::checkPlain($this->getLabel());
}
$form_state = new \Drupal\Core\Form\FormState();
if ($this->getSetting('direction') == 'vertical') {
$element += array('#type' => 'vertical_tabs', '#theme_wrappers' => array('vertical_tabs'));
$complete_form = array();
$element = \Drupal\Core\Render\Element\VerticalTabs::processVerticalTabs($element, $form_state, $complete_form);
} else {
$element += array('#type' => 'horizontal_tabs', '#theme_wrappers' => array('horizontal_tabs'));
$on_form = $this->context == 'form';
$element = \Drupal\field_group\Element\HorizontalTabs::processHorizontalTabs($element, $form_state, $on_form);
}
// Make sure the group has 1 child. This is needed to succeed at form_pre_render_vertical_tabs().
// Skipping this would force us to move all child groups to this array, making it an un-nestable.
$element['group']['#groups'][$this->group->group_name] = array(0 => array());
$element['group']['#groups'][$this->group->group_name]['#group_exists'] = TRUE;
// Search for a tab that was marked as open. First one wins.
foreach (\Drupal\Core\Render\Element::children($element) as $tab_name) {
if (!empty($element[$tab_name]['#open'])) {
$element[$this->group->group_name . '__active_tab']['#default_value'] = $tab_name;
break;
}
}
}
示例2: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state)
{
module_load_include('inc', 'pathauto');
$config = $this->config('pathauto.settings');
$form = array();
$form['verbose'] = array('#type' => 'checkbox', '#title' => t('Verbose'), '#default_value' => $config->get('verbose'), '#description' => t('Display alias changes (except during bulk updates).'));
$form['separator'] = array('#type' => 'textfield', '#title' => t('Separator'), '#size' => 1, '#maxlength' => 1, '#default_value' => $config->get('separator'), '#description' => t('Character used to separate words in titles. This will replace any spaces and punctuation characters. Using a space or + character can cause unexpected results.'));
$form['case'] = array('#type' => 'radios', '#title' => t('Character case'), '#default_value' => $config->get('case'), '#options' => array(self::CASE_LEAVE_ASIS => t('Leave case the same as source token values.'), self::CASE_LOWER => t('Change to lower case')));
$max_length = \Drupal::service('pathauto.alias_storage_helper')->getAliasSchemaMaxlength();
$form['max_length'] = array('#type' => 'number', '#title' => t('Maximum alias length'), '#size' => 3, '#maxlength' => 3, '#default_value' => $config->get('max_length'), '#min' => 1, '#max' => $max_length, '#description' => t('Maximum length of aliases to generate. 100 is the recommended length. @max is the maximum possible length. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => $this->getUrlGenerator()->generateFromPath('admin/help/pathauto'), '@max' => $max_length)));
$form['max_component_length'] = array('#type' => 'number', '#title' => t('Maximum component length'), '#size' => 3, '#maxlength' => 3, '#default_value' => $config->get('max_component_length'), '#min' => 1, '#max' => $max_length, '#description' => t('Maximum text length of any component in the alias (e.g., [title]). 100 is the recommended length. @max is the maximum possible length. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => $this->getUrlGenerator()->generateFromPath('admin/help/pathauto'), '@max' => $max_length)));
$description = t('What should Pathauto do when updating an existing content item which already has an alias?');
if (\Drupal::moduleHandler()->moduleExists('redirect')) {
$description .= ' ' . t('The <a href="!url">Redirect module settings</a> affect whether a redirect is created when an alias is deleted.', array('!url' => \Drupal::url('redirect.settings')));
} else {
$description .= ' ' . t('Considering installing the <a href="!url">Redirect module</a> to get redirects when your aliases change.', array('!url' => 'http://drupal.org/project/redirect'));
}
$form['update_action'] = array('#type' => 'radios', '#title' => t('Update action'), '#default_value' => $config->get('update_action'), '#options' => array(PathautoManagerInterface::UPDATE_ACTION_NO_NEW => t('Do nothing. Leave the old alias intact.'), PathautoManagerInterface::UPDATE_ACTION_LEAVE => t('Create a new alias. Leave the existing alias functioning.'), PathautoManagerInterface::UPDATE_ACTION_DELETE => t('Create a new alias. Delete the old alias.')), '#description' => $description);
$form['transliterate'] = array('#type' => 'checkbox', '#title' => t('Transliterate prior to creating alias'), '#default_value' => $config->get('transliterate'), '#description' => t('When a pattern includes certain characters (such as those with accents) should Pathauto attempt to transliterate them into the US-ASCII alphabet? Transliteration is handled by the Transliteration module.'));
$form['reduce_ascii'] = array('#type' => 'checkbox', '#title' => t('Reduce strings to letters and numbers'), '#default_value' => $config->get('reduce_ascii'), '#description' => t('Filters the new alias to only letters and numbers found in the ASCII-96 set.'));
$form['ignore_words'] = array('#type' => 'textarea', '#title' => t('Strings to Remove'), '#default_value' => $config->get('ignore_words'), '#description' => t('Words to strip out of the URL alias, separated by commas. Do not use this to remove punctuation.'), '#wysiwyg' => FALSE);
$form['punctuation'] = array('#type' => 'fieldset', '#title' => t('Punctuation'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#tree' => TRUE);
$punctuation = \Drupal::service('pathauto.manager')->getPunctuationCharacters();
foreach ($punctuation as $name => $details) {
$details['default'] = PathautoManagerInterface::PUNCTUATION_REMOVE;
if ($details['value'] == $config->get('separator')) {
$details['default'] = PathautoManagerInterface::PUNCTUATION_REPLACE;
}
$form['punctuation']['punctuation' . $name] = array('#type' => 'select', '#title' => $details['name'] . ' (<code>' . SafeMarkup::checkPlain($details['value']) . '</code>)', '#default_value' => $details['default'], '#options' => array(PathautoManagerInterface::PUNCTUATION_REMOVE => t('Remove'), PathautoManagerInterface::PUNCTUATION_REPLACE => t('Replace by separator'), PathautoManagerInterface::PUNCTUATION_DO_NOTHING => t('No action (do not replace)')));
}
return parent::buildForm($form, $form_state);
}
示例3: listItems
/**
* Lists the feed items belonging to a feed.
*/
public function listItems(FeedInterface $feeds_feed, Request $request)
{
$processor = $feeds_feed->getType()->getProcessor();
$header = ['title' => $this->t('Label'), 'imported' => $this->t('Imported'), 'guid' => ['data' => $this->t('GUID'), 'class' => [RESPONSIVE_PRIORITY_LOW]], 'url' => ['data' => $this->t('URL'), 'class' => [RESPONSIVE_PRIORITY_LOW]]];
$build = [];
$build['table'] = ['#type' => 'table', '#header' => $header, '#rows' => [], '#empty' => $this->t('There are no items yet.')];
// @todo Allow processors to create their own entity listings.
if (!$processor instanceof EntityProcessorInterface) {
return $build;
}
$entity_ids = \Drupal::entityQuery($processor->entityType())->condition('feeds_item.target_id', $feeds_feed->id())->pager(50)->sort('feeds_item.imported', 'DESC')->execute();
$storage = $this->entityManager()->getStorage($processor->entityType());
foreach ($storage->loadMultiple($entity_ids) as $entity) {
$ago = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $entity->get('feeds_item')->imported);
$row = [];
// Entity link.
$row[] = ['data' => $entity->link(Unicode::truncate($entity->label(), 75, TRUE, TRUE)), 'title' => $entity->label()];
// Imported ago.
$row[] = $this->t('@time ago', ['@time' => $ago]);
// Item GUID.
$row[] = ['data' => SafeMarkup::checkPlain(Unicode::truncate($entity->get('feeds_item')->guid, 30, FALSE, TRUE)), 'title' => $entity->get('feeds_item')->guid];
// Item URL.
$row[] = ['data' => SafeMarkup::checkPlain(Unicode::truncate($entity->get('feeds_item')->url, 30, FALSE, TRUE)), 'title' => $entity->get('feeds_item')->url];
$build['table']['#rows'][] = $row;
}
$build['pager'] = ['#type' => 'pager'];
$build['#title'] = $this->t('%title items', ['%title' => $feeds_feed->label()]);
return $build;
}
示例4: preRender
/**
* {@inheritdoc}
*/
public function preRender(&$element)
{
$element_attributes = new \Drupal\Core\Template\Attribute();
if ($this->getSetting('attributes')) {
// This regex split the attributes string so that we can pass that
// later to drupal_attributes().
preg_match_all('/([^\\s=]+)="([^"]+)"/', $this->getSetting('attributes'), $matches);
// Put the attribute and the value together.
foreach ($matches[1] as $key => $attribute) {
$element_attributes[$attribute] = $matches[2][$key];
}
}
// Add the classes to the attributes array.
if ($this->getSetting('classes')) {
if (!isset($element_attributes['class'])) {
$element_attributes['class'] = array();
}
$element_attributes['class'][] = $this->getSetting('classes');
}
$element['#prefix'] = '<' . $this->getSetting('element') . $element_attributes . '>';
if ($this->getSetting('show_label')) {
$element['#prefix'] .= '<' . $this->getSetting('label_element') . '><span>';
$element['#prefix'] .= SafeMarkup::checkPlain($this->t($group->label));
$element['#prefix'] .= '</span></' . $this->getSetting('label_element') . '>';
}
$element['#suffix'] = '</' . $this->getSetting('element') . '>';
}
示例5: testBlockInterface
/**
* Test configuration and subsequent form() and build() method calls.
*
* This test is attempting to test the existing block plugin api and all
* functionality that is expected to remain consistent. The arrays that are
* used for comparison can change, but only to include elements that are
* contained within BlockBase or the plugin being tested. Likely these
* comparison arrays should get smaller, not larger, as more form/build
* elements are moved into a more suitably responsible class.
*
* Instantiation of the plugin is the primary element being tested here. The
* subsequent method calls are just attempting to cause a failure if a
* dependency outside of the plugin configuration is required.
*/
public function testBlockInterface()
{
$manager = $this->container->get('plugin.manager.block');
$configuration = array('label' => 'Custom Display Message');
$expected_configuration = array('id' => 'test_block_instantiation', 'label' => 'Custom Display Message', 'provider' => 'block_test', 'label_display' => BlockInterface::BLOCK_LABEL_VISIBLE, 'cache' => array('max_age' => Cache::PERMANENT), 'display_message' => 'no message set');
// Initial configuration of the block at construction time.
/** @var $display_block \Drupal\Core\Block\BlockPluginInterface */
$display_block = $manager->createInstance('test_block_instantiation', $configuration);
$this->assertIdentical($display_block->getConfiguration(), $expected_configuration, 'The block was configured correctly.');
// Updating an element of the configuration.
$display_block->setConfigurationValue('display_message', 'My custom display message.');
$expected_configuration['display_message'] = 'My custom display message.';
$this->assertIdentical($display_block->getConfiguration(), $expected_configuration, 'The block configuration was updated correctly.');
$definition = $display_block->getPluginDefinition();
$period = array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400);
$period = array_map(array(\Drupal::service('date.formatter'), 'formatInterval'), array_combine($period, $period));
$period[0] = '<' . t('no caching') . '>';
$period[\Drupal\Core\Cache\Cache::PERMANENT] = t('Forever');
$expected_form = array('provider' => array('#type' => 'value', '#value' => 'block_test'), 'admin_label' => array('#type' => 'item', '#title' => t('Block description'), '#markup' => SafeMarkup::checkPlain($definition['admin_label'])), 'label' => array('#type' => 'textfield', '#title' => 'Title', '#maxlength' => 255, '#default_value' => 'Custom Display Message', '#required' => TRUE), 'label_display' => array('#type' => 'checkbox', '#title' => 'Display title', '#default_value' => TRUE, '#return_value' => 'visible'), 'cache' => array('#type' => 'details', '#title' => t('Cache settings'), 'max_age' => array('#type' => 'select', '#title' => t('Maximum age'), '#description' => t('The maximum time this block may be cached.'), '#default_value' => Cache::PERMANENT, '#options' => $period)), 'display_message' => array('#type' => 'textfield', '#title' => t('Display message'), '#default_value' => 'My custom display message.'));
$form_state = new FormState();
// Ensure there are no form elements that do not belong to the plugin.
$actual_form = $display_block->buildConfigurationForm(array(), $form_state);
// Remove the visibility sections, as that just tests condition plugins.
unset($actual_form['visibility'], $actual_form['visibility_tabs']);
$this->assertIdentical($actual_form, $expected_form, 'Only the expected form elements were present.');
$expected_build = array('#children' => 'My custom display message.');
// Ensure the build array is proper.
$this->assertIdentical($display_block->build(), $expected_build, 'The plugin returned the appropriate build array.');
// Ensure the machine name suggestion is correct. In truth, this is actually
// testing BlockBase's implementation, not the interface itself.
$this->assertIdentical($display_block->getMachineNameSuggestion(), 'displaymessage', 'The plugin returned the expected machine name suggestion.');
}
示例6: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $attributes = NULL)
{
$form['attributes']['#tree'] = TRUE;
foreach ($attributes as $aid => $attribute) {
$base_attr = uc_attribute_load($aid);
if ($base_attr->options) {
$form['attributes'][$aid]['options'] = array('#type' => 'table', '#header' => array($this->t('Options'), $this->t('Default'), $this->t('Cost'), $this->t('Price'), $this->t('Weight'), $this->t('List position')), '#caption' => '<h2>' . SafeMarkup::checkPlain($attribute->name) . '</h2>', '#empty' => $this->t('This attribute does not have any options.'), '#tabledrag' => array(array('action' => 'order', 'relationship' => 'sibling', 'group' => 'uc-attribute-option-table-ordering')));
$query = db_select('uc_attribute_options', 'ao')->fields('ao', array('aid', 'oid', 'name'));
$query->leftJoin($this->optionTable, 'po', "ao.oid = po.oid AND po." . $this->idField . " = :id", array(':id' => $this->idValue));
$query->addField('ao', 'cost', 'default_cost');
$query->addField('ao', 'price', 'default_price');
$query->addField('ao', 'weight', 'default_weight');
$query->addField('ao', 'ordering', 'default_ordering');
$query->fields('po', array('cost', 'price', 'weight', 'ordering'))->addExpression('CASE WHEN po.ordering IS NULL THEN 1 ELSE 0 END', 'null_order');
$query->condition('aid', $aid)->orderBy('null_order')->orderBy('po.ordering')->orderBy('default_ordering')->orderBy('ao.name');
$result = $query->execute();
foreach ($result as $option) {
$oid = $option->oid;
$form['attributes'][$aid]['options'][$oid]['#attributes']['class'][] = 'draggable';
$form['attributes'][$aid]['options'][$oid]['select'] = array('#type' => 'checkbox', '#title' => SafeMarkup::checkPlain($option->name), '#default_value' => isset($attribute->options[$oid]));
$form['attributes'][$aid]['options'][$oid]['default'] = array('#type' => 'radio', '#title' => $this->t('Default'), '#title_display' => 'invisible', '#parents' => array('attributes', $aid, 'default'), '#return_value' => $oid, '#default_value' => $attribute->default_option);
$form['attributes'][$aid]['options'][$oid]['cost'] = array('#type' => 'uc_price', '#title' => $this->t('Cost'), '#title_display' => 'invisible', '#default_value' => is_null($option->cost) ? $option->default_cost : $option->cost, '#size' => 6, '#allow_negative' => TRUE);
$form['attributes'][$aid]['options'][$oid]['price'] = array('#type' => 'uc_price', '#title' => $this->t('Price'), '#title_display' => 'invisible', '#default_value' => is_null($option->price) ? $option->default_price : $option->price, '#size' => 6, '#allow_negative' => TRUE);
$form['attributes'][$aid]['options'][$oid]['weight'] = array('#type' => 'textfield', '#title' => $this->t('Weight'), '#title_display' => 'invisible', '#default_value' => is_null($option->weight) ? $option->default_weight : $option->weight, '#size' => 5);
$form['attributes'][$aid]['options'][$oid]['ordering'] = array('#type' => 'weight', '#title' => $this->t('List position'), '#title_display' => 'invisible', '#delta' => 50, '#default_value' => is_null($option->ordering) ? $option->default_ordering : $option->ordering, '#attributes' => array('class' => array('uc-attribute-option-table-ordering')));
}
}
}
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save changes'));
return $form;
}
示例7: render
/**
* Returns a string representation of the attribute.
*
* While __toString only returns the value in a string form, render()
* contains the name of the attribute as well.
*
* @return string
* The string representation of the attribute.
*/
public function render()
{
$value = (string) $this;
if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) {
return SafeMarkup::checkPlain($this->name) . '="' . $value . '"';
}
}
示例8: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL)
{
$account = $this->currentUser();
$this->user = $user;
// Prepare the list of shortcut sets.
$options = array_map(function (ShortcutSet $set) {
return SafeMarkup::checkPlain($set->label());
}, $this->shortcutSetStorage->loadMultiple());
$current_set = shortcut_current_displayed_set($this->user);
// Only administrators can add shortcut sets.
$add_access = $account->hasPermission('administer shortcuts');
if ($add_access) {
$options['new'] = $this->t('New set');
}
$account_is_user = $this->user->id() == $account->id();
if (count($options) > 1) {
$form['set'] = array('#type' => 'radios', '#title' => $account_is_user ? $this->t('Choose a set of shortcuts to use') : $this->t('Choose a set of shortcuts for this user'), '#options' => $options, '#default_value' => $current_set->id());
$form['label'] = array('#type' => 'textfield', '#title' => $this->t('Label'), '#description' => $this->t('The new set is created by copying items from your default shortcut set.'), '#access' => $add_access, '#states' => array('visible' => array(':input[name="set"]' => array('value' => 'new')), 'required' => array(':input[name="set"]' => array('value' => 'new'))));
$form['id'] = array('#type' => 'machine_name', '#machine_name' => array('exists' => array($this, 'exists'), 'replace_pattern' => '[^a-z0-9-]+', 'replace' => '-'), '#maxlength' => 23, '#states' => array('required' => array(':input[name="set"]' => array('value' => 'new'))), '#required' => FALSE);
if (!$account_is_user) {
$default_set = $this->shortcutSetStorage->getDefaultSet($this->user);
$form['new']['#description'] = $this->t('The new set is created by copying items from the %default set.', array('%default' => $default_set->label()));
}
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Change set'));
} else {
// There is only 1 option, so output a message in the $form array.
$form['info'] = array('#markup' => '<p>' . $this->t('You are currently using the %set-name shortcut set.', array('%set-name' => $current_set->label())) . '</p>');
}
return $form;
}
示例9: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ServerInterface $search_api_server = NULL)
{
$form['#title'] = $this->t('List of configuration files found');
try {
// Retrieve the list of available files.
$files_list = SearchApiSolrUtility::getServerFiles($search_api_server);
if (empty($files_list)) {
$form['info']['#markup'] = $this->t('No files found.');
return $form;
}
$form['files_tabs'] = array('#type' => 'vertical_tabs');
// Generate a fieldset for each file.
foreach ($files_list as $file_name => $file_info) {
$file_date = format_date(strtotime($file_info['modified']));
$escaped_file_name = SafeMarkup::checkPlain($file_name);
$form['files'][$file_name] = array('#type' => 'details', '#title' => $escaped_file_name, '#group' => 'files_tabs');
$data = '<h3>' . $escaped_file_name . '</h3>';
$data .= '<p><em>' . $this->t('Last modified: @time.', array('@time' => $file_date)) . '</em></p>';
if ($file_info['size'] > 0) {
$file_data = $search_api_server->getBackend()->getFile($file_name);
$data .= '<pre><code>' . SafeMarkup::checkPlain($file_data->getBody()) . '</code></pre>';
} else {
$data .= '<p><em>' . $this->t('The file is empty.') . '</em></p>';
}
$form['files'][$file_name]['data']['#markup'] = $data;
}
} catch (SearchApiException $e) {
watchdog_exception('search_api_solr', $e, '%type while retrieving config files of Solr server @server: !message in %function (line %line of %file).', array('@server' => $search_api_server->label()));
$form['info']['#markup'] = $this->t('An error occured while trying to load the list of files.');
}
return $form;
}
示例10: testTitleQuery
/**
* Tests the title_query method.
*
* @see \Drupal\user\Plugin\views\argument\RolesRid::title_query()
*/
public function testTitleQuery()
{
$role1 = new Role(array('id' => 'test_rid_1', 'label' => 'test rid 1'), 'user_role');
$role2 = new Role(array('id' => 'test_rid_2', 'label' => 'test <strong>rid 2</strong>'), 'user_role');
// Creates a stub entity storage;
$role_storage = $this->getMockForAbstractClass('Drupal\\Core\\Entity\\EntityStorageInterface');
$role_storage->expects($this->any())->method('loadMultiple')->will($this->returnValueMap(array(array(array(), array()), array(array('test_rid_1'), array('test_rid_1' => $role1)), array(array('test_rid_1', 'test_rid_2'), array('test_rid_1' => $role1, 'test_rid_2' => $role2)))));
$entity_type = $this->getMock('Drupal\\Core\\Entity\\EntityTypeInterface');
$entity_type->expects($this->any())->method('getKey')->with('label')->will($this->returnValue('label'));
$entity_manager = $this->getMock('Drupal\\Core\\Entity\\EntityManagerInterface');
$entity_manager->expects($this->any())->method('getDefinition')->with($this->equalTo('user_role'))->will($this->returnValue($entity_type));
$entity_manager->expects($this->once())->method('getStorage')->with($this->equalTo('user_role'))->will($this->returnValue($role_storage));
// @todo \Drupal\Core\Entity\Entity::entityType() uses a global call to
// entity_get_info(), which in turn wraps \Drupal::entityManager(). Set
// the entity manager until this is fixed.
$container = new ContainerBuilder();
$container->set('entity.manager', $entity_manager);
\Drupal::setContainer($container);
$roles_rid_argument = new RolesRid(array(), 'user__roles_rid', array(), $entity_manager);
$roles_rid_argument->value = array();
$titles = $roles_rid_argument->title_query();
$this->assertEquals(array(), $titles);
$roles_rid_argument->value = array('test_rid_1');
$titles = $roles_rid_argument->title_query();
$this->assertEquals(array('test rid 1'), $titles);
$roles_rid_argument->value = array('test_rid_1', 'test_rid_2');
$titles = $roles_rid_argument->title_query();
$this->assertEquals(array('test rid 1', SafeMarkup::checkPlain('test <strong>rid 2</strong>')), $titles);
}
示例11: generateFieldMetadata
/**
* {@inheritdoc}
*/
public function generateFieldMetadata(FieldItemListInterface $items, $view_mode)
{
$entity = $items->getEntity();
$field_name = $items->getFieldDefinition()->getName();
// Early-return if user does not have access.
$access = $this->accessChecker->accessEditEntityField($entity, $field_name);
if (!$access) {
return array('access' => FALSE);
}
// Early-return if no editor is available.
$formatter_id = EntityViewDisplay::collectRenderDisplay($entity, $view_mode)->getRenderer($field_name)->getPluginId();
$editor_id = $this->editorSelector->getEditor($formatter_id, $items);
if (!isset($editor_id)) {
return array('access' => FALSE);
}
// Gather metadata, allow the editor to add additional metadata of its own.
$label = $items->getFieldDefinition()->getLabel();
$editor = $this->editorManager->createInstance($editor_id);
$metadata = array('label' => SafeMarkup::checkPlain($label), 'access' => TRUE, 'editor' => $editor_id, 'aria' => t('Entity @type @id, field @field', array('@type' => $entity->getEntityTypeId(), '@id' => $entity->id(), '@field' => $label)));
$custom_metadata = $editor->getMetadata($items);
if (count($custom_metadata)) {
$metadata['custom'] = $custom_metadata;
}
return $metadata;
}
示例12: preRender
public function preRender(&$values)
{
$uids = array();
$this->items = array();
foreach ($values as $result) {
$uids[] = $this->getValue($result);
}
if ($uids) {
$roles = user_roles();
$result = $this->database->query('SELECT u.entity_id as uid, u.roles_target_id as rid FROM {user__roles} u WHERE u.entity_id IN ( :uids[] ) AND u.roles_target_id IN ( :rids[] )', array(':uids[]' => $uids, ':rids[]' => array_keys($roles)));
foreach ($result as $role) {
$this->items[$role->uid][$role->rid]['role'] = SafeMarkup::checkPlain($roles[$role->rid]->label());
$this->items[$role->uid][$role->rid]['rid'] = $role->rid;
}
// Sort the roles for each user by role weight.
$ordered_roles = array_flip(array_keys($roles));
foreach ($this->items as &$user_roles) {
// Create an array of rids that the user has in the role weight order.
$sorted_keys = array_intersect_key($ordered_roles, $user_roles);
// Merge with the unsorted array of role information which has the
// effect of sorting it.
$user_roles = array_merge($sorted_keys, $user_roles);
}
}
}
示例13: callback_batch_operation
/**
* Perform a single batch operation.
*
* Callback for batch_set().
*
* @param $MULTIPLE_PARAMS
* Additional parameters specific to the batch. These are specified in the
* array passed to batch_set().
* @param $context
* The batch context array, passed by reference. This contains the following
* properties:
* - 'finished': A float number between 0 and 1 informing the processing
* engine of the completion level for the operation. 1 (or no value
* explicitly set) means the operation is finished: the operation will not
* be called again, and execution passes to the next operation or the
* callback_batch_finished() implementation. Any other value causes this
* operation to be called again; however it should be noted that the value
* set here does not persist between executions of this callback: each time
* it is set to 1 by default by the batch system.
* - 'sandbox': This may be used by operations to persist data between
* successive calls to the current operation. Any values set in
* $context['sandbox'] will be there the next time this function is called
* for the current operation. For example, an operation may wish to store a
* pointer in a file or an offset for a large query. The 'sandbox' array key
* is not initially set when this callback is first called, which makes it
* useful for determining whether it is the first call of the callback or
* not:
* @code
* if (empty($context['sandbox'])) {
* // Perform set-up steps here.
* }
* @endcode
* The values in the sandbox are stored and updated in the database between
* http requests until the batch finishes processing. This avoids problems
* if the user navigates away from the page before the batch finishes.
* - 'message': A text message displayed in the progress page.
* - 'results': The array of results gathered so far by the batch processing.
* This array is highly useful for passing data between operations. After
* all operations have finished, this is passed to callback_batch_finished()
* where results may be referenced to display information to the end-user,
* such as how many total items were processed.
*/
function callback_batch_operation($MULTIPLE_PARAMS, &$context)
{
$node_storage = $this->container->get('entity.manager')->getStorage('node');
if (!isset($context['sandbox']['progress'])) {
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_node'] = 0;
$context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
}
// For this example, we decide that we can safely process
// 5 nodes at a time without a timeout.
$limit = 5;
// With each pass through the callback, retrieve the next group of nids.
$result = db_query_range("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC", $context['sandbox']['current_node'], 0, $limit);
while ($row = db_fetch_array($result)) {
// Here we actually perform our processing on the current node.
$node_storage->resetCache(array($row['nid']));
$node = $node_storage->load($row['nid']);
$node->value1 = $options1;
$node->value2 = $options2;
node_save($node);
// Store some result for post-processing in the finished callback.
$context['results'][] = SafeMarkup::checkPlain($node->title);
// Update our progress information.
$context['sandbox']['progress']++;
$context['sandbox']['current_node'] = $node->nid;
$context['message'] = t('Now processing %node', array('%node' => $node->title));
}
// Inform the batch engine that we are not finished,
// and provide an estimation of the completion level we reached.
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}
}
示例14: testTableSortInit
/**
* Tests tablesort_init().
*/
function testTableSortInit()
{
// Test simple table headers.
$headers = array('foo', 'bar', 'baz');
// Reset $request->query to prevent parameters from Simpletest and Batch API
// ending up in $ts['query'].
$expected_ts = array('name' => 'foo', 'sql' => '', 'sort' => 'asc', 'query' => array());
$request = Request::createFromGlobals();
$request->query->replace(array());
\Drupal::getContainer()->get('request_stack')->push($request);
$ts = tablesort_init($headers);
$this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => SafeMarkup::checkPlain(var_export($ts, TRUE)))));
$this->assertEqual($ts, $expected_ts, 'Simple table headers sorted correctly.');
// Test with simple table headers plus $_GET parameters that should _not_
// override the default.
$request = Request::createFromGlobals();
$request->query->replace(array('order' => 'bar'));
\Drupal::getContainer()->get('request_stack')->push($request);
$ts = tablesort_init($headers);
$this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => SafeMarkup::checkPlain(var_export($ts, TRUE)))));
$this->assertEqual($ts, $expected_ts, 'Simple table headers plus non-overriding $_GET parameters sorted correctly.');
// Test with simple table headers plus $_GET parameters that _should_
// override the default.
$request = Request::createFromGlobals();
$request->query->replace(array('sort' => 'DESC', 'alpha' => 'beta'));
\Drupal::getContainer()->get('request_stack')->push($request);
$expected_ts['sort'] = 'desc';
$expected_ts['query'] = array('alpha' => 'beta');
$ts = tablesort_init($headers);
$this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => SafeMarkup::checkPlain(var_export($ts, TRUE)))));
$this->assertEqual($ts, $expected_ts, 'Simple table headers plus $_GET parameters sorted correctly.');
// Test complex table headers.
$headers = array('foo', array('data' => '1', 'field' => 'one', 'sort' => 'asc', 'colspan' => 1), array('data' => '2', 'field' => 'two', 'sort' => 'desc'));
// Reset $_GET from previous assertion.
$request = Request::createFromGlobals();
$request->query->replace(array('order' => '2'));
\Drupal::getContainer()->get('request_stack')->push($request);
$ts = tablesort_init($headers);
$expected_ts = array('name' => '2', 'sql' => 'two', 'sort' => 'desc', 'query' => array());
$this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => SafeMarkup::checkPlain(var_export($ts, TRUE)))));
$this->assertEqual($ts, $expected_ts, 'Complex table headers sorted correctly.');
// Test complex table headers plus $_GET parameters that should _not_
// override the default.
$request = Request::createFromGlobals();
$request->query->replace(array('order' => 'bar'));
\Drupal::getContainer()->get('request_stack')->push($request);
$ts = tablesort_init($headers);
$expected_ts = array('name' => '1', 'sql' => 'one', 'sort' => 'asc', 'query' => array());
$this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => SafeMarkup::checkPlain(var_export($ts, TRUE)))));
$this->assertEqual($ts, $expected_ts, 'Complex table headers plus non-overriding $_GET parameters sorted correctly.');
// Test complex table headers plus $_GET parameters that _should_
// override the default.
$request = Request::createFromGlobals();
$request->query->replace(array('order' => '1', 'sort' => 'ASC', 'alpha' => 'beta'));
\Drupal::getContainer()->get('request_stack')->push($request);
$expected_ts = array('name' => '1', 'sql' => 'one', 'sort' => 'asc', 'query' => array('alpha' => 'beta'));
$ts = tablesort_init($headers);
$this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => SafeMarkup::checkPlain(var_export($ts, TRUE)))));
$this->assertEqual($ts, $expected_ts, 'Complex table headers plus $_GET parameters sorted correctly.');
}
示例15: testCleanString
/**
* Test pathauto_cleanstring().
*/
public function testCleanString()
{
$config = $this->config('pathauto.settings');
$tests = array();
$config->set('ignore_words', ', in, is,that, the , this, with, ');
$config->set('max_component_length', 35);
$config->set('transliterate', TRUE);
$config->save();
\Drupal::service('pathauto.manager')->resetCaches();
// Test the 'ignored words' removal.
$tests['this'] = 'this';
$tests['this with that'] = 'this-with-that';
$tests['this thing with that thing'] = 'thing-thing';
// Test length truncation and duplicate separator removal.
$tests[' - Pathauto is the greatest - module ever in Drupal hiarticle - '] = 'pathauto-greatest-module-ever';
// Test that HTML tags are removed.
$tests['This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.'] = 'text-has-html-tags';
$tests[(string) SafeMarkup::checkPlain('This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.')] = 'text-has-html-tags';
// Transliteration.
$tests['ľščťžýáíéňô'] = 'lsctzyaieno';
foreach ($tests as $input => $expected) {
$output = \Drupal::service('pathauto.manager')->cleanString($input);
$this->assertEqual($output, $expected, t("Drupal::service('pathauto.manager')->cleanString('@input') expected '@expected', actual '@output'", array('@input' => $input, '@expected' => $expected, '@output' => $output)));
}
}