From 85b66b887b565c3002174337426c05cc2aed63f2 Mon Sep 17 00:00:00 2001 From: "J. King" Date: Wed, 9 Feb 2022 23:41:34 -0500 Subject: [PATCH] More porting --- lib/Docopt.php | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/lib/Docopt.php b/lib/Docopt.php index 89d2154..4ee452a 100644 --- a/lib/Docopt.php +++ b/lib/Docopt.php @@ -125,24 +125,49 @@ class Docopt { # parents = [Required, NotRequired, OptionsShortcut, Either, OneOrMore] $parents = [Required::class, NotRequired::class, OptionsShortcut::class, Either::class, OneOrMore::class]; # if any(t in map(type, children) for t in parents): - $anyParentTypeInChildren = array_reduce($children, function($out, $c) use ($parents) { - return $out ?: in_array(get_class($c), $parents); - }, false); - if ($anyParentTypeInChildren) { + // This line and the next three lines do the following: + // 1. Ascertain if there is a child of one of the parent types + // 2. Filter the list for those types and retrieve the first one + // 3. Splice the child out of the list + // In PHP (and maybe even in Python?) these operations are faster + // if one just searches the array and returns the first matching + // offset, using that for the other two operations + $childOffset = null; + foreach ($children as $k => $c) { + if (in_array(get_class($c), $parents)) { + $childOffset = $k; + break; + } + } + if ($childOffset !== null) { # child = [c for c in children if type(c) in parents][0] # children.remove(child) + $child = array_splice($children, $childOffset, 1, [])[0]; # if type(child) is Either: # for c in child.children: # groups.append([c] + children) # elif type(child) is OneOrMore: - # groups.append(child.children * 2 + children) + # groups.append(child.children * 2 + children) # else: # groups.append(child.children + children) + if ($child instanceof Either) { + foreach ($child->children as $c) { + $groups[] = [$c, ...$children]; + } + } elseif ($child instanceof OneOrMore) { + $groups[] = [...$child->children, ...$child->children, ...$children]; + } else { + $groups[] = [...$child->children, ...$children]; + } } # else: - # result.append(children) + else { + # result.append(children) + $result[] = $children; + } } # return Either(*[Required(*e) for e in result]) + return new Either(...$result); // FIXME: This is wrong, but I'm not sure what the Python line does, yet } }