From 9207253a1e76d6c8441325d6895b57f244aa3580 Mon Sep 17 00:00:00 2001 From: Jan Date: Wed, 29 Sep 2021 10:57:57 +0200 Subject: [PATCH] extract generator methods (#130) Co-authored-by: Jan Teriete --- src/Generator/DefaultGenerator.php | 43 +++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/src/Generator/DefaultGenerator.php b/src/Generator/DefaultGenerator.php index ed5b9ad..aab52c4 100644 --- a/src/Generator/DefaultGenerator.php +++ b/src/Generator/DefaultGenerator.php @@ -17,19 +17,9 @@ public function make($name, $length = 2, $uppercase = false, $ascii = false, $rt // if name contains single word, use first N character if ($words->count() === 1) { - $initial = (string) $words->first(); - - if (strlen($this->name) >= $length) { - $initial = Str::substr($this->name, 0, $length); - } + $initial = $this->getInitialFromOneWord($words, $length); } else { - // otherwise, use initial char from each word - $initials = new Collection(); - $words->each(function ($word) use ($initials) { - $initials->push(Str::substr($word, 0, 1)); - }); - - $initial = $initials->slice(0, $length)->implode(''); + $initial = $this->getInitialFromMultipleWords($words, $length); } if ($uppercase) { @@ -43,7 +33,7 @@ public function make($name, $length = 2, $uppercase = false, $ascii = false, $rt return $initial; } - private function setName($name, $ascii) + protected function setName($name, $ascii) { if (is_array($name)) { throw new \InvalidArgumentException( @@ -66,4 +56,31 @@ private function setName($name, $ascii) $this->name = $name; } + + protected function getInitialFromOneWord($words, $length) + { + $initial = (string)$words->first(); + + if (strlen($this->name) >= $length) { + $initial = Str::substr($this->name, 0, $length); + } + + return $initial; + } + + protected function getInitialFromMultipleWords($words, $length) + { + // otherwise, use initial char from each word + $initials = new Collection(); + $words->each(function ($word) use ($initials) { + $initials->push(Str::substr($word, 0, 1)); + }); + + return $this->selectInitialFromMultipleInitials($initials, $length); + } + + protected function selectInitialFromMultipleInitials($initials, $length) + { + return $initials->slice(0, $length)->implode(''); + } }