From 74adde2255b3814ff1fc0a48ad7eab589c346abb Mon Sep 17 00:00:00 2001 From: Leo Germani Date: Thu, 19 Jul 2018 15:16:02 -0300 Subject: [PATCH] new template tag to get initials from name --- src/theme-helper/template-tags.php | 36 +++++++++++++++++++++ tests/test-utilities.php | 50 ++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 tests/test-utilities.php diff --git a/src/theme-helper/template-tags.php b/src/theme-helper/template-tags.php index 9b2827a3c..8584a91ab 100644 --- a/src/theme-helper/template-tags.php +++ b/src/theme-helper/template-tags.php @@ -247,4 +247,40 @@ function tainacan_current_view_displays($property) { return in_array($property, $view_mode_displayed_metadata['meta']); } return false; +} + +/** + * Gets the initials from a name. + * + * By default, returns 2 uppercase letters representing the name. The first letter from the first name and the first letter from the last. + * + * @param string $string The name to extract the initials from + * @param bool $one whether to return only the first letter, instead of two + * + * @return string + */ +function tainacan_get_initials(string $string, $one = false) { + + if (empty($string)) { + return ''; + } + if (strlen($string) == 1) { + return strtoupper($string); + } + + $first = strtoupper(substr($string,0,1)); + + if ($one) { + return $first; + } + + $words=explode(" ",$string); + + if (sizeof($words) < 2) { + $second = $string[1]; + } else { + $second = $words[ sizeof($words) - 1 ][0]; + } + + return strtoupper($first . $second); } \ No newline at end of file diff --git a/tests/test-utilities.php b/tests/test-utilities.php new file mode 100644 index 000000000..153f8166c --- /dev/null +++ b/tests/test-utilities.php @@ -0,0 +1,50 @@ +assertEquals('RC', tainacan_get_initials($string)); + + $string = 'Ronaldo'; + + $this->assertEquals('RO', tainacan_get_initials($string)); + $this->assertEquals('R', tainacan_get_initials($string, true)); + + $string = 'Marilia Mendonça das Neves Costa Silva Fonseca'; + + $this->assertEquals('MF', tainacan_get_initials($string)); + $this->assertEquals('M', tainacan_get_initials($string, true)); + + $string = 'Machado de Assis'; + + $this->assertEquals('MA', tainacan_get_initials($string)); + + $string = 'b'; + + $this->assertEquals('B', tainacan_get_initials($string)); + + $string = ''; + + $this->assertEquals('', tainacan_get_initials($string)); + + + + + } +} \ No newline at end of file