<?php
namespace EasyChat\Library\Messenger\Marketplace;

 
final class MarketplaceText {
    public static function truncate($value, int $limit): string {
        $value = (string)$value;
        $limit = max(0, $limit);
        if ($limit === 0 || $value === '') {
            return '';
        }
        if (function_exists('mb_substr')) {
            return mb_substr($value, 0, $limit, 'UTF-8');
        }
        if (function_exists('iconv_substr')) {
            $result = iconv_substr($value, 0, $limit, 'UTF-8');
            if ($result !== false) {
                return $result;
            }
        }
        $matched = preg_match_all('/./us', $value, $characters);
        if ($matched !== false) {
            return implode('', array_slice($characters[0], 0, $limit));
        }
        return substr($value, 0, $limit);
    }

    public static function length($value): int {
        $value = (string)$value;
        if (function_exists('mb_strlen')) {
            return (int)mb_strlen($value, 'UTF-8');
        }
        if (function_exists('iconv_strlen')) {
            $length = iconv_strlen($value, 'UTF-8');
            if ($length !== false) {
                return (int)$length;
            }
        }
        $matched = preg_match_all('/./us', $value, $characters);
        return $matched !== false ? (int)$matched : strlen($value);
    }
}
