[TASK] Use arrays in str_replace() calls
[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(
276 array(
277 'LEGACY_NAMESPACE_SEPARATOR',
278 'FLUID_NAMESPACE_SEPARATOR'
279 ),
280 array(
281 preg_quote(\TYPO3\CMS\Fluid\Fluid::LEGACY_NAMESPACE_SEPARATOR),
282 preg_quote(\TYPO3\CMS\Fluid\Fluid::NAMESPACE_SEPARATOR)
283 ),
284 self::$SCAN_PATTERN_NAMESPACEDECLARATION
285 );
286 }
287
288 /**
289 * Injects Fluid settings
290 *
291 * @param array $settings
292 */
293 public function injectSettings(array $settings) {
294 $this->settings = $settings;
295 }
296
297 /**
298 * Set the configuration for the parser.
299 *
300 * @param \TYPO3\CMS\Fluid\Core\Parser\Configuration $configuration
301 * @return void
302 */
303 public function setConfiguration(\TYPO3\CMS\Fluid\Core\Parser\Configuration $configuration = NULL) {
304 $this->configuration = $configuration;
305 }
306
307 /**
308 * Parses a given template string and returns a parsed template object.
309 *
310 * The resulting ParsedTemplate can then be rendered by calling evaluate() on it.
311 *
312 * Normally, you should use a subclass of AbstractTemplateView instead of calling the
313 * TemplateParser directly.
314 *
315 * @param string $templateString The template to parse as a string
316 * @return \TYPO3\CMS\Fluid\Core\Parser\ParsedTemplateInterface Parsed template
317 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
318 */
319 public function parse($templateString) {
320 if (!is_string($templateString)) {
321 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Parse requires a template string as argument, ' . gettype($templateString) . ' given.', 1224237899);
322 }
323 $this->reset();
324
325 $templateString = $this->extractNamespaceDefinitions($templateString);
326 $splitTemplate = $this->splitTemplateAtDynamicTags($templateString);
327
328 $parsingState = $this->buildObjectTree($splitTemplate, self::CONTEXT_OUTSIDE_VIEWHELPER_ARGUMENTS);
329
330 $variableContainer = $parsingState->getVariableContainer();
331 if ($variableContainer !== NULL && $variableContainer->exists('layoutName')) {
332 $parsingState->setLayoutNameNode($variableContainer->get('layoutName'));
333 }
334
335 return $parsingState;
336 }
337
338 /**
339 * Gets the namespace definitions found.
340 *
341 * @return array Namespace identifiers and their component name prefix
342 */
343 public function getNamespaces() {
344 return $this->namespaces;
345 }
346
347 /**
348 * Resets the parser to its default values.
349 *
350 * @return void
351 */
352 protected function reset() {
353 $this->namespaces = array(
354 'f' => 'TYPO3\\CMS\\Fluid\\ViewHelpers'
355 );
356 }
357
358 /**
359 * Extracts namespace definitions out of the given template string and sets
360 * $this->namespaces.
361 *
362 * @param string $templateString Template string to extract the namespaces from
363 * @return string The updated template string without namespace declarations inside
364 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception if a namespace can't be resolved or has been declared already
365 */
366 protected function extractNamespaceDefinitions($templateString) {
367 $matches = array();
368 preg_match_all(self::$SCAN_PATTERN_XMLNSDECLARATION, $templateString, $matches, PREG_SET_ORDER);
369 foreach ($matches as $match) {
370 // skip reserved "f" namespace identifier
371 if ($match['identifier'] === 'f') {
372 continue;
373 }
374 if (array_key_exists($match['identifier'], $this->namespaces)) {
375 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception(sprintf('Namespace identifier "%s" is already registered. Do not re-declare namespaces!', $match['identifier']), 1331135889);
376 }
377 if (isset($this->settings['namespaces'][$match['xmlNamespace']])) {
378 $phpNamespace = $this->settings['namespaces'][$match['xmlNamespace']];
379 } else {
380 $matchedPhpNamespace = array();
381 if (preg_match(self::$SCAN_PATTERN_DEFAULT_XML_NAMESPACE, $match['xmlNamespace'], $matchedPhpNamespace) === 0) {
382 continue;
383 }
384 $phpNamespace = str_replace('/', '\\', $matchedPhpNamespace['PhpNamespace']);
385 }
386 $this->namespaces[$match['identifier']] = $phpNamespace;
387 }
388 $matches = array();
389 preg_match_all(self::$SCAN_PATTERN_NAMESPACEDECLARATION, $templateString, $matches, PREG_SET_ORDER);
390 foreach ($matches as $match) {
391 if (array_key_exists($match['identifier'], $this->namespaces)) {
392 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception(sprintf('Namespace identifier "%s" is already registered. Do not re-declare namespaces!', $match['identifier']), 1224241246);
393 }
394 $this->namespaces[$match['identifier']] = $match['phpNamespace'];
395 }
396 if ($matches !== array()) {
397 $templateString = preg_replace(self::$SCAN_PATTERN_NAMESPACEDECLARATION, '', $templateString);
398 }
399
400 return $templateString;
401 }
402
403 /**
404 * Splits the template string on all dynamic tags found.
405 *
406 * @param string $templateString Template string to split.
407 * @return array Splitted template
408 */
409 protected function splitTemplateAtDynamicTags($templateString) {
410 $regularExpression = $this->prepareTemplateRegularExpression(self::$SPLIT_PATTERN_TEMPLATE_DYNAMICTAGS);
411 return preg_split($regularExpression, $templateString, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
412 }
413
414 /**
415 * Build object tree from the split template
416 *
417 * @param array $splitTemplate The split template, so that every tag with a namespace declaration is already a separate array element.
418 * @param integer $context one of the CONTEXT_* constants, defining whether we are inside or outside of ViewHelper arguments currently.
419 * @return \TYPO3\CMS\Fluid\Core\Parser\ParsingState
420 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
421 */
422 protected function buildObjectTree($splitTemplate, $context) {
423 $regularExpression_openingViewHelperTag = $this->prepareTemplateRegularExpression(self::$SCAN_PATTERN_TEMPLATE_VIEWHELPERTAG);
424 $regularExpression_closingViewHelperTag = $this->prepareTemplateRegularExpression(self::$SCAN_PATTERN_TEMPLATE_CLOSINGVIEWHELPERTAG);
425
426 $state = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\ParsingState');
427 $rootNode = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\RootNode');
428 $state->setRootNode($rootNode);
429 $state->pushNodeToStack($rootNode);
430
431 foreach ($splitTemplate as $templateElement) {
432 $matchedVariables = array();
433 if (preg_match(self::$SCAN_PATTERN_CDATA, $templateElement, $matchedVariables) > 0) {
434 $this->textHandler($state, $matchedVariables[1]);
435 } elseif (preg_match($regularExpression_openingViewHelperTag, $templateElement, $matchedVariables) > 0) {
436 $this->openingViewHelperTagHandler($state, $matchedVariables['NamespaceIdentifier'], $matchedVariables['MethodIdentifier'], $matchedVariables['Attributes'], ($matchedVariables['Selfclosing'] === '' ? FALSE : TRUE));
437 } elseif (preg_match($regularExpression_closingViewHelperTag, $templateElement, $matchedVariables) > 0) {
438 $this->closingViewHelperTagHandler($state, $matchedVariables['NamespaceIdentifier'], $matchedVariables['MethodIdentifier']);
439 } else {
440 $this->textAndShorthandSyntaxHandler($state, $templateElement, $context);
441 }
442 }
443
444 if ($state->countNodeStack() !== 1) {
445 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Not all tags were closed!', 1238169398);
446 }
447 return $state;
448 }
449
450 /**
451 * Handles an opening or self-closing view helper tag.
452 *
453 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state Current parsing state
454 * @param string $namespaceIdentifier Namespace identifier - being looked up in $this->namespaces
455 * @param string $methodIdentifier Method identifier
456 * @param string $arguments Arguments string, not yet parsed
457 * @param boolean $selfclosing true, if the tag is a self-closing tag.
458 * @return void
459 */
460 protected function openingViewHelperTagHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $namespaceIdentifier, $methodIdentifier, $arguments, $selfclosing) {
461 $argumentsObjectTree = $this->parseArguments($arguments);
462 $this->initializeViewHelperAndAddItToStack($state, $namespaceIdentifier, $methodIdentifier, $argumentsObjectTree);
463
464 if ($selfclosing) {
465 $node = $state->popNodeFromStack();
466 $this->callInterceptor($node, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_CLOSING_VIEWHELPER, $state);
467 }
468 }
469
470 /**
471 * Initialize the given ViewHelper and adds it to the current node and to
472 * the stack.
473 *
474 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state Current parsing state
475 * @param string $namespaceIdentifier Namespace identifier - being looked up in $this->namespaces
476 * @param string $methodIdentifier Method identifier
477 * @param array $argumentsObjectTree Arguments object tree
478 * @return void
479 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
480 */
481 protected function initializeViewHelperAndAddItToStack(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $namespaceIdentifier, $methodIdentifier, $argumentsObjectTree) {
482 if (!array_key_exists($namespaceIdentifier, $this->namespaces)) {
483 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Namespace could not be resolved. This exception should never be thrown!', 1224254792);
484 }
485 $viewHelper = $this->objectManager->get($this->resolveViewHelperName($namespaceIdentifier, $methodIdentifier));
486
487 // The following three checks are only done *in an uncached template*, and not needed anymore in the cached version
488 $expectedViewHelperArguments = $viewHelper->prepareArguments();
489 $this->abortIfUnregisteredArgumentsExist($expectedViewHelperArguments, $argumentsObjectTree);
490 $this->abortIfRequiredArgumentsAreMissing($expectedViewHelperArguments, $argumentsObjectTree);
491 $this->rewriteBooleanNodesInArgumentsObjectTree($expectedViewHelperArguments, $argumentsObjectTree);
492
493 $currentViewHelperNode = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ViewHelperNode', $viewHelper, $argumentsObjectTree);
494
495 $state->getNodeFromStack()->addChildNode($currentViewHelperNode);
496
497 if ($viewHelper instanceof \TYPO3\CMS\Fluid\Core\ViewHelper\Facets\ChildNodeAccessInterface && !($viewHelper instanceof \TYPO3\CMS\Fluid\Core\ViewHelper\Facets\CompilableInterface)) {
498 $state->setCompilable(FALSE);
499 }
500
501 // PostParse Facet
502 if ($viewHelper instanceof \TYPO3\CMS\Fluid\Core\ViewHelper\Facets\PostParseInterface) {
503 // Don't just use $viewHelper::postParseEvent(...),
504 // as this will break with PHP < 5.3.
505 call_user_func(array($viewHelper, 'postParseEvent'), $currentViewHelperNode, $argumentsObjectTree, $state->getVariableContainer());
506 }
507
508 $this->callInterceptor($currentViewHelperNode, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_OPENING_VIEWHELPER, $state);
509
510 $state->pushNodeToStack($currentViewHelperNode);
511 }
512
513 /**
514 * Throw an exception if there are arguments which were not registered
515 * before.
516 *
517 * @param array $expectedArguments Array of \TYPO3\CMS\Fluid\Core\ViewHelper\ArgumentDefinition of all expected arguments
518 * @param array $actualArguments Actual arguments
519 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
520 */
521 protected function abortIfUnregisteredArgumentsExist($expectedArguments, $actualArguments) {
522 $expectedArgumentNames = array();
523 foreach ($expectedArguments as $expectedArgument) {
524 $expectedArgumentNames[] = $expectedArgument->getName();
525 }
526
527 foreach (array_keys($actualArguments) as $argumentName) {
528 if (!in_array($argumentName, $expectedArgumentNames)) {
529 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Argument "' . $argumentName . '" was not registered.', 1237823695);
530 }
531 }
532 }
533
534 /**
535 * Throw an exception if required arguments are missing
536 *
537 * @param array $expectedArguments Array of \TYPO3\CMS\Fluid\Core\ViewHelper\ArgumentDefinition of all expected arguments
538 * @param array $actualArguments Actual arguments
539 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
540 */
541 protected function abortIfRequiredArgumentsAreMissing($expectedArguments, $actualArguments) {
542 $actualArgumentNames = array_keys($actualArguments);
543 foreach ($expectedArguments as $expectedArgument) {
544 if ($expectedArgument->isRequired() && !in_array($expectedArgument->getName(), $actualArgumentNames)) {
545 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Required argument "' . $expectedArgument->getName() . '" was not supplied.', 1237823699);
546 }
547 }
548 }
549
550 /**
551 * Wraps the argument tree, if a node is boolean, into a Boolean syntax tree node
552 *
553 * @param array $argumentDefinitions the argument definitions, key is the argument name, value is the ArgumentDefinition object
554 * @param array $argumentsObjectTree the arguments syntax tree, key is the argument name, value is an AbstractNode
555 * @return void
556 */
557 protected function rewriteBooleanNodesInArgumentsObjectTree($argumentDefinitions, &$argumentsObjectTree) {
558 foreach ($argumentDefinitions as $argumentName => $argumentDefinition) {
559 if ($argumentDefinition->getType() === 'boolean' && isset($argumentsObjectTree[$argumentName])) {
560 $argumentsObjectTree[$argumentName] = new \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\BooleanNode($argumentsObjectTree[$argumentName]);
561 }
562 }
563 }
564
565 /**
566 * Resolve a viewhelper name.
567 *
568 * @param string $namespaceIdentifier Namespace identifier for the view helper.
569 * @param string $methodIdentifier Method identifier, might be hierarchical like "link.url"
570 * @return string The fully qualified class name of the viewhelper
571 */
572 protected function resolveViewHelperName($namespaceIdentifier, $methodIdentifier) {
573 $explodedViewHelperName = explode('.', $methodIdentifier);
574 $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;
575 if (count($explodedViewHelperName) > 1) {
576 $className = implode($namespaceSeparator, array_map('ucfirst', $explodedViewHelperName));
577 } else {
578 $className = ucfirst($explodedViewHelperName[0]);
579 }
580 $className .= 'ViewHelper';
581 $name = $this->namespaces[$namespaceIdentifier] . $namespaceSeparator . $className;
582 $name = \TYPO3\CMS\Core\Core\ClassLoader::getClassNameForAlias($name);
583 return $name;
584 }
585
586 /**
587 * Handles a closing view helper tag
588 *
589 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state The current parsing state
590 * @param string $namespaceIdentifier Namespace identifier for the closing tag.
591 * @param string $methodIdentifier Method identifier.
592 * @return void
593 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
594 */
595 protected function closingViewHelperTagHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $namespaceIdentifier, $methodIdentifier) {
596 if (!array_key_exists($namespaceIdentifier, $this->namespaces)) {
597 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Namespace could not be resolved. This exception should never be thrown!', 1224256186);
598 }
599 $lastStackElement = $state->popNodeFromStack();
600 if (!($lastStackElement instanceof \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\ViewHelperNode)) {
601 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('You closed a templating tag which you never opened!', 1224485838);
602 }
603 if ($lastStackElement->getViewHelperClassName() != $this->resolveViewHelperName($namespaceIdentifier, $methodIdentifier)) {
604 throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Templating tags not properly nested. Expected: ' . $lastStackElement->getViewHelperClassName() . '; Actual: ' . $this->resolveViewHelperName($namespaceIdentifier, $methodIdentifier), 1224485398);
605 }
606 $this->callInterceptor($lastStackElement, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_CLOSING_VIEWHELPER, $state);
607 }
608
609 /**
610 * Handles the appearance of an object accessor (like {posts.author.email}).
611 * Creates a new instance of \TYPO3\CMS\Fluid\ObjectAccessorNode.
612 *
613 * Handles ViewHelpers as well which are in the shorthand syntax.
614 *
615 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state The current parsing state
616 * @param string $objectAccessorString String which identifies which objects to fetch
617 * @param string $delimiter
618 * @param string $viewHelperString
619 * @param string $additionalViewHelpersString
620 * @return void
621 */
622 protected function objectAccessorHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $objectAccessorString, $delimiter, $viewHelperString, $additionalViewHelpersString) {
623 $viewHelperString .= $additionalViewHelpersString;
624 $numberOfViewHelpers = 0;
625
626 // The following post-processing handles a case when there is only a ViewHelper, and no Object Accessor.
627 // Resolves bug #5107.
628 if (strlen($delimiter) === 0 && strlen($viewHelperString) > 0) {
629 $viewHelperString = $objectAccessorString . $viewHelperString;
630 $objectAccessorString = '';
631 }
632
633 // ViewHelpers
634 $matches = array();
635 if (strlen($viewHelperString) > 0 && preg_match_all(self::$SPLIT_PATTERN_SHORTHANDSYNTAX_VIEWHELPER, $viewHelperString, $matches, PREG_SET_ORDER) > 0) {
636 // The last ViewHelper has to be added first for correct chaining.
637 foreach (array_reverse($matches) as $singleMatch) {
638 if (strlen($singleMatch['ViewHelperArguments']) > 0) {
639 $arguments = $this->postProcessArgumentsForObjectAccessor(
640 $this->recursiveArrayHandler($singleMatch['ViewHelperArguments'])
641 );
642 } else {
643 $arguments = array();
644 }
645 $this->initializeViewHelperAndAddItToStack($state, $singleMatch['NamespaceIdentifier'], $singleMatch['MethodIdentifier'], $arguments);
646 $numberOfViewHelpers++;
647 }
648 }
649
650 // Object Accessor
651 if (strlen($objectAccessorString) > 0) {
652
653 $node = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ObjectAccessorNode', $objectAccessorString);
654 $this->callInterceptor($node, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_OBJECTACCESSOR, $state);
655
656 $state->getNodeFromStack()->addChildNode($node);
657 }
658
659 // Close ViewHelper Tags if needed.
660 for ($i=0; $i<$numberOfViewHelpers; $i++) {
661 $node = $state->popNodeFromStack();
662 $this->callInterceptor($node, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_CLOSING_VIEWHELPER, $state);
663 }
664 }
665
666 /**
667 * Call all interceptors registered for a given interception point.
668 *
669 * @param \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\NodeInterface $node The syntax tree node which can be modified by the interceptors.
670 * @param integer $interceptionPoint the interception point. One of the \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_* constants.
671 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state the parsing state
672 * @return void
673 */
674 protected function callInterceptor(\TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\NodeInterface &$node, $interceptionPoint, \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state) {
675 if ($this->configuration !== NULL) {
676 // $this->configuration is UNSET inside the arguments of a ViewHelper.
677 // That's why the interceptors are only called if the object accesor is not inside a ViewHelper Argument
678 // This could be a problem if We have a ViewHelper as an argument to another ViewHelper, and an ObjectAccessor nested inside there.
679 // TODO: Clean up this.
680 $interceptors = $this->configuration->getInterceptors($interceptionPoint);
681 if (count($interceptors) > 0) {
682 foreach ($interceptors as $interceptor) {
683 $node = $interceptor->process($node, $interceptionPoint, $state);
684 }
685 }
686 }
687 }
688
689 /**
690 * Post process the arguments for the ViewHelpers in the object accessor
691 * syntax. We need to convert an array into an array of (only) nodes
692 *
693 * @param array $arguments The arguments to be processed
694 * @return array the processed array
695 * @todo This method should become superflous once the rest has been refactored, so that this code is not needed.
696 */
697 protected function postProcessArgumentsForObjectAccessor(array $arguments) {
698 foreach ($arguments as $argumentName => $argumentValue) {
699 if (!($argumentValue instanceof \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode)) {
700 $arguments[$argumentName] = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\TextNode', (string) $argumentValue);
701 }
702 }
703 return $arguments;
704 }
705
706 /**
707 * Parse arguments of a given tag, and build up the Arguments Object Tree
708 * for each argument.
709 * Returns an associative array, where the key is the name of the argument,
710 * and the value is a single Argument Object Tree.
711 *
712 * @param string $argumentsString All arguments as string
713 * @return array An associative array of objects, where the key is the argument name.
714 */
715 protected function parseArguments($argumentsString) {
716 $argumentsObjectTree = array();
717 $matches = array();
718 if (preg_match_all(self::$SPLIT_PATTERN_TAGARGUMENTS, $argumentsString, $matches, PREG_SET_ORDER) > 0) {
719 $configurationBackup = $this->configuration;
720 $this->configuration = NULL;
721 foreach ($matches as $singleMatch) {
722 $argument = $singleMatch['Argument'];
723 $value = $this->unquoteString($singleMatch['ValueQuoted']);
724 $argumentsObjectTree[$argument] = $this->buildArgumentObjectTree($value);
725 }
726 $this->configuration = $configurationBackup;
727 }
728 return $argumentsObjectTree;
729 }
730
731 /**
732 * Build up an argument object tree for the string in $argumentString.
733 * This builds up the tree for a single argument value.
734 *
735 * This method also does some performance optimizations, so in case
736 * no { or < is found, then we just return a TextNode.
737 *
738 * @param string $argumentString
739 * @return SyntaxTree\AbstractNode the corresponding argument object tree.
740 */
741 protected function buildArgumentObjectTree($argumentString) {
742 if (strpos($argumentString, '{') === FALSE && strpos($argumentString, '<') === FALSE) {
743 return $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\TextNode', $argumentString);
744 }
745 $splitArgument = $this->splitTemplateAtDynamicTags($argumentString);
746 $rootNode = $this->buildObjectTree($splitArgument, self::CONTEXT_INSIDE_VIEWHELPER_ARGUMENTS)->getRootNode();
747 return $rootNode;
748 }
749
750 /**
751 * Removes escapings from a given argument string and trims the outermost
752 * quotes.
753 *
754 * This method is meant as a helper for regular expression results.
755 *
756 * @param string $quotedValue Value to unquote
757 * @return string Unquoted value
758 */
759 protected function unquoteString($quotedValue) {
760 switch ($quotedValue[0]) {
761 case '"':
762 $value = str_replace('\\"', '"', preg_replace('/(^"|"$)/', '', $quotedValue));
763 break;
764 case "'":
765 $value = str_replace("\\'", "'", preg_replace('/(^\'|\'$)/', '', $quotedValue));
766 break;
767 default:
768 $value = $quotedValue;
769 }
770 return str_replace('\\\\', '\\', $value);
771 }
772
773 /**
774 * Takes a regular expression template and replaces "NAMESPACE" with the
775 * currently registered namespace identifiers. Returns a regular expression
776 * which is ready to use.
777 *
778 * @param string $regularExpression Regular expression template
779 * @return string Regular expression ready to be used
780 */
781 protected function prepareTemplateRegularExpression($regularExpression) {
782 return str_replace('NAMESPACE', implode('|', array_keys($this->namespaces)), $regularExpression);
783 }
784
785 /**
786 * Handler for everything which is not a ViewHelperNode.
787 *
788 * This includes Text, array syntax, and object accessor syntax.
789 *
790 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state Current parsing state
791 * @param string $text Text to process
792 * @param integer $context one of the CONTEXT_* constants, defining whether we are inside or outside of ViewHelper arguments currently.
793 * @return void
794 */
795 protected function textAndShorthandSyntaxHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $text, $context) {
796 $sections = preg_split($this->prepareTemplateRegularExpression(self::$SPLIT_PATTERN_SHORTHANDSYNTAX), $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
797
798 foreach ($sections as $section) {
799 $matchedVariables = array();
800 if (preg_match(self::$SCAN_PATTERN_SHORTHANDSYNTAX_OBJECTACCESSORS, $section, $matchedVariables) > 0) {
801 $this->objectAccessorHandler($state, $matchedVariables['Object'], $matchedVariables['Delimiter'], isset($matchedVariables['ViewHelper']) ? $matchedVariables['ViewHelper'] : '', isset($matchedVariables['AdditionalViewHelpers']) ? $matchedVariables['AdditionalViewHelpers'] : '');
802 } elseif ($context === self::CONTEXT_INSIDE_VIEWHELPER_ARGUMENTS && preg_match(self::$SCAN_PATTERN_SHORTHANDSYNTAX_ARRAYS, $section, $matchedVariables) > 0) {
803 // We only match arrays if we are INSIDE viewhelper arguments
804 $this->arrayHandler($state, $matchedVariables['Array']);
805 } else {
806 $this->textHandler($state, $section);
807 }
808 }
809 }
810
811 /**
812 * Handler for array syntax. This creates the array object recursively and
813 * adds it to the current node.
814 *
815 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state The current parsing state
816 * @param string $arrayText The array as string.
817 * @return void
818 */
819 protected function arrayHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $arrayText) {
820 $state->getNodeFromStack()->addChildNode(
821 $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ArrayNode', $this->recursiveArrayHandler($arrayText))
822 );
823 }
824
825 /**
826 * Recursive function which takes the string representation of an array and
827 * builds an object tree from it.
828 *
829 * Deals with the following value types:
830 * - Numbers (Integers and Floats)
831 * - Strings
832 * - Variables
833 * - sub-arrays
834 *
835 * @param string $arrayText Array text
836 * @return SyntaxTree\ArrayNode the array node built up
837 * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
838 */
839 protected function recursiveArrayHandler($arrayText) {
840 $matches = array();
841 if (preg_match_all(self::$SPLIT_PATTERN_SHORTHANDSYNTAX_ARRAY_PARTS, $arrayText, $matches, PREG_SET_ORDER) > 0) {
842 $arrayToBuild = array();
843 foreach ($matches as $singleMatch) {
844 $arrayKey = $singleMatch['Key'];
845 if (!empty($singleMatch['VariableIdentifier'])) {
846 $arrayToBuild[$arrayKey] = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ObjectAccessorNode', $singleMatch['VariableIdentifier']);
847 } elseif (array_key_exists('Number', $singleMatch) && (!empty($singleMatch['Number']) || $singleMatch['Number'] === '0')) {
848 $arrayToBuild[$arrayKey] = floatval($singleMatch['Number']);
849 } elseif ((array_key_exists('QuotedString', $singleMatch) && !empty($singleMatch['QuotedString']))) {
850 $argumentString = $this->unquoteString($singleMatch['QuotedString']);
851 $arrayToBuild[$arrayKey] = $this->buildArgumentObjectTree($argumentString);
852 } elseif (array_key_exists('Subarray', $singleMatch) && !empty($singleMatch['Subarray'])) {
853 $arrayToBuild[$arrayKey] = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\ArrayNode', $this->recursiveArrayHandler($singleMatch['Subarray']));
854 } else {
855 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);
856 }
857 }
858 return $arrayToBuild;
859 } else {
860 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);
861 }
862 }
863
864 /**
865 * Text node handler
866 *
867 * @param \TYPO3\CMS\Fluid\Core\Parser\ParsingState $state
868 * @param string $text
869 * @return void
870 */
871 protected function textHandler(\TYPO3\CMS\Fluid\Core\Parser\ParsingState $state, $text) {
872 $node = $this->objectManager->get('TYPO3\\CMS\\Fluid\\Core\\Parser\\SyntaxTree\\TextNode', $text);
873 $this->callInterceptor($node, \TYPO3\CMS\Fluid\Core\Parser\InterceptorInterface::INTERCEPT_TEXT, $state);
874
875 $state->getNodeFromStack()->addChildNode($node);
876 }
877 }