本文整理汇总了PHP中Drupal\Component\Utility\Html::load方法的典型用法代码示例。如果您正苦于以下问题:PHP Html::load方法的具体用法?PHP Html::load怎么用?PHP Html::load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Component\Utility\Html
的用法示例。
在下文中一共展示了Html::load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (stristr($text, 'data-entity-type="file"') !== FALSE) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
$processed_uuids = array();
foreach ($xpath->query('//*[@data-entity-type="file" and @data-entity-uuid]') as $node) {
$uuid = $node->getAttribute('data-entity-uuid');
// If there is a 'src' attribute, set it to the file entity's current
// URL. This ensures the URL works even after the file location changes.
if ($node->hasAttribute('src')) {
$file = $this->entityManager->loadEntityByUuid('file', $uuid);
if ($file) {
$node->setAttribute('src', file_url_transform_relative(file_create_url($file->getFileUri())));
}
}
// Only process the first occurrence of each file UUID.
if (!isset($processed_uuids[$uuid])) {
$processed_uuids[$uuid] = TRUE;
$file = $this->entityManager->loadEntityByUuid('file', $uuid);
if ($file) {
$result->addCacheTags($file->getCacheTags());
}
}
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
示例2: testCreatePlaceholderGeneratesValidHtmlMarkup
/**
* @covers ::createPlaceholder
* @dataProvider providerCreatePlaceholderGeneratesValidHtmlMarkup
*
* Ensure that the generated placeholder markup is valid. If it is not, then
* simply using DOMDocument on HTML that contains placeholders may modify the
* placeholders' markup, which would make it impossible to replace the
* placeholders: the placeholder markup in #attached versus that in the HTML
* processed by DOMDocument would no longer match.
*/
public function testCreatePlaceholderGeneratesValidHtmlMarkup(array $element)
{
$build = $this->placeholderGenerator->createPlaceholder($element);
$original_placeholder_markup = (string) $build['#markup'];
$processed_placeholder_markup = Html::serialize(Html::load($build['#markup']));
$this->assertEquals($original_placeholder_markup, $processed_placeholder_markup);
}
示例3: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$document = Html::load($text);
foreach ($this->settings['tags'] as $tag) {
$tag_elements = $document->getElementsByTagName($tag);
foreach ($tag_elements as $tag_element) {
$tag_element->setAttribute('test_attribute', 'test attribute value');
}
}
return new FilterProcessResult(Html::serialize($document));
}
示例4: replaceNodeContent
/**
* Replace the contents of a DOMNode.
*
* @param \DOMNode $node
* A DOMNode object.
* @param string $content
* The text or HTML that will replace the contents of $node.
*/
protected function replaceNodeContent(\DOMNode &$node, $content)
{
if (strlen($content)) {
// Load the content into a new DOMDocument and retrieve the DOM nodes.
$replacement_nodes = Html::load($content)->getElementsByTagName('body')->item(0)->childNodes;
} else {
$replacement_nodes = [$node->ownerDocument->createTextNode('')];
}
foreach ($replacement_nodes as $replacement_node) {
// Import the replacement node from the new DOMDocument into the original
// one, importing also the child nodes of the replacement node.
$replacement_node = $node->ownerDocument->importNode($replacement_node, TRUE);
$node->parentNode->insertBefore($replacement_node, $node);
}
$node->parentNode->removeChild($node);
}
示例5: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (strpos($text, 'data-entity-type') !== FALSE && (strpos($text, 'data-entity-embed-display') !== FALSE || strpos($text, 'data-view-mode') !== FALSE)) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//drupal-entity[@data-entity-type and (@data-entity-uuid or @data-entity-id) and (@data-entity-embed-display or @data-view-mode)]') as $node) {
/** @var \DOMElement $node */
$entity_type = $node->getAttribute('data-entity-type');
$entity = NULL;
$entity_output = '';
try {
// Load the entity either by UUID (preferred) or ID.
$id = $node->getAttribute('data-entity-uuid') ?: $node->getAttribute('data-entity-id');
$entity = $this->loadEntity($entity_type, $id);
if ($entity) {
// Protect ourselves from recursive rendering.
static $depth = 0;
$depth++;
if ($depth > 20) {
throw new RecursiveRenderingException(sprintf('Recursive rendering detected when rendering embedded %s entity %s.', $entity_type, $entity->id()));
}
// If a UUID was not used, but is available, add it to the HTML.
if (!$node->getAttribute('data-entity-uuid') && ($uuid = $entity->uuid())) {
$node->setAttribute('data-entity-uuid', $uuid);
}
$access = $entity->access('view', NULL, TRUE);
$access_metadata = CacheableMetadata::createFromObject($access);
$entity_metadata = CacheableMetadata::createFromObject($entity);
$result = $result->merge($entity_metadata)->merge($access_metadata);
$context = $this->getNodeAttributesAsArray($node);
$context += array('data-langcode' => $langcode);
$entity_output = $this->renderEntityEmbed($entity, $context);
$depth--;
} else {
throw new EntityNotFoundException(sprintf('Unable to load embedded %s entity %s.', $entity_type, $id));
}
} catch (\Exception $e) {
watchdog_exception('entity_embed', $e);
}
$this->replaceNodeContent($node, $entity_output);
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
示例6: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (stristr($text, '<pre') !== FALSE) {
$attach = FALSE;
$nodes = Html::load($text)->getElementsByTagName('pre');
foreach ($nodes as $node) {
if (preg_match('/\\bbrush\\b:(.*?);/i', $node->getAttribute('class'))) {
$attach = TRUE;
break;
}
}
if ($attach) {
$result->addAttachments(['library' => ['syntax_highlighter/highlight']]);
}
}
return $result;
}
开发者ID:kaa4ever,项目名称:drupal8-syntax-highlighter,代码行数:21,代码来源:FilterSyntaxHighlighterAttachLibrary.php
示例7: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (stristr($text, 'data-caption') !== FALSE) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//*[@data-caption]') as $node) {
// Read the data-caption attribute's value, then delete it.
$caption = Html::escape($node->getAttribute('data-caption'));
$node->removeAttribute('data-caption');
// Sanitize caption: decode HTML encoding, limit allowed HTML tags; only
// allow inline tags that are allowed by default, plus <br>.
$caption = Html::decodeEntities($caption);
$caption = FilteredMarkup::create(Xss::filter($caption, array('a', 'em', 'strong', 'cite', 'code', 'br')));
// The caption must be non-empty.
if (Unicode::strlen($caption) === 0) {
continue;
}
// Given the updated node and caption: re-render it with a caption, but
// bubble up the value of the class attribute of the captioned element,
// this allows it to collaborate with e.g. the filter_align filter.
$tag = $node->tagName;
$classes = $node->getAttribute('class');
$node->removeAttribute('class');
$node = $node->parentNode->tagName === 'a' ? $node->parentNode : $node;
$filter_caption = array('#theme' => 'filter_caption', '#node' => FilteredMarkup::create($node->C14N()), '#tag' => $tag, '#caption' => $caption, '#classes' => $classes);
$altered_html = drupal_render($filter_caption);
// Load the altered HTML into a new DOMDocument and retrieve the element.
$updated_nodes = Html::load($altered_html)->getElementsByTagName('body')->item(0)->childNodes;
foreach ($updated_nodes as $updated_node) {
// Import the updated node from the new DOMDocument into the original
// one, importing also the child nodes of the updated node.
$updated_node = $dom->importNode($updated_node, TRUE);
$node->parentNode->insertBefore($updated_node, $node);
}
// Finally, remove the original data-caption node.
$node->parentNode->removeChild($node);
}
$result->setProcessedText(Html::serialize($dom))->addAttachments(array('library' => array('filter/caption')));
}
return $result;
}
示例8: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (stristr($text, 'data-entity-type="file"') !== FALSE) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
$processed_uuids = array();
foreach ($xpath->query('//*[@data-entity-type="file" and @data-entity-uuid]') as $node) {
$uuid = $node->getAttribute('data-entity-uuid');
// Only process the first occurrence of each file UUID.
if (!isset($processed_uuids[$uuid])) {
$processed_uuids[$uuid] = TRUE;
$file = $this->entityManager->loadEntityByUuid('file', $uuid);
if ($file) {
$result->addCacheTags($file->getCacheTags());
}
}
}
}
return $result;
}
示例9: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (stristr($text, 'data-align') !== FALSE) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//*[@data-align]') as $node) {
// Read the data-align attribute's value, then delete it.
$align = $node->getAttribute('data-align');
$node->removeAttribute('data-align');
// If one of the allowed alignments, add the corresponding class.
if (in_array($align, array('left', 'center', 'right'))) {
$classes = $node->getAttribute('class');
$classes = strlen($classes) > 0 ? explode(' ', $classes) : array();
$classes[] = 'align-' . $align;
$node->setAttribute('class', implode(' ', $classes));
}
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
示例10: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
/** @var \DOMNode $node */
foreach ($xpath->query('//img') as $node) {
// Read the data-align attribute's value, then delete it.
$width = $node->getAttribute('width');
$height = $node->getAttribute('height');
$src = $node->getAttribute('src');
if (!UrlHelper::isExternal($src)) {
if ($width || $height) {
/** @var \DOMNode $element */
$element = $dom->createElement('a');
$element->setAttribute('href', $src);
$node->parentNode->replaceChild($element, $node);
$element->appendChild($node);
}
}
}
$result->setProcessedText(Html::serialize($dom));
return $result;
}
示例11: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (stristr($text, '<img ') !== FALSE) {
$dom = Html::load($text);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$src = $image->getAttribute("src");
// The src must be non-empty.
if (Unicode::strlen($src) === 0) {
continue;
}
// The src must not already be an external URL
if (stristr($src, 'http://') !== FALSE || stristr($src, 'https://') !== FALSE) {
continue;
}
$url = Url::fromUri('internal:' . $src, array('absolute' => TRUE));
$url_string = $url->toString();
$image->setAttribute('src', $url_string);
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
示例12: getHTMLRestrictions
/**
* {@inheritdoc}
*/
public function getHTMLRestrictions()
{
if ($this->restrictions) {
return $this->restrictions;
}
// Parse the allowed HTML setting, and gradually make the whitelist more
// specific.
$restrictions = ['allowed' => []];
// Make all the tags self-closing, so they will be parsed into direct
// children of the body tag in the DomDocument.
$html = str_replace('>', ' />', $this->settings['allowed_html']);
// Protect any trailing * characters in attribute names, since DomDocument
// strips them as invalid.
$star_protector = '__zqh6vxfbk3cg__';
$html = str_replace('*', $star_protector, $html);
$body_child_nodes = Html::load($html)->getElementsByTagName('body')->item(0)->childNodes;
foreach ($body_child_nodes as $node) {
if ($node->nodeType !== XML_ELEMENT_NODE) {
// Skip the empty text nodes inside tags.
continue;
}
$tag = $node->tagName;
if ($node->hasAttributes()) {
// Mark the tag as allowed, assigning TRUE for each attribute name if
// all values are allowed, or an array of specific allowed values.
$restrictions['allowed'][$tag] = [];
// Iterate over any attributes, and mark them as allowed.
foreach ($node->attributes as $name => $attribute) {
// Put back any trailing * on wildcard attribute name.
$name = str_replace($star_protector, '*', $name);
if ($attribute->value === '') {
// If the value is the empty string all values are allowed.
$restrictions['allowed'][$tag][$name] = TRUE;
} else {
// A non-empty attribute value is assigned, mark each of the
// specified attribute values as allowed.
foreach (preg_split('/\\s+/', $attribute->value, -1, PREG_SPLIT_NO_EMPTY) as $value) {
// Put back any trailing * on wildcard attribute value.
$value = str_replace($star_protector, '*', $value);
$restrictions['allowed'][$tag][$name][$value] = TRUE;
}
}
}
} else {
// Mark the tag as allowed, but with no attributes allowed.
$restrictions['allowed'][$tag] = FALSE;
}
}
// The 'style' and 'on*' ('onClick' etc.) attributes are always forbidden,
// and are removed by Xss::filter().
// The 'lang', and 'dir' attributes apply to all elements and are always
// allowed. The value whitelist for the 'dir' attribute is enforced by
// self::filterAttributes(). Note that those two attributes are in the
// short list of globally usable attributes in HTML5. They are always
// allowed since the correct values of lang and dir may only be known to
// the content author. Of the other global attributes, they are not usually
// added by hand to content, and especially the class attribute can have
// undesired visual effects by allowing content authors to apply any
// available style, so specific values should be explicitly whitelisted.
// @see http://www.w3.org/TR/html5/dom.html#global-attributes
$restrictions['allowed']['*'] = ['style' => FALSE, 'on*' => FALSE, 'lang' => TRUE, 'dir' => ['ltr' => TRUE, 'rtl' => TRUE]];
// Save this calculated result for re-use.
$this->restrictions = $restrictions;
return $restrictions;
}
示例13: filterXssDataAttributes
/**
* Applies a very permissive XSS/HTML filter to data-attributes.
*
* @param string $html
* The string to apply the data-attributes filtering to.
*
* @return string
* The filtered string.
*/
protected static function filterXssDataAttributes($html)
{
if (stristr($html, 'data-') !== FALSE) {
$dom = Html::load($html);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//@*[starts-with(name(.), "data-")]') as $node) {
// The data-attributes contain an HTML-encoded value, so we need to
// decode the value, apply XSS filtering and then re-save as encoded
// value. There is no need to explicitly decode $node->value, since the
// DOMAttr::value getter returns the decoded value.
$value = Xss::filterAdmin($node->value);
$node->value = Html::escape($value);
}
$html = Html::serialize($dom);
}
return $html;
}
示例14: array
/**
* Tests post-render cache-integrated 'render_cache_placeholder' child
* element.
*/
function testDrupalRenderChildElementRenderCachePlaceholder()
{
$container = array('#type' => 'container');
$context = array('bar' => $this->randomContextValue());
$callback = 'common_test_post_render_cache_placeholder';
$placeholder = drupal_render_cache_generate_placeholder($callback, $context);
$test_element = array('#post_render_cache' => array($callback => array($context)), '#markup' => $placeholder, '#prefix' => '<foo>', '#suffix' => '</foo>');
$container['test_element'] = $test_element;
$expected_output = '<div><foo><bar>' . $context['bar'] . '</bar></foo></div>' . "\n";
// #cache disabled.
drupal_static_reset('_drupal_add_js');
$element = $container;
$output = drupal_render($element);
$this->assertIdentical($output, $expected_output, 'Placeholder was replaced in output');
$settings = $this->parseDrupalSettings(drupal_get_js());
$this->assertIdentical($settings['common_test'], $context, '#attached is modified; JavaScript setting is added to page.');
// The cache system is turned off for POST requests.
$request_method = \Drupal::request()->getMethod();
\Drupal::request()->setMethod('GET');
// GET request: #cache enabled, cache miss.
drupal_static_reset('_drupal_add_js');
$element = $container;
$element['#cache'] = array('cid' => 'render_cache_placeholder_test_GET');
$element['test_element']['#cache'] = array('cid' => 'render_cache_placeholder_test_child_GET');
// Simulate element rendering in a template, where sub-items of a renderable
// can be sent to drupal_render() before the parent.
$child =& $element['test_element'];
$element['#children'] = drupal_render($child, TRUE);
// Eventually, drupal_render() gets called on the root element.
$output = drupal_render($element);
$this->assertIdentical($output, $expected_output, 'Placeholder was replaced in output');
$this->assertTrue(isset($element['#printed']), 'No cache hit');
$this->assertIdentical($element['#markup'], $expected_output, 'Placeholder was replaced in #markup.');
$settings = $this->parseDrupalSettings(drupal_get_js());
$this->assertIdentical($settings['common_test'], $context, '#attached is modified; JavaScript setting is added to page.');
// GET request: validate cached data for child element.
$child_tokens = $element['test_element']['#post_render_cache']['common_test_post_render_cache_placeholder'][0]['token'];
$parent_tokens = $element['#post_render_cache']['common_test_post_render_cache_placeholder'][0]['token'];
$expected_token = $child_tokens;
$element = array('#cache' => array('cid' => 'render_cache_placeholder_test_child_GET'));
$cached_element = \Drupal::cache('render')->get(drupal_render_cid_create($element))->data;
// Parse unique token out of the cached markup.
$dom = Html::load($cached_element['#markup']);
$xpath = new \DOMXPath($dom);
$nodes = $xpath->query('//*[@token]');
$this->assertTrue($nodes->length, 'The token attribute was found in the cached child element markup');
$token = '';
if ($nodes->length) {
$token = $nodes->item(0)->getAttribute('token');
}
$this->assertIdentical($token, $expected_token, 'The tokens are identical for the child element');
// Verify the token is in the cached element.
$expected_element = array('#markup' => '<foo><drupal-render-cache-placeholder callback="common_test_post_render_cache_placeholder" token="' . $expected_token . '"></drupal-render-cache-placeholder></foo>', '#post_render_cache' => array('common_test_post_render_cache_placeholder' => array($context)), '#cache' => array('tags' => array('rendered' => TRUE)));
$this->assertIdentical($cached_element, $expected_element, 'The correct data is cached for the child element: the stored #markup and #attached properties are not affected by #post_render_cache callbacks.');
// GET request: validate cached data (for the parent/entire render array).
$element = array('#cache' => array('cid' => 'render_cache_placeholder_test_GET'));
$cached_element = \Drupal::cache('render')->get(drupal_render_cid_create($element))->data;
// Parse unique token out of the cached markup.
$dom = Html::load($cached_element['#markup']);
$xpath = new \DOMXPath($dom);
$nodes = $xpath->query('//*[@token]');
$this->assertTrue($nodes->length, 'The token attribute was found in the cached parent element markup');
$token = '';
if ($nodes->length) {
$token = $nodes->item(0)->getAttribute('token');
}
$this->assertIdentical($token, $expected_token, 'The tokens are identical for the parent element');
// Verify the token is in the cached element.
$expected_element = array('#markup' => '<div><foo><drupal-render-cache-placeholder callback="common_test_post_render_cache_placeholder" token="' . $expected_token . '"></drupal-render-cache-placeholder></foo></div>' . "\n", '#post_render_cache' => array('common_test_post_render_cache_placeholder' => array($context)), '#cache' => array('tags' => array('rendered' => TRUE)));
$this->assertIdentical($cached_element, $expected_element, 'The correct data is cached for the parent element: the stored #markup and #attached properties are not affected by #post_render_cache callbacks.');
// GET request: validate cached data.
// Check the cache of the child element again after the parent has been
// rendered.
$element = array('#cache' => array('cid' => 'render_cache_placeholder_test_child_GET'));
$cached_element = \Drupal::cache('render')->get(drupal_render_cid_create($element))->data;
// Verify that the child element contains the correct
// render_cache_placeholder markup.
$expected_token = $child_tokens;
$dom = Html::load($cached_element['#markup']);
$xpath = new \DOMXPath($dom);
$nodes = $xpath->query('//*[@token]');
$this->assertTrue($nodes->length, 'The token attribute was found in the cached child element markup');
$token = '';
if ($nodes->length) {
$token = $nodes->item(0)->getAttribute('token');
}
$this->assertIdentical($token, $expected_token, 'The tokens are identical for the child element');
// Verify the token is in the cached element.
$expected_element = array('#markup' => '<foo><drupal-render-cache-placeholder callback="common_test_post_render_cache_placeholder" token="' . $expected_token . '"></drupal-render-cache-placeholder></foo>', '#post_render_cache' => array('common_test_post_render_cache_placeholder' => array($context)), '#cache' => array('tags' => array('rendered' => TRUE)));
$this->assertIdentical($cached_element, $expected_element, 'The correct data is cached for the child element: the stored #markup and #attached properties are not affected by #post_render_cache callbacks.');
// GET request: #cache enabled, cache hit.
drupal_static_reset('_drupal_add_js');
$element = $container;
$element['#cache'] = array('cid' => 'render_cache_placeholder_test_GET');
// Simulate element rendering in a template, where sub-items of a renderable
// can be sent to drupal_render before the parent.
//.........这里部分代码省略.........
示例15: processEmbeds
/**
* {@inheritdoc}
*/
public function processEmbeds($text)
{
$document = Html::load($text);
$xpath = new \DOMXPath($document);
foreach ($xpath->query('//oembed') as $node) {
$embed = $this->getEmbedObject($node->nodeValue);
if (!empty($embed) && !empty($embed->html)) {
$this->swapEmbedHtml($node, $embed);
}
}
return Html::serialize($document);
}