Skip to content

Instantly share code, notes, and snippets.

@jrenggli
Created August 11, 2016 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrenggli/ef90e670697399bea5cfebeb1630ab64 to your computer and use it in GitHub Desktop.
Save jrenggli/ef90e670697399bea5cfebeb1630ab64 to your computer and use it in GitHub Desktop.
CDATA ViewHelper for Fluid: Only wrapping if CDATA is necessary
<?php
namespace Swisscom\Finapp\ViewHelpers;
// Credits: https://git.typo3.org/Packages/TYPO3.CMS.git/blob_plain/HEAD:/typo3/sysext/fluid/Classes/ViewHelpers/Format/CdataViewHelper.php
// Extended with functionality to only wrap if CDATA is necessary.
// See $predeclaredCharacters
/* *
* This script is backported from the TYPO3 Flow package "TYPO3.Fluid". *
* *
* It is free software; you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License, either version 3 *
* of the License, or (at your option) any later version. *
* *
* The TYPO3 project - inspiring people to share! *
* */
use TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper;
/**
* Outputs an argument/value without any escaping and wraps it with CDATA tags
* if necessary.
*
* PAY SPECIAL ATTENTION TO SECURITY HERE (especially Cross Site Scripting),
* as the output is NOT SANITIZED!
*
* = Examples =
*
* <code title="Child nodes">
* <my:formatCdata>{string}</my:formatCdata>
* </code>
* <output>
* <![CDATA[(Content of {string} without any conversion/escaping)]]>
* </output>
*
* <code title="Value attribute">
* <my:formatCdata value="{string}" />
* </code>
* <output>
* <![CDATA[(Content of {string} without any conversion/escaping)]]>
* </output>
*
* <code title="Inline notation">
* {string -> my:formatCdata()}
* </code>
* <output>
* <![CDATA[(Content of {string} without any conversion/escaping)]]>
* </output>
*
* @api
*/
class FormatCdataViewHelper extends AbstractViewHelper {
/**
* Disable the escaping interceptor because otherwise the child nodes would be escaped before this view helper
* can decode the text's entities.
*
* @var bool
*/
protected $escapingInterceptorEnabled = FALSE;
/**
* Predeclared characters according to XML specification
* http://xml.silmaril.ie/specials.html
*
* @var array
*/
protected $predeclaredCharacters = array ('&', '<', '>', '"', "'");
/**
* @param mixed $value The value to output
* @return string
*/
public function render($value = NULL) {
if ($value === NULL) {
$value = $this->renderChildren();
}
foreach ($this->predeclaredCharacters as $c) {
if (stripos($value, $c) !== false) {
return sprintf('<![CDATA[%s]]>', $value);
}
}
return $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment