Skip to content

Commit

Permalink
Simplify lastname parser by getting rid of array reversals
Browse files Browse the repository at this point in the history
  • Loading branch information
wyrfel committed Sep 16, 2018
1 parent 015bb01 commit a1d94da
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions src/Mapper/LastnameMapper.php
Expand Up @@ -34,11 +34,7 @@ public function map(array $parts): array
return $parts;
}

$parts = array_reverse($parts);

$parts = $this->mapReversedParts($parts);

return array_reverse($parts);
return $this->mapParts($parts);
}

/**
Expand All @@ -48,12 +44,14 @@ public function map(array $parts): array
* @param array $parts
* @return array
*/
protected function mapReversedParts(array $parts): array
protected function mapParts(array $parts): array
{
$length = count($parts);
$k = count($parts);
$remapIgnored = true;

foreach ($parts as $k => $part) {
while (--$k >= 0) {
$part = $parts[$k];

if ($this->isIgnoredPart($part)) {
continue;
}
Expand All @@ -62,11 +60,8 @@ protected function mapReversedParts(array $parts): array
break;
}

$originalIndex = $length - $k - 1;
$originalParts = array_reverse($parts);

if ($this->isFollowedByLastnamePart($originalParts, $originalIndex)) {
if ($this->isApplicablePrefix($originalParts, $originalIndex)) {
if ($this->isFollowedByLastnamePart($parts, $k)) {
if ($this->isApplicablePrefix($parts, $k)) {
$parts[$k] = new LastnamePrefix($part, $this->prefixes[$this->getKey($part)]);
continue;
}
Expand Down Expand Up @@ -99,11 +94,15 @@ protected function mapReversedParts(array $parts): array
*/
protected function shouldStopMapping(array $parts, int $k): bool
{
if ($k + 2 > count($parts)) {
if ($k < 1) {
return true;
}

return strlen($parts[$k - 1]->getValue()) >= 3;
if ($parts[$k + 1] instanceof LastnamePrefix) {
return true;
}

return strlen($parts[$k + 1]->getValue()) >= 3;
}

/**
Expand All @@ -128,7 +127,11 @@ protected function isIgnoredPart($part) {
*/
protected function remapIgnored(array $parts): array
{
foreach ($parts as $k => $part) {
$k = count($parts);

while (--$k >= 0) {
$part = $parts[$k];

if (!$this->isIgnoredPart($part)) {
break;
}
Expand Down

0 comments on commit a1d94da

Please sign in to comment.