diff --git a/src/Name.php b/src/Name.php index 304a91f..0b50489 100644 --- a/src/Name.php +++ b/src/Name.php @@ -94,11 +94,22 @@ public function getFirstname(): string /** * get the last name * + * @param bool $pure * @return string */ - public function getLastname(): string + public function getLastname(bool $pure = false): string { - return $this->export('Lastname'); + return $this->export('Lastname', $pure); + } + + /** + * get the last name prefix + * + * @return string + */ + public function getLastnamePrefix(): string + { + return $this->export('LastnamePrefix'); } /** @@ -159,19 +170,48 @@ public function getMiddlename(): string /** * helper method used by getters to extract and format relevant name parts * - * @param string $type the part type to export - * @return string the exported parts + * @param string $type + * @param bool $pure + * @return string */ - protected function export($type): string + protected function export(string $type, bool $strict = false): string { $matched = []; foreach ($this->parts as $part) { - if ($part instanceof AbstractPart && is_a($part, 'TheIconic\\NameParser\\Part\\' . $type)) { + if (!($part instanceof AbstractPart)) { + continue; + } + + $method = ($strict) ? 'isStrictType' : 'isType'; + + if (call_user_func([$this, $method], $part, $type)) { $matched[] = $part->normalize(); } } return implode(' ', $matched); } + + /** + * helper method to check if a part is of the given type + * + * @param AbstractPart $part + * @param string $type + * @return bool + */ + protected function isType(AbstractPart $part, string $type) { + return is_a($part, 'TheIconic\\NameParser\\Part\\' . $type); + } + + /** + * helper method to check if a part is the exact given type (not considering superclasses) + * + * @param AbstractPart $part + * @param string $type + * @return bool + */ + protected function isStrictType(AbstractPart $part, string $type) { + return get_class($part) === 'TheIconic\\NameParser\\Part\\' . $type; + } } diff --git a/tests/NameTest.php b/tests/NameTest.php index 6830f57..b759093 100644 --- a/tests/NameTest.php +++ b/tests/NameTest.php @@ -6,6 +6,7 @@ use TheIconic\NameParser\Part\Firstname; use TheIconic\NameParser\Part\Initial; use TheIconic\NameParser\Part\Lastname; +use TheIconic\NameParser\Part\LastnamePrefix; use TheIconic\NameParser\Part\Middlename; use TheIconic\NameParser\Part\Nickname; use TheIconic\NameParser\Part\Salutation; @@ -40,4 +41,18 @@ public function testGetNickname() $this->assertSame('Jim', $name->getNickname()); $this->assertSame('(Jim)', $name->getNickname(true)); } + + public function testGettingLastnameAndLastnamePrefixSeparately() + { + $name = new Name([ + new Firstname('Frank'), + new LastnamePrefix('van'), + new Lastname('Delft'), + ]); + + $this->assertSame('Frank', $name->getFirstname()); + $this->assertSame('van', $name->getLastnamePrefix()); + $this->assertSame('Delft', $name->getLastname(true)); + $this->assertSame('van Delft', $name->getLastname()); + } }