index/src/XString.php

90 lines
2.6 KiB
PHP

<?php
// XString.php
// Created: 2022-02-03
// Updated: 2023-01-05
namespace Index;
use InvalidArgumentException;
/**
* Provides various helper methods for strings.
*/
final class XString {
/**
* Default character set for the random method.
*
* @var string
*/
public const RANDOM_CHARS = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789';
public static function toBool(string $value): bool {
return boolval($value);
}
public static function toInt(string $value, int $base = 10): int {
return $base === 10 ? (int)$value : intval($value, $base);
}
public static function toFloat(string $value): float {
return (float)$value;
}
public static function escape(
string $value,
int $flags = ENT_COMPAT | ENT_HTML5,
?string $encoding = null,
bool $doubleEncoding = true
): string {
return htmlspecialchars($value, $flags, $encoding, $doubleEncoding);
}
/**
* Check if a string is null or empty.
*
* @param IString|string|null $string String ot check for emptiness.
* @return bool true if the string is empty, false if not.
*/
public static function nullOrEmpty(IString|string|null $string): bool {
if($string === null)
return true;
if($string instanceof IString)
return $string->isEmpty();
return empty($string);
}
/**
* Check if a string is null or whitespace.
*
* @param IString|string|null $string String to check for whitespace.
* @return bool true if the string is whitespace, false if not.
*/
public static function nullOrWhitespace(IString|string|null $string): bool {
if($string === null)
return true;
return empty(trim((string)$string));
}
/**
* Generates a random string of user specified length.
*
* @param int $length Desired length of the string.
* @param string $chars Set of characters to pick from. Default set contains the alphabet in upper- and lowercase and numbers 0 thru 9.
* @return string The generated string.
*/
public static function random(int $length, string $chars = self::RANDOM_CHARS): string {
if($length < 1)
throw new InvalidArgumentException('$length must be at least 1.');
if($chars === '')
throw new InvalidArgumentException('$chars may not be empty.');
$string = '';
$count = strlen($chars) - 1;
while($length-- > 0)
$string .= $chars[random_int(0, $count)];
return $string;
}
}