d8d832037ee824d1ee815d12107f744b35e87c9a
[Packages/TYPO3.CMS.git] / typo3 / sysext / fluid / Classes / Core / Parser / TemplateParser.php
1 <?php
2 namespace TYPO3\CMS\Fluid\Core\Parser;
3
4 /* *
5 * This script is backported from the TYPO3 Flow package "TYPO3.Fluid". *
6 * *
7 * It is free software; you can redistribute it and/or modify it under *
8 * the terms of the GNU Lesser General Public License, either version 3 *
9 * of the License, or (at your option) any later version. *
10 * *
11 * The TYPO3 project - inspiring people to share! *
12 * */
13
14 /**
15 * Template parser building up an object syntax tree
16 */
17 class TemplateParser {
18
19 static public $SCAN_PATTERN_NAMESPACEDECLARATION = '/(?<!\\\\){namespace\\s*(?P<identifier>[a-zA-Z]+[a-zA-Z0-9]*)\\s*=\\s*(?P<phpNamespace>(?:[A-Za-z0-9\.]+|Tx)(?:LEGACY_NAMESPACE_SEPARATOR\\w+|FLUID_NAMESPACE_SEPARATOR\\w+)+)\\s*}/m';
20 static public $SCAN_PATTERN_XMLNSDECLARATION = '/\sxmlns:(?P<identifier>.*?)="(?P<xmlNamespace>.*?)"/m';
21
22 /**
23 * The following two constants are used for tracking whether we are currently
24 * parsing ViewHelper arguments or not. This is used to parse arrays only as
25 * ViewHelper argument.
26 */
27 const CONTEXT_INSIDE_VIEWHELPER_ARGUMENTS = 1;
28 const CONTEXT_OUTSIDE_VIEWHELPER_ARGUMENTS = 2;
29
30 /**
31 * This regular expression splits the input string at all dynamic tags, AND
32 * on all <![CDATA[...]]> sections.
33 */
34 static public $SPLIT_PATTERN_TEMPLATE_DYNAMICTAGS = '/
35 (
36 (?: <\\/? # Start dynamic tags
37 (?:(?:NAMESPACE):[a-zA-Z0-9\\.]+) # A tag consists of the namespace prefix and word characters
38 (?: # Begin tag arguments
39 \\s*[a-zA-Z0-9:-]+ # Argument Keys
40 = # =
41 (?> # either... If we have found an argument, we will not back-track (That does the Atomic Bracket)
42 "(?:\\\\"|[^"])*" # a double-quoted string
43 |\'(?:\\\\\'|[^\'])*\' # or a single quoted string
44 )\\s* #
45 )* # Tag arguments can be replaced many times.
46 \\s*
47 \\/?> # Closing tag
48 )
49 |(?: # Start match CDATA section
50 <!\\[CDATA\\[.*?\\]\\]>
51 )
52 )/xs';
53
54 /**
55 * This regular expression scans if the input string is a ViewHelper tag
56 */
57 static public $SCAN_PATTERN_TEMPLATE_VIEWHELPERTAG = '/
58 ^< # A Tag begins with <
59 (?P<NamespaceIdentifier>NAMESPACE): # Then comes the Namespace prefix followed by a :
60 (?P<MethodIdentifier> # Now comes the Name of the ViewHelper
61 [a-zA-Z0-9\\.]+
62 )
63 (?P<Attributes> # Begin Tag Attributes
64 (?: # A tag might have multiple attributes
65 \\s*
66 [a-zA-Z0-9:-]+ # The attribute name
67 = # =
68 (?> # either... # If we have found an argument, we will not back-track (That does the Atomic Bracket)
69 "(?:\\\\"|[^"])*" # a double-quoted string
70 |\'(?:\\\\\'|[^\'])*\' # or a single quoted string
71 ) #
72 \\s*
73 )* # A tag might have multiple attributes
74 ) # End Tag Attributes
75 \\s*
76 (?P<Selfclosing>\\/?) # A tag might be selfclosing
77 >$/x';
78
79 /**
80 * This regular expression scans if the input string is a closing ViewHelper
81 * tag.
82 */
83 static public $SCAN_PATTERN_TEMPLATE_CLOSINGVIEWHELPERTAG = '/^<\\/(?P<NamespaceIdentifier>NAMESPACE):(?P<MethodIdentifier>[a-zA-Z0-9\\.]+)\\s*>$/';
84
85 /**
86 * This regular expression splits the tag arguments into its parts
87 */
88 static public $SPLIT_PATTERN_TAGARGUMENTS = '/
89 (?: #
90 \\s* #
91 (?P<Argument> # The attribute name
92 [a-zA-Z0-9:-]+ #
93 ) #
94 = # =
95 (?> # If we have found an argument, we will not back-track (That does the Atomic Bracket)
96 (?P<ValueQuoted> # either...
97 (?:"(?:\\\\"|[^"])*") # a double-quoted string
98 |(?:\'(?:\\\\\'|[^\'])*\') # or a single quoted string
99 )
100 )\\s*
101 )
102 /xs';
103
104 /**
105 * This pattern detects CDATA sections and outputs the text between opening
106 * and closing CDATA.
107 */
108 static public $SCAN_PATTERN_CDATA = '/^<!\\[CDATA\\[(.*?)\\]\\]>$/s';
109
110 /**
111 * Pattern which splits the shorthand syntax into different tokens. The
112 * "shorthand syntax" is everything like {...}
113 */
114 static public $SPLIT_PATTERN_SHORTHANDSYNTAX = '/
115 (
116 { # Start of shorthand syntax
117 (?: # Shorthand syntax is either composed of...
118 [a-zA-Z0-9\\->_:,.()] # Various characters
119 |"(?:\\\\"|[^"])*" # Double-quoted strings
120 |\'(?:\\\\\'|[^\'])*\' # Single-quoted strings
121 |(?R) # Other shorthand syntaxes inside, albeit not in a quoted string
122 |\\s+ # Spaces
123 )+
124 } # End of shorthand syntax
125 )/x';
126
127 /**
128 * Pattern which detects the object accessor syntax:
129 * {object.some.value}, additionally it detects ViewHelpers like
130 * {f:for(param1:bla)} and chaining like
131 * {object.some.value->f:bla.blubb()->f:bla.blubb2()}
132 *
133 * THIS IS ALMOST THE SAME AS IN $SCAN_PATTERN_SHORTHANDSYNTAX_ARRAYS
134 */
135 static public $SCAN_PATTERN_SHORTHANDSYNTAX_OBJECTACCESSORS = '/
136 ^{ # Start of shorthand syntax
137 # A shorthand syntax is either...
138 (?P<Object>[a-zA-Z0-9\\-_.]*) # ... an object accessor
139 \\s*(?P<Delimiter>(?:->)?)\\s*
140
141 (?P<ViewHelper> # ... a ViewHelper
142 [a-zA-Z0-9]+ # Namespace prefix of ViewHelper (as in $SCAN_PATTERN_TEMPLATE_VIEWHELPERTAG)
143 :
144 [a-zA-Z0-9\\.]+ # Method Identifier (as in $SCAN_PATTERN_TEMPLATE_VIEWHELPERTAG)
145 \\( # Opening parameter brackets of ViewHelper
146 (?P<ViewHelperArguments> # Start submatch for ViewHelper arguments. This is taken from $SCAN_PATTERN_SHORTHANDSYNTAX_ARRAYS
147 (?:
148 \\s*[a-zA-Z0-9\\-_]+ # The keys of the array
149 \\s*:\\s* # Key|Value delimiter :
150 (?: # Possible value options:
151 "(?:\\\\"|[^"])*" # Double qouoted string
152 |\'(?:\\\\\'|[^\'])*\' # Single quoted string
153 |[a-zA-Z0-9\\-_.]+ # variable identifiers
154 |{(?P>ViewHelperArguments)} # Another sub-array
155 ) # END possible value options
156 \\s*,? # There might be a , to separate different parts of the array
157 )* # The above cycle is repeated for all array elements
158 ) # End ViewHelper Arguments submatch
159 \\) # Closing parameter brackets of ViewHelper
160 )?
161 (?P<AdditionalViewHelpers> # There can be more than one ViewHelper chained, by adding more -> and the ViewHelper (recursively)
162 (?:
163 \\s*->\\s*
164 (?P>ViewHelper)
165 )*
166 )
167 }$/x';
168
169 /**
170 * THIS IS ALMOST THE SAME AS $SCAN_PATTERN_SHORTHANDSYNTAX_OBJECTACCESSORS
171 */
172 static public $SPLIT_PATTERN_SHORTHANDSYNTAX_VIEWHELPER = '/
173
174 (?P<NamespaceIdentifier>[a-zA-Z0-9]+) # Namespace prefix of ViewHelper (as in $SCAN_PATTERN_TEMPLATE_VIEWHELPERTAG)
175 :
176 (?P<MethodIdentifier>[a-zA-Z0-9\\.]+)
177 \\( # Opening parameter brackets of ViewHelper
178 (?P<ViewHelperArguments> # Start submatch for ViewHelper arguments. This is taken from $SCAN_PATTERN_SHORTHANDSYNTAX_ARRAYS
179 (?:
180 \\s*[a-zA-Z0-9\\-_]+ # The keys of the array
181 \\s*:\\s* # Key|Value delimiter :
182 (?: # Possible value options:
183 "(?:\\\\"|[^"])*" # Double qouoted string
184 |\'(?:\\\\\'|[^\'])*\' # Single quoted string
185 |[a-zA-Z0-9\\-_.]+ # variable identifiers
186 |{(?P>ViewHelperArguments)} # Another sub-array
187 ) # END possible value options
188 \\s*,? # There might be a , to separate different parts of the array
189 )* # The above cycle is repeated for all array elements
190 ) # End ViewHelper Arguments submatch
191 \\) # Closing parameter brackets of ViewHelper
192 /x';
193
194 /**
195 * Pattern which detects the array/object syntax like in JavaScript, so it
196 * detects strings like:
197 * {object: value, object2: {nested: array}, object3: "Some string"}
198 *
199 * THIS IS ALMOST THE SAME AS IN SCAN_PATTERN_SHORTHANDSYNTAX_OBJECTACCESSORS
200 */
201 static public $SCAN_PATTERN_SHORTHANDSYNTAX_ARRAYS = '/^
202 (?P<Recursion> # Start the recursive part of the regular expression - describing the array syntax
203 { # Each array needs to start with {
204 (?P<Array> # Start submatch
205 (?:
206 \\s*[a-zA-Z0-9\\-_]+ # The keys of the array
207 \\s*:\\s* # Key|Value delimiter :
208 (?: # Possible value options:
209 "(?:\\\\"|[^"])*" # Double qouoted string
210 |\'(?:\\\\\'|[^\'])*\' # Single quoted string
211 |[a-zA-Z0-9\\-_.]+ # variable identifiers
212 |(?P>Recursion) # Another sub-array
213 ) # END possible value options
214 \\s*,? # There might be a , to separate different parts of the array
215 )* # The above cycle is repeated for all array elements
216 ) # End array submatch
217 } # Each array ends with }
218 )$/x';
219
220 /**
221 * This pattern splits an array into its parts. It is quite similar to the
222 * pattern above.
223 */
224 static public $SPLIT_PATTERN_SHORTHANDSYNTAX_ARRAY_PARTS = '/
225 (?P<ArrayPart> # Start submatch
226 (?P<Key>[a-zA-Z0-9\\-_]+) # The keys of the array
227 \\s*:\\s* # Key|Value delimiter :
228 (?: # Possible value options:
229 (?P<QuotedString> # Quoted string
230 (?:"(?:\\\\"|[^"])*")
231 |(?:\'(?:\\\\\'|[^\'])*\')
232 )
233 |(?P<VariableIdentifier>[a-zA-Z][a-zA-Z0-9\\-_.]*) # variable identifiers have to start with a letter
234 |(?P<Number>[0-9.]+) # Number
235 |{\\s*(?P<Subarray>(?:(?P>ArrayPart)\\s*,?\\s*)+)\\s*} # Another sub-array
236 ) # END possible value options
237 ) # End array part submatch
238 /x';
239
240 /**
241 * This pattern detects the default xml namespace
242 *
243 */
244 static public $SCAN_PATTERN_DEFAULT_XML_NAMESPACE = '/^http\:\/\/typo3\.org\/ns\/(?P<PhpNamespace>.+)$/s';
245
246 /**
247 * Namespace identifiers and their component name prefix (Associative array).
248 * @var array
249 */
250 protected $namespaces = array(
251 'f' => 'TYPO3\\CMS\\Fluid\\ViewHelpers'
252 );
253
254 /**
255 * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
256 * @inject
257 */
258 protected $objectManager;
259
260 /**
261 * @var \TYPO3\CMS\Fluid\Core\Parser\Configuration
262 */
263 protected $configuration;
264
265 /**
266 * @var array
267 */
268 protected $settings;
269
270 /**
271 * Constructor. Preprocesses the $SCAN_PATTERN_NAMESPACEDECLARATION by
272 * inserting the correct namespace separator.
273 */
274 public function __construct() {
275 self::$SCAN_PATTERN_NAMESPACEDECLARATION = str_replace('LEGACY_NAMESPACE_SEPARATOR', preg_quote(\TYPO3\CMS\Fluid\Fluid::LEGACY_NAMESPACE_SEPARATOR), self::$SCAN_PATTERN_NAMESPACEDECLARATION);
276 self::$SCAN_PATTERN_NAMESPACEDECLARATION = str_replace('FLUID_NAMESPACE_SEPARATOR', preg_quote(\TYPO3\CMS\Fluid\Fluid::NAMESPACE_SEPARATOR), self::$SCAN_PATTERN_NAMESPACEDECLARATION);
277 }
278
279 /**
280 * Injects Fluid settings
281 *
282 * @param array $settings
283 */
284 public function injectSettings(array $settings) {
285 $this->settings = $settings;
286 }
287
288 /**
289 * Set the configuration for the parser.
290 *
291 * @param \TYPO3\CMS\Fluid\Core\Parser\Configuration $configuration
292 * @return void
293 */
294 public function setConfiguration(\TYPO3\CMS\Fluid\Core\Parser\Configuration $configuration = NULL) {
295 $this->configuration = $configuration;
296 }
297
298 /**
299 * Parses a given template string and returns a parsed template object.
300 *
301 * The resulting ParsedTemplate can then be rendered by calling evaluate() on it.
302 *
303 * Normally, you should use a subclass of AbstractTemplateView instead of calling the
304 * TemplateParser directly.
305 *
306 * @param string $templateString The template to parse as a string
307 * @return \TYPO3\CMS\Fluid\Core\Parser\ParsedTemplateInterface Parsed template
308 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
309 */
310 public function parse($templateString) {
311 if (!is_string($templateString)) {
312 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Parse requires a template string as argument, ' . gettype($templateString) . ' given.', 1224237899);
313 }
314 $this->reset();
315
316 $templateString = $this->extractNamespaceDefinitions($templateString);
317 $splitTemplate = $this->splitTemplateAtDynamicTags($templateString);
318
319 $parsingState = $this->buildObjectTree($splitTemplate, self::CONTEXT_OUTSIDE_VIEWHELPER_ARGUMENTS);
320
321 $variableContainer = $parsingState->getVariableContainer();
322 if ($variableContainer !== NULL && $variableContainer->exists('layoutName')) {
323 $parsingState->setLayoutNameNode($variableContainer->get('layoutName'));
324 }
325
326 return $parsingState;
327 }
328
329 /**
330 * Gets the namespace definitions found.
331 *
332 * @return array Namespace identifiers and their component name prefix
333 */
334 public function getNamespaces() {
335 return $this->namespaces;
336 }
337
338 /**
339 * Resets the parser to its default values.
340 *
341 * @return void
342 */
343 protected function reset() {
344 $this->namespaces = array(
345 'f' => 'TYPO3\\CMS\\Fluid\\ViewHelpers'
346 );
347 }
348
349 /**
350 * Extracts namespace definitions out of the given template string and sets
351 * $this->namespaces.
352 *
353 * @param string $templateString Template string to extract the namespaces from
354 * @return string The updated template string without namespace declarations inside
355 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception if a namespace can't be resolved or has been declared already
356 */
357 protected function extractNamespaceDefinitions($templateString) {
358 $matches = array();
359 preg_match_all(self::$SCAN_PATTERN_XMLNSDECLARATION, $templateString, $matches, PREG_SET_ORDER);
360 foreach ($matches as $match) {
361 // skip reserved "f" namespace identifier
362 if ($match['identifier'] === 'f') {
363 continue;
364 }
365 if (array_key_exists($match['identifier'], $this->namespaces)) {
366 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception(sprintf('Namespace identifier "%s" is already registered. Do not re-declare namespaces!', $match['identifier']), 1331135889);
367 }
368 if (isset($this->settings['namespaces'][$match['xmlNamespace']])) {
369 $phpNamespace = $this->settings['namespaces'][$match['xmlNamespace']];
370 } else {
371 $matchedPhpNamespace = array();
372 if (preg_match(self::$SCAN_PATTERN_DEFAULT_XML_NAMESPACE, $match['xmlNamespace'], $matchedPhpNamespace) === 0) {
373 continue;
374 }
375 $phpNamespace = str_replace('/', '\\', $matchedPhpNamespace['PhpNamespace']);
376 }
377 $this->namespaces[$match['identifier']] = $phpNamespace;
378 }
379 $matches = array();
380 preg_match_all(self::$SCAN_PATTERN_NAMESPACEDECLARATION, $templateString, $matches, PREG_SET_ORDER);
381 foreach ($matches as $match) {
382 if (array_key_exists($match['identifier'], $this->namespaces)) {
383 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception(sprintf('Namespace identifier "%s" is already registered. Do not re-declare namespaces!', $match['identifier']), 1224241246);
384 }
385 $this->namespaces[$match['identifier']] = $match['phpNamespace'];
386 }
387 if ($matches !== array()) {
388 $templateString = preg_replace(self::$SCAN_PATTERN_NAMESPACEDECLARATION, '', $templateString);
389 }
390
391 return $templateString;
392 }
393
394 /**
395 * Splits the template string on all dynamic tags found.
396 *
397 * @param string $templateString Template string to split.
398 * @return array Splitted template
399 */
400 protected function splitTemplateAtDynamicTags($templateString) {
401 $regularExpression = $this->prepareTemplateRegularExpression(self::$SPLIT_PATTERN_TEMPLATE_DYNAMICTAGS);
402 return preg_split($regularExpression, $templateString, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
403 }
404
405 /**
406 * Build object tree from the split template
407 *
408 * @param array $splitTemplate The split template, so that every tag with a namespace declaration is already a separate array element.
409 * @param integer $context one of the CONTEXT_* constants, defining whether we are inside or outside of ViewHelper arguments currently.
410 * @return \TYPO3\CMS\Fluid\Core\Parser\ParsingState
411 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
412 */
413 protected function buildObjectTree($splitTemplate, $context) {
414 $regularExpression_openingViewHelperTag = $this->prepareTemplateRegularExpression(self::$SCAN_PATTERN_TEMPLATE_VIEWHELPERTAG);
415 $regularExpression_closingViewHelperTag = $this->prepareTemplateRegularExpression(self::$SCAN_PATTERN_TEMPLATE_CLOSINGVIEWHELPERTAG);
416
417 $state = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\ParsingState');
418 $rootNode = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\RootNode');
419 $state->setRootNode($rootNode);
420 $state->pushNodeToStack($rootNode);
421
422 foreach ($splitTemplate as $templateElement) {
423 $matchedVariables = array();
424 if (preg_match(self::$SCAN_PATTERN_CDATA, $templateElement, $matchedVariables) > 0) {
425 $this->textHandler($state, $matchedVariables[1]);
426 } elseif (preg_match($regularExpression_openingViewHelperTag, $templateElement, $matchedVariables) > 0) {
427 $this->openingViewHelperTagHandler($state, $matchedVariables['NamespaceIdentifier'], $matchedVariables['MethodIdentifier'], $matchedVariables['Attributes'], ($matchedVariables['Selfclosing'] === '' ? FALSE : TRUE));
428 } elseif (preg_match($regularExpression_closingViewHelperTag, $templateElement, $matchedVariables) > 0) {
429 $this->closingViewHelperTagHandler($state, $matchedVariables['NamespaceIdentifier'], $matchedVariables['MethodIdentifier']);
430 } else {
431 $this->textAndShorthandSyntaxHandler($state, $templateElement, $context);
432 }
433 }
434
435 if ($state->countNodeStack() !== 1) {
436 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Not all tags were closed!', 1238169398);
437 }
438 return $state;
439 }
440
441 /**
442 * Handles an opening or self-closing view helper tag.
443 *
444 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state Current parsing state
445 * @param string $namespaceIdentifier Namespace identifier - being looked up in $this->namespaces
446 * @param string $methodIdentifier Method identifier
447 * @param string $arguments Arguments string, not yet parsed
448 * @param boolean $selfclosing true, if the tag is a self-closing tag.
449 * @return void
450 */
451 protected function openingViewHelperTagHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $namespaceIdentifier, $methodIdentifier, $arguments, $selfclosing) {
452 $argumentsObjectTree = $this->parseArguments($arguments);
453 $this->initializeViewHelperAndAddItToStack($state, $namespaceIdentifier, $methodIdentifier, $argumentsObjectTree);
454
455 if ($selfclosing) {
456 $node = $state->popNodeFromStack();
457 $this->callInterceptor($node, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_CLOSING_VIEWHELPER, $state);
458 }
459 }
460
461 /**
462 * Initialize the given ViewHelper and adds it to the current node and to
463 * the stack.
464 *
465 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state Current parsing state
466 * @param string $namespaceIdentifier Namespace identifier - being looked up in $this->namespaces
467 * @param string $methodIdentifier Method identifier
468 * @param array $argumentsObjectTree Arguments object tree
469 * @return void
470 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
471 */
472 protected function initializeViewHelperAndAddItToStack(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $namespaceIdentifier, $methodIdentifier, $argumentsObjectTree) {
473 if (!array_key_exists($namespaceIdentifier, $this->namespaces)) {
474 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Namespace could not be resolved. This exception should never be thrown!', 1224254792);
475 }
476 $viewHelper = $this->objectManager->get($this->resolveViewHelperName($namespaceIdentifier, $methodIdentifier));
477
478 // The following three checks are only done *in an uncached template*, and not needed anymore in the cached version
479 $expectedViewHelperArguments = $viewHelper->prepareArguments();
480 $this->abortIfUnregisteredArgumentsExist($expectedViewHelperArguments, $argumentsObjectTree);
481 $this->abortIfRequiredArgumentsAreMissing($expectedViewHelperArguments, $argumentsObjectTree);
482 $this->rewriteBooleanNodesInArgumentsObjectTree($expectedViewHelperArguments, $argumentsObjectTree);
483
484 $currentViewHelperNode = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ViewHelperNode', $viewHelper, $argumentsObjectTree);
485
486 $state->getNodeFromStack()->addChildNode($currentViewHelperNode);
487
488 if ($viewHelper instanceof \TYPO3\CMS\Fluid\Core\ViewHelper\Facets\ChildNodeAccessInterface && !($viewHelper instanceof \TYPO3\CMS\Fluid\Core\ViewHelper\Facets\CompilableInterface)) {
489 $state->setCompilable(FALSE);
490 }
491
492 // PostParse Facet
493 if ($viewHelper instanceof \TYPO3\CMS\Fluid\Core\ViewHelper\Facets\PostParseInterface) {
494 // Don't just use $viewHelper::postParseEvent(...),
495 // as this will break with PHP < 5.3.
496 call_user_func(array($viewHelper, 'postParseEvent'), $currentViewHelperNode, $argumentsObjectTree, $state->getVariableContainer());
497 }
498
499 $this->callInterceptor($currentViewHelperNode, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_OPENING_VIEWHELPER, $state);
500
501 $state->pushNodeToStack($currentViewHelperNode);
502 }
503
504 /**
505 * Throw an exception if there are arguments which were not registered
506 * before.
507 *
508 * @param array $expectedArguments Array of \TYPO3\CMS\Fluid\Core\ViewHelper\ArgumentDefinition of all expected arguments
509 * @param array $actualArguments Actual arguments
510 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
511 */
512 protected function abortIfUnregisteredArgumentsExist($expectedArguments, $actualArguments) {
513 $expectedArgumentNames = array();
514 foreach ($expectedArguments as $expectedArgument) {
515 $expectedArgumentNames[] = $expectedArgument->getName();
516 }
517
518 foreach (array_keys($actualArguments) as $argumentName) {
519 if (!in_array($argumentName, $expectedArgumentNames)) {
520 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Argument "' . $argumentName . '" was not registered.', 1237823695);
521 }
522 }
523 }
524
525 /**
526 * Throw an exception if required arguments are missing
527 *
528 * @param array $expectedArguments Array of \TYPO3\CMS\Fluid\Core\ViewHelper\ArgumentDefinition of all expected arguments
529 * @param array $actualArguments Actual arguments
530 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
531 */
532 protected function abortIfRequiredArgumentsAreMissing($expectedArguments, $actualArguments) {
533 $actualArgumentNames = array_keys($actualArguments);
534 foreach ($expectedArguments as $expectedArgument) {
535 if ($expectedArgument->isRequired() && !in_array($expectedArgument->getName(), $actualArgumentNames)) {
536 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Required argument "' . $expectedArgument->getName() . '" was not supplied.', 1237823699);
537 }
538 }
539 }
540
541 /**
542 * Wraps the argument tree, if a node is boolean, into a Boolean syntax tree node
543 *
544 * @param array $argumentDefinitions the argument definitions, key is the argument name, value is the ArgumentDefinition object
545 * @param array $argumentsObjectTree the arguments syntax tree, key is the argument name, value is an AbstractNode
546 * @return void
547 */
548 protected function rewriteBooleanNodesInArgumentsObjectTree($argumentDefinitions, &$argumentsObjectTree) {
549 foreach ($argumentDefinitions as $argumentName => $argumentDefinition) {
550 if ($argumentDefinition->getType() === 'boolean' && isset($argumentsObjectTree[$argumentName])) {
551 $argumentsObjectTree[$argumentName] = new \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\BooleanNode($argumentsObjectTree[$argumentName]);
552 }
553 }
554 }
555
556 /**
557 * Resolve a viewhelper name.
558 *
559 * @param string $namespaceIdentifier Namespace identifier for the view helper.
560 * @param string $methodIdentifier Method identifier, might be hierarchical like "link.url"
561 * @return string The fully qualified class name of the viewhelper
562 */
563 protected function resolveViewHelperName($namespaceIdentifier, $methodIdentifier) {
564 $explodedViewHelperName = explode('.', $methodIdentifier);
565 $namespaceSeparator = strpos($this->namespaces[$namespaceIdentifier], \TYPO3\CMS\Fluid\Fluid::NAMESPACE_SEPARATOR) !== FALSE ? \TYPO3\CMS\Fluid\Fluid::NAMESPACE_SEPARATOR : \TYPO3\CMS\Fluid\Fluid::LEGACY_NAMESPACE_SEPARATOR;
566 if (count($explodedViewHelperName) > 1) {
567 $className = implode($namespaceSeparator, array_map('ucfirst', $explodedViewHelperName));
568 } else {
569 $className = ucfirst($explodedViewHelperName[0]);
570 }
571 $className .= 'ViewHelper';
572 $name = $this->namespaces[$namespaceIdentifier] . $namespaceSeparator . $className;
573 $name = \TYPO3\CMS\Core\Core\ClassLoader::getClassNameForAlias($name);
574 return $name;
575 }
576
577 /**
578 * Handles a closing view helper tag
579 *
580 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state The current parsing state
581 * @param string $namespaceIdentifier Namespace identifier for the closing tag.
582 * @param string $methodIdentifier Method identifier.
583 * @return void
584 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
585 */
586 protected function closingViewHelperTagHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $namespaceIdentifier, $methodIdentifier) {
587 if (!array_key_exists($namespaceIdentifier, $this->namespaces)) {
588 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Namespace could not be resolved. This exception should never be thrown!', 1224256186);
589 }
590 $lastStackElement = $state->popNodeFromStack();
591 if (!($lastStackElement instanceof \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\ViewHelperNode)) {
592 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('You closed a templating tag which you never opened!', 1224485838);
593 }
594 if ($lastStackElement->getViewHelperClassName() != $this->resolveViewHelperName($namespaceIdentifier, $methodIdentifier)) {
595 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Templating tags not properly nested. Expected: ' . $lastStackElement->getViewHelperClassName() . '; Actual: ' . $this->resolveViewHelperName($namespaceIdentifier, $methodIdentifier), 1224485398);
596 }
597 $this->callInterceptor($lastStackElement, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_CLOSING_VIEWHELPER, $state);
598 }
599
600 /**
601 * Handles the appearance of an object accessor (like {posts.author.email}).
602 * Creates a new instance of \TYPO3\CMS\Fluid\ObjectAccessorNode.
603 *
604 * Handles ViewHelpers as well which are in the shorthand syntax.
605 *
606 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state The current parsing state
607 * @param string $objectAccessorString String which identifies which objects to fetch
608 * @param string $delimiter
609 * @param string $viewHelperString
610 * @param string $additionalViewHelpersString
611 * @return void
612 */
613 protected function objectAccessorHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $objectAccessorString, $delimiter, $viewHelperString, $additionalViewHelpersString) {
614 $viewHelperString .= $additionalViewHelpersString;
615 $numberOfViewHelpers = 0;
616
617 // The following post-processing handles a case when there is only a ViewHelper, and no Object Accessor.
618 // Resolves bug #5107.
619 if (strlen($delimiter) === 0 && strlen($viewHelperString) > 0) {
620 $viewHelperString = $objectAccessorString . $viewHelperString;
621 $objectAccessorString = '';
622 }
623
624 // ViewHelpers
625 $matches = array();
626 if (strlen($viewHelperString) > 0 && preg_match_all(self::$SPLIT_PATTERN_SHORTHANDSYNTAX_VIEWHELPER, $viewHelperString, $matches, PREG_SET_ORDER) > 0) {
627 // The last ViewHelper has to be added first for correct chaining.
628 foreach (array_reverse($matches) as $singleMatch) {
629 if (strlen($singleMatch['ViewHelperArguments']) > 0) {
630 $arguments = $this->postProcessArgumentsForObjectAccessor(
631 $this->recursiveArrayHandler($singleMatch['ViewHelperArguments'])
632 );
633 } else {
634 $arguments = array();
635 }
636 $this->initializeViewHelperAndAddItToStack($state, $singleMatch['NamespaceIdentifier'], $singleMatch['MethodIdentifier'], $arguments);
637 $numberOfViewHelpers++;
638 }
639 }
640
641 // Object Accessor
642 if (strlen($objectAccessorString) > 0) {
643
644 $node = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ObjectAccessorNode', $objectAccessorString);
645 $this->callInterceptor($node, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_OBJECTACCESSOR, $state);
646
647 $state->getNodeFromStack()->addChildNode($node);
648 }
649
650 // Close ViewHelper Tags if needed.
651 for ($i=0; $i<$numberOfViewHelpers; $i++) {
652 $node = $state->popNodeFromStack();
653 $this->callInterceptor($node, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_CLOSING_VIEWHELPER, $state);
654 }
655 }
656
657 /**
658 * Call all interceptors registered for a given interception point.
659 *
660 * @param \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\NodeInterface $node The syntax tree node which can be modified by the interceptors.
661 * @param integer $interceptionPoint the interception point. One of the \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_* constants.
662 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state the parsing state
663 * @return void
664 */
665 protected function callInterceptor(\TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\NodeInterface &$node, $interceptionPoint, \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state) {
666 if ($this->configuration !== NULL) {
667 // $this->configuration is UNSET inside the arguments of a ViewHelper.
668 // That's why the interceptors are only called if the object accesor is not inside a ViewHelper Argument
669 // This could be a problem if We have a ViewHelper as an argument to another ViewHelper, and an ObjectAccessor nested inside there.
670 // TODO: Clean up this.
671 $interceptors = $this->configuration->getInterceptors($interceptionPoint);
672 if (count($interceptors) > 0) {
673 foreach ($interceptors as $interceptor) {
674 $node = $interceptor->process($node, $interceptionPoint, $state);
675 }
676 }
677 }
678 }
679
680 /**
681 * Post process the arguments for the ViewHelpers in the object accessor
682 * syntax. We need to convert an array into an array of (only) nodes
683 *
684 * @param array $arguments The arguments to be processed
685 * @return array the processed array
686 * @todo This method should become superflous once the rest has been refactored, so that this code is not needed.
687 */
688 protected function postProcessArgumentsForObjectAccessor(array $arguments) {
689 foreach ($arguments as $argumentName => $argumentValue) {
690 if (!($argumentValue instanceof \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode)) {
691 $arguments[$argumentName] = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\TextNode', (string) $argumentValue);
692 }
693 }
694 return $arguments;
695 }
696
697 /**
698 * Parse arguments of a given tag, and build up the Arguments Object Tree
699 * for each argument.
700 * Returns an associative array, where the key is the name of the argument,
701 * and the value is a single Argument Object Tree.
702 *
703 * @param string $argumentsString All arguments as string
704 * @return array An associative array of objects, where the key is the argument name.
705 */
706 protected function parseArguments($argumentsString) {
707 $argumentsObjectTree = array();
708 $matches = array();
709 if (preg_match_all(self::$SPLIT_PATTERN_TAGARGUMENTS, $argumentsString, $matches, PREG_SET_ORDER) > 0) {
710 $configurationBackup = $this->configuration;
711 $this->configuration = NULL;
712 foreach ($matches as $singleMatch) {
713 $argument = $singleMatch['Argument'];
714 $value = $this->unquoteString($singleMatch['ValueQuoted']);
715 $argumentsObjectTree[$argument] = $this->buildArgumentObjectTree($value);
716 }
717 $this->configuration = $configurationBackup;
718 }
719 return $argumentsObjectTree;
720 }
721
722 /**
723 * Build up an argument object tree for the string in $argumentString.
724 * This builds up the tree for a single argument value.
725 *
726 * This method also does some performance optimizations, so in case
727 * no { or < is found, then we just return a TextNode.
728 *
729 * @param string $argumentString
730 * @return SyntaxTree\AbstractNode the corresponding argument object tree.
731 */
732 protected function buildArgumentObjectTree($argumentString) {
733 if (strpos($argumentString, '{') === FALSE && strpos($argumentString, '<') === FALSE) {
734 return $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\TextNode', $argumentString);
735 }
736 $splitArgument = $this->splitTemplateAtDynamicTags($argumentString);
737 $rootNode = $this->buildObjectTree($splitArgument, self::CONTEXT_INSIDE_VIEWHELPER_ARGUMENTS)->getRootNode();
738 return $rootNode;
739 }
740
741 /**
742 * Removes escapings from a given argument string and trims the outermost
743 * quotes.
744 *
745 * This method is meant as a helper for regular expression results.
746 *
747 * @param string $quotedValue Value to unquote
748 * @return string Unquoted value
749 */
750 protected function unquoteString($quotedValue) {
751 switch ($quotedValue[0]) {
752 case '"':
753 $value = str_replace('\\"', '"', preg_replace('/(^"|"$)/', '', $quotedValue));
754 break;
755 case "'":
756 $value = str_replace("\\'", "'", preg_replace('/(^\'|\'$)/', '', $quotedValue));
757 break;
758 default:
759 $value = $quotedValue;
760 }
761 return str_replace('\\\\', '\\', $value);
762 }
763
764 /**
765 * Takes a regular expression template and replaces "NAMESPACE" with the
766 * currently registered namespace identifiers. Returns a regular expression
767 * which is ready to use.
768 *
769 * @param string $regularExpression Regular expression template
770 * @return string Regular expression ready to be used
771 */
772 protected function prepareTemplateRegularExpression($regularExpression) {
773 return str_replace('NAMESPACE', implode('|', array_keys($this->namespaces)), $regularExpression);
774 }
775
776 /**
777 * Handler for everything which is not a ViewHelperNode.
778 *
779 * This includes Text, array syntax, and object accessor syntax.
780 *
781 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state Current parsing state
782 * @param string $text Text to process
783 * @param integer $context one of the CONTEXT_* constants, defining whether we are inside or outside of ViewHelper arguments currently.
784 * @return void
785 */
786 protected function textAndShorthandSyntaxHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $text, $context) {
787 $sections = preg_split($this->prepareTemplateRegularExpression(self::$SPLIT_PATTERN_SHORTHANDSYNTAX), $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
788
789 foreach ($sections as $section) {
790 $matchedVariables = array();
791 if (preg_match(self::$SCAN_PATTERN_SHORTHANDSYNTAX_OBJECTACCESSORS, $section, $matchedVariables) > 0) {
792 $this->objectAccessorHandler($state, $matchedVariables['Object'], $matchedVariables['Delimiter'], isset($matchedVariables['ViewHelper']) ? $matchedVariables['ViewHelper'] : '', isset($matchedVariables['AdditionalViewHelpers']) ? $matchedVariables['AdditionalViewHelpers'] : '');
793 } elseif ($context === self::CONTEXT_INSIDE_VIEWHELPER_ARGUMENTS && preg_match(self::$SCAN_PATTERN_SHORTHANDSYNTAX_ARRAYS, $section, $matchedVariables) > 0) {
794 // We only match arrays if we are INSIDE viewhelper arguments
795 $this->arrayHandler($state, $matchedVariables['Array']);
796 } else {
797 $this->textHandler($state, $section);
798 }
799 }
800 }
801
802 /**
803 * Handler for array syntax. This creates the array object recursively and
804 * adds it to the current node.
805 *
806 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state The current parsing state
807 * @param string $arrayText The array as string.
808 * @return void
809 */
810 protected function arrayHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $arrayText) {
811 $state->getNodeFromStack()->addChildNode(
812 $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ArrayNode', $this->recursiveArrayHandler($arrayText))
813 );
814 }
815
816 /**
817 * Recursive function which takes the string representation of an array and
818 * builds an object tree from it.
819 *
820 * Deals with the following value types:
821 * - Numbers (Integers and Floats)
822 * - Strings
823 * - Variables
824 * - sub-arrays
825 *
826 * @param string $arrayText Array text
827 * @return SyntaxTree\ArrayNode the array node built up
828 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
829 */
830 protected function recursiveArrayHandler($arrayText) {
831 $matches = array();
832 if (preg_match_all(self::$SPLIT_PATTERN_SHORTHANDSYNTAX_ARRAY_PARTS, $arrayText, $matches, PREG_SET_ORDER) > 0) {
833 $arrayToBuild = array();
834 foreach ($matches as $singleMatch) {
835 $arrayKey = $singleMatch['Key'];
836 if (!empty($singleMatch['VariableIdentifier'])) {
837 $arrayToBuild[$arrayKey] = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ObjectAccessorNode', $singleMatch['VariableIdentifier']);
838 } elseif (array_key_exists('Number', $singleMatch) && (!empty($singleMatch['Number']) || $singleMatch['Number'] === '0')) {
839 $arrayToBuild[$arrayKey] = floatval($singleMatch['Number']);
840 } elseif ((array_key_exists('QuotedString', $singleMatch) && !empty($singleMatch['QuotedString']))) {
841 $argumentString = $this->unquoteString($singleMatch['QuotedString']);
842 $arrayToBuild[$arrayKey] = $this->buildArgumentObjectTree($argumentString);
843 } elseif (array_key_exists('Subarray', $singleMatch) && !empty($singleMatch['Subarray'])) {
844 $arrayToBuild[$arrayKey] = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ArrayNode', $this->recursiveArrayHandler($singleMatch['Subarray']));
845 } else {
846 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('This exception should never be thrown, as the array value has to be of some type (Value given: "' . var_export($singleMatch, TRUE) . '"). Please post your template to the bugtracker at forge.typo3.org.', 1225136013);
847 }
848 }
849 return $arrayToBuild;
850 } else {
851 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('This exception should never be thrown, there is most likely some error in the regular expressions. Please post your template to the bugtracker at forge.typo3.org.', 1225136013);
852 }
853 }
854
855 /**
856 * Text node handler
857 *
858 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state
859 * @param string $text
860 * @return void
861 */
862 protected function textHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $text) {
863 $node = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\TextNode', $text);
864 $this->callInterceptor($node, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_TEXT, $state);
865
866 $state->getNodeFromStack()->addChildNode($node);
867 }
868 }