Skip to content

Commit

Permalink
Resolve lambdas before beginning filter chains.
Browse files Browse the repository at this point in the history
  • Loading branch information
bobthecow committed May 13, 2024
1 parent 0cadc54 commit fbf7a16
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/Mustache/Compiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -570,18 +570,23 @@ private function variable($id, $filters, $escape, $level)
if (!(%s)) {
throw new Mustache_Exception_UnknownFilterException(%s);
}
$value = call_user_func($filter, $value);%s
$value = call_user_func($filter, %s);%s
';
const FILTER_FIRST_VALUE = '$this->resolveValue($value, $context)';
const FILTER_VALUE = '$value';

/**
* Generate Mustache Template variable filtering PHP source.
*
* If the initial $value is a lambda it will be resolved before starting the filter chain.
*
* @param string[] $filters Array of filters
* @param int $level
* @param bool $first (default: false)
*
* @return string Generated filter PHP source
*/
private function getFilters(array $filters, $level)
private function getFilters(array $filters, $level, $first = true)
{
if (empty($filters)) {
return '';
Expand All @@ -593,8 +598,9 @@ private function getFilters(array $filters, $level)
$findArg = $this->getFindMethodArgs($method);
$callable = $this->getCallable('$filter');
$msg = var_export($name, true);
$value = $first ? self::FILTER_FIRST_VALUE : self::FILTER_VALUE;

return sprintf($this->prepare(self::FILTER, $level), $method, $filter, $findArg, $callable, $msg, $this->getFilters($filters, $level));
return sprintf($this->prepare(self::FILTER, $level), $method, $filter, $findArg, $callable, $msg, $value, $this->getFilters($filters, $level, false));
}

const LINE = '$buffer .= "\n";';
Expand Down
8 changes: 8 additions & 0 deletions test/Mustache/Test/FiveThree/Functional/FiltersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,13 @@ public function lambdaFiltersData()
);

$data = array(
'noop' => function ($value) {
return $value;
},
'people' => $people,
'people_lambda' => function () use ($people) {
return $people;
},
'first_name' => function ($arr) {
return $arr[0]->name;
},
Expand All @@ -225,6 +231,8 @@ public function lambdaFiltersData()
array('{{% FILTERS }}{{ people | last_name }}', $data, 'Charles'),
array('{{% FILTERS }}{{ people | all_names }}', $data, 'Albert, Betty, Charles'),
array('{{% FILTERS }}{{# people | first_person }}{{ name }}{{/ people }}', $data, 'Albert'),
array('{{% FILTERS }}{{# people_lambda | first_person }}{{ name }}{{/ people_lambda }}', $data, 'Albert'),
array('{{% FILTERS }}{{# people_lambda | noop | first_person }}{{ name }}{{/ people_lambda }}', $data, 'Albert'),
);
}
}

0 comments on commit fbf7a16

Please sign in to comment.