HtmlTitleFilter.php in HTML Title 8        
                          
                  
                        
  
  
  
  
  
File
  src/HtmlTitleFilter.php
  
    View source  
  <?php
namespace Drupal\html_title;
use Drupal\Component\Utility\Xss;
use Drupal\Component\Utility\Html;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Render\RendererInterface;
class HtmlTitleFilter {
  
  protected $configFactory;
  
  protected $renderer;
  
  public function __construct(ConfigFactoryInterface $configFactory, RendererInterface $renderer) {
    $this->configFactory = $configFactory;
    $this->renderer = $renderer;
  }
  
  protected function filterXss($title) {
    $dom = new \DOMDocument();
    
    @$dom
      ->loadHTML('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>' . $title . '</body></html>', LIBXML_NOENT);
    $xp = new \DOMXPath($dom);
    $q = "//body//text()";
    $nodes = $xp
      ->query($q);
    foreach ($nodes as $n) {
      $n->nodeValue = htmlspecialchars($n->nodeValue, ENT_QUOTES);
    }
    $body = $dom
      ->saveHTML($dom
      ->getElementsByTagName('body')
      ->item(0));
    
    $body = str_replace('&', '&', $body);
    return Xss::filter($body, $this
      ->getAllowHtmlTags());
  }
  
  public function decodeToText($str) {
    if (is_array($str)) {
      $str = $this->renderer
        ->renderPlain($str);
    }
    return trim($this
      ->filterXss(Html::decodeEntities((string) $str)));
  }
  
  public function decodeToMarkup($str) {
    return Markup::create($this
      ->decodeToText($str));
  }
  
  public function getAllowHtmlTags() {
    $tags = [];
    $html = str_replace('>', ' />', $this->configFactory
      ->get('html_title.settings')
      ->get('allow_html_tags'));
    $body_child_nodes = Html::load($html)
      ->getElementsByTagName('body')
      ->item(0)->childNodes;
    foreach ($body_child_nodes as $node) {
      if ($node->nodeType === XML_ELEMENT_NODE) {
        $tags[] = $node->tagName;
      }
    }
    return $tags;
  }
}