index/src/XString.php

59 lines
1.6 KiB
PHP

<?php
// XString.php
// Created: 2022-02-03
// Updated: 2023-01-01
namespace Index;
/**
* Provides various helper methods for strings.
*/
final class XString {
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));
}
}