N°5172 - Add internal helpers to keep usage of null value in native PHP methods: strlen() => utils::StrLen()

This commit is contained in:
Molkobain
2022-05-16 16:15:11 +02:00
parent 98b24dff36
commit ff58fb8617
2 changed files with 39 additions and 0 deletions

View File

@@ -2819,6 +2819,23 @@ HTML;
return $aPrefs[$sShortcutId];
}
//----------------------------------------------
// PHP function helpers
//----------------------------------------------
/**
* Helper around the native strlen() PHP method to keep allowing usage of null value when computing the length of a string as null value is no longer allowed with PHP 8.1+
*
* @param string|null $sString
*
* @return int Length of $sString, 0 if null
* @since 3.0.2 N°5172
*/
public static function StrLen(?string $sString): int
{
return strlen($sString ?? '');
}
//----------------------------------------------
// Environment helpers
//----------------------------------------------

View File

@@ -605,4 +605,26 @@ class UtilsTest extends \Combodo\iTop\Test\UnitTest\ItopTestCase
'2G' => ['2G', 2 * 1024 * 1024 * 1024],
];
}
/**
* @param string|null $sString
* @param int $iExpected
*
* @dataProvider StrLenProvider
*/
public function testStrLen(?string $sString, int $iExpected)
{
$iComputed = utils::StrLen($sString);
self::assertEquals($iExpected, $iComputed, 'Length was not as expected');
}
public function StrLenProvider(): array
{
return [
'null value' => [null, 0],
'0 character' => ['', 0],
'1 character' => ['a', 1],
'5 characters' => ['abcde', 5],
];
}
}