Created
April 22, 2014 11:24
-
-
Save Pezmc/11174922 to your computer and use it in GitHub Desktop.
PHP Username Generator Using the Template Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class UsernameGenerator { | |
private $user; | |
abstract function generateUsername(); | |
public function getUsername($user) { | |
$this->user = strtolower($user); | |
return $this->generateUsername(); | |
} | |
protected function getFirstName() { | |
$parts = (explode(' ', $this->user, 2)); | |
return $parts[0]; | |
} | |
protected function getLastName() { | |
$parts = (explode(' ', $this->user, 2)); | |
return $parts[1]; | |
} | |
protected function getFirstLetter($string) { | |
return substr($string, 0, 1); | |
} | |
protected function getFirstVowel($string) { | |
$position = strcspn(strtolower($string), "aeiou"); | |
if($position>0) return substr($string, $position, 1); | |
} | |
} | |
class UsernameGenerator1 extends UsernameGenerator { | |
public function generateUsername() { | |
$username = ""; | |
$username .= $this->getFirstLetter($this->getFirstName()); | |
$username .= $this->getFirstLetter($this->getLastName()); | |
$username .= $this->getFirstVowel($this->getLastName()); | |
return $username; | |
} | |
} | |
$tests = array("Pez Cuckow" => "pcu", "Oliver Brown" => "obo", "Alpha Alpha" => "aa"); | |
$generator = new UsernameGenerator1(); | |
foreach($tests as $input => $expectedOutput) { | |
$output = $generator->getUsername($input); | |
echo sprintf("%s: %s\t%s\n", $input, $output, | |
($output == $expectedOutput ? "PASS" : "FAIL\tExpected $expectedOutput")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment