Browse Source

More porting

master
J. King 2 years ago
parent
commit
85b66b887b
  1. 37
      lib/Docopt.php

37
lib/Docopt.php

@ -125,24 +125,49 @@ class Docopt {
# parents = [Required, NotRequired, OptionsShortcut, Either, OneOrMore] # parents = [Required, NotRequired, OptionsShortcut, Either, OneOrMore]
$parents = [Required::class, NotRequired::class, OptionsShortcut::class, Either::class, OneOrMore::class]; $parents = [Required::class, NotRequired::class, OptionsShortcut::class, Either::class, OneOrMore::class];
# if any(t in map(type, children) for t in parents): # if any(t in map(type, children) for t in parents):
$anyParentTypeInChildren = array_reduce($children, function($out, $c) use ($parents) { // This line and the next three lines do the following:
return $out ?: in_array(get_class($c), $parents); // 1. Ascertain if there is a child of one of the parent types
}, false); // 2. Filter the list for those types and retrieve the first one
if ($anyParentTypeInChildren) { // 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] # child = [c for c in children if type(c) in parents][0]
# children.remove(child) # children.remove(child)
$child = array_splice($children, $childOffset, 1, [])[0];
# if type(child) is Either: # if type(child) is Either:
# for c in child.children: # for c in child.children:
# groups.append([c] + children) # groups.append([c] + children)
# elif type(child) is OneOrMore: # elif type(child) is OneOrMore:
# groups.append(child.children * 2 + children) # groups.append(child.children * 2 + children)
# else: # else:
# groups.append(child.children + children) # 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: # else:
# result.append(children) else {
# result.append(children)
$result[] = $children;
}
} }
# return Either(*[Required(*e) for e in result]) # 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
} }
} }

Loading…
Cancel
Save