ParagonIE\Halite\Util::safeStrlen PHP Method

safeStrlen() public static method

Safe string length
public static safeStrlen ( string $str ) : integer
$str string
return integer
    public static function safeStrlen(string $str) : int
    {
        static $exists = null;
        if ($exists === null) {
            $exists = \is_callable('\\mb_strlen');
        }
        if ($exists) {
            $length = \mb_strlen($str, '8bit');
            if ($length === false) {
                throw new CannotPerformOperation('mb_strlen() failed unexpectedly');
            }
        } else {
            // If we reached here, we can rely on strlen to count bytes:
            $length = \strlen($str);
            if ($length === false) {
                throw new CannotPerformOperation('strlen() failed unexpectedly');
            }
        }
        return $length;
    }

Usage Example

 /**
  * @param string $keyMaterial - The actual key data
  * @param bool $signing - Is this a signing key?
  */
 public function __construct(string $keyMaterial = '', ...$args)
 {
     if (CryptoUtil::safeStrlen($keyMaterial) !== \Sodium\CRYPTO_BOX_PUBLICKEYBYTES) {
         throw new InvalidKey('Encryption public key must be CRYPTO_BOX_PUBLICKEYBYTES bytes long');
     }
     parent::__construct($keyMaterial, false);
 }
All Usage Examples Of ParagonIE\Halite\Util::safeStrlen