From 9026b1abdb2ceaff39d275e65712c2bb79f54e2b Mon Sep 17 00:00:00 2001 From: Aidan Woods Date: Sun, 1 Apr 2018 16:55:10 +0100 Subject: [PATCH 1/2] Add recursive helper for AST, use this for implementation of calling handler recursively --- Parsedown.php | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/Parsedown.php b/Parsedown.php index 382023c..e0783c9 100644 --- a/Parsedown.php +++ b/Parsedown.php @@ -1588,26 +1588,39 @@ class Parsedown protected function handleElementRecursive(array $Element) { - $Element = $this->handle($Element); + return $this->elementApplyRecursive(array($this, 'handle'), $Element); + } + + protected function handleElementsRecursive(array $Elements) + { + return $this->elementsApplyRecursive(array($this, 'handle'), $Elements); + } + + protected function elementApplyRecursive($closure, array $Element) + { + $Element = call_user_func($closure, $Element); if (isset($Element['elements'])) { - $Element['elements'] = $this->handleElementsRecursive($Element['elements']); + $Element['elements'] = $this->elementsApplyRecursive($closure, $Element['elements']); } elseif (isset($Element['element'])) { - $Element['element'] = $this->handleElementRecursive($Element['element']); + $Element['element'] = $this->elementApplyRecursive($closure, $Element['element']); } return $Element; } - protected function handleElementsRecursive(array $Elements) + protected function elementsApplyRecursive($closure, array $Elements) { - return array_map(array($this, 'handleElementRecursive'), $Elements); + return array_map( + array($this, 'elementApplyRecursive'), + array_fill(0, count($Elements), $closure), + $Elements + ); } - protected function element(array $Element) { if ($this->safeMode) From 390fa0da1b2da708ed040455de24fbc085e61a74 Mon Sep 17 00:00:00 2001 From: Aidan Woods Date: Sun, 1 Apr 2018 17:55:32 +0100 Subject: [PATCH 2/2] This is probably faster than duplicating the closure --- Parsedown.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Parsedown.php b/Parsedown.php index e0783c9..d0cf8bc 100644 --- a/Parsedown.php +++ b/Parsedown.php @@ -1614,10 +1614,13 @@ class Parsedown protected function elementsApplyRecursive($closure, array $Elements) { - return array_map( - array($this, 'elementApplyRecursive'), - array_fill(0, count($Elements), $closure), - $Elements + return array_reduce( + $Elements, + function (array $Elements, array $Element) use ($closure) { + $Elements[] = $this->elementApplyRecursive($closure, $Element); + return $Elements; + }, + array() ); }