index/src/XString.php

100 lines
3.2 KiB
PHP

<?php
// XString.php
// Created: 2022-02-03
// Updated: 2024-01-04
namespace Index;
use InvalidArgumentException;
use Stringable;
/**
* Provides various helper methods for strings.
*/
final class XString {
/**
* Default character set for the random method.
*
* @var string
*/
public const RANDOM_CHARS = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789';
/**
* 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;
}
/**
* Converts special characters to HTML entities.
*
* Uses htmlspecialchars with alternate defaults.
*
* @param Stringable|string $string The string being converted.
* @param int $flags A bitmask consisting of flags found in the documentation for htmlspecialchars.
* @param ?string $encoding Optional argument defining the encoding used when converting characters.
* @param bool $doubleEncoding Also reencode existing HTML entities.
* @return string The converted string.
*/
public static function escape(
Stringable|string $string,
int $flags = ENT_COMPAT | ENT_HTML5,
?string $encoding = null,
bool $doubleEncoding = true
): string {
return htmlspecialchars((string)$string, $flags, $encoding, $doubleEncoding);
}
/**
* Counts unique characters in a string.
*
* @param Stringable|string $string String to count unique characters of.
* @return int Unique character count.
*/
public static function countUnique(Stringable|string $string): int {
$string = str_split((string)$string);
$chars = [];
foreach($string as $char)
if(!in_array($char, $chars, true))
$chars[] = $char;
return count($chars);
}
/**
* Check if a string is null or empty.
*
* @param Stringable|string|null $string String ot check for emptiness.
* @return bool true if the string is empty, false if not.
*/
public static function nullOrEmpty(Stringable|string|null $string): bool {
return $string === null || (string)$string === '';
}
/**
* Check if a string is null or whitespace.
*
* @param Stringable|string|null $string String to check for whitespace.
* @return bool true if the string is whitespace, false if not.
*/
public static function nullOrWhitespace(Stringable|string|null $string): bool {
return $string === null || trim((string)$string) === '';
}
}