new template tag to get initials from name

This commit is contained in:
Leo Germani 2018-07-19 15:16:02 -03:00
parent 4d09b824ca
commit 74adde2255
2 changed files with 86 additions and 0 deletions

View File

@ -248,3 +248,39 @@ function tainacan_current_view_displays($property) {
}
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);
}

50
tests/test-utilities.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace Tainacan\Tests;
/**
* Class TestUtilities
*
* @package Test_Tainacan
*/
/**
* Sample test case.
*/
class TestUtilities extends TAINACAN_UnitTestCase {
function test_initials() {
$string = 'Roberto Carlos';
$this->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));
}
}