<?php

class Slug
{
    public static function make(string $text, int $maxLength = 80): string
    {
        if (function_exists('transliterator_transliterate')) {
            $t = transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', $text);
            if ($t !== false) {
                $text = $t;
            }
        }
        $text = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text) ?: $text;
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9]+/', '-', $text);
        $text = trim($text, '-');
        if ($text === '') {
            $text = 'article-' . substr(bin2hex(random_bytes(3)), 0, 6);
        }
        if (strlen($text) > $maxLength) {
            $text = substr($text, 0, $maxLength);
            $text = rtrim($text, '-');
        }
        return $text;
    }
}
