Skip to content

Instantly share code, notes, and snippets.

@Muqsit
Created January 16, 2018 15:59
Show Gist options
  • Save Muqsit/21fca3188d64cd8d88970537dde94da0 to your computer and use it in GitHub Desktop.
Save Muqsit/21fca3188d64cd8d88970537dde94da0 to your computer and use it in GitHub Desktop.
minet str center
<?php
/**
* Source from:
* https://github.com/NiclasOlofsson/MiNET/blob/master/src/MiNET/MiNET/Utils/TextUtils.cs
*/
namespace cosmiccore\miscs;
use pocketmine\utils\TextFormat as TF;
class StringUtils {
public const LineLength = 30;
public const CharWidth = 6;
public const SpaceChar = ' ';
public const CleanAllFormattingFilter = '(?:&|§)([0123456789abcdefklmnor])';
public const CleanColourFilter = '(?:&|§)([0123456789abcdef])';
public const BoldTextRegex = '(?:&|§)l(.+?)(?:[&|§]r|$)';
public const CharWidths = [
' ' => 4,
'!' => 2,
'"' => 5,
'\'' => 3,
'(' => 5,
')' => 5,
'*' => 5,
',' => 2,
'.' => 2,
':' => 2,
';' => 2,
'<' => 5,
'>' => 5,
'@' => 7,
'I' => 4,
'[' => 4,
']' => 4,
'f' => 5,
'i' => 2,
'k' => 5,
'l' => 3,
't' => 4,
'' => 5,
'|' => 2,
'' => 5,
'~' => 7,
'█' => 9,
'░' => 8,
'▒' => 9,
'▓' => 9,
'▌' => 5,
'─' => 9
//'-' => 9,
];
public static function centerLine(string $input) : string
{
return self::center($input, self::LineLength * self::CharWidth);
}
public static function center(string $input, int $maxLength = 0, bool $addRightPadding = false) : string
{
$lines = explode("\n", trim($input));
$sortedLines = $lines;
usort($sortedLines, function(string $a, string $b) {
return self::getPixelLength($b) <=> self::getPixelLength($a);
});
$longest = $sortedLines[0];
if ($maxLength === 0) {
$maxLength = self::getPixelLength($longest);
}
$result = "";
$spaceWidth = self::getCharWidth(self::SpaceChar);
foreach ($lines as $sortedLine) {
$len = max($maxLength - self::getPixelLength($sortedLine), 0);
$padding = (int) round($len / (2 * $spaceWidth));
$paddingRight = (int) floor($len / (2 * $spaceWidth));
$result .= str_pad(self::SpaceChar, $padding) . $sortedLine . TF::RESET . ($addRightPadding ? str_pad(self::SpaceChar, $paddingRight) : "") . "\n";
}
$result = rtrim($result, "\n");
return $result;
}
private static function getCharWidth(string $c) : int
{
return self::CharWidths[$c] ?? self::CharWidth;
}
public static function getPixelLength(string $line) : int
{
$length = 0;
foreach (str_split(TF::clean($line)) as $c) {
$length += self::getCharWidth($c);
}
// +1 for each bold character
$length += substr_count($line, TF::BOLD);
return $length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment