<?php
namespace Adianti\Util;

/**
 * String manipulation
 *
 * @version    8.4
 * @package    util
 * @author     Pablo Dall'Oglio
 * @copyright  Copyright (c) 2006 Adianti Solutions Ltd. (http://www.adianti.com.br)
 * @license    https://adiantiframework.com.br/license
 */
class AdiantiStringConversion
{
    /**
     * Polyfill for utf8_encode()
     */
    public static function utf8Encode($string)
    {
        if (version_compare(PHP_VERSION, '8.1.999', 'le'))
        {
            return utf8_encode((string) $string);
        }
        
        if (function_exists('mb_convert_encoding'))
        {
            return mb_convert_encoding((string) $string, 'UTF-8', 'ISO-8859-1');
        }
        
        if (class_exists('UConverter'))
        {
            return UConverter::transcode((string) $string, 'UTF8', 'ISO-8859-1');
        }
        
        if (function_exists('iconv'))
        {
            return iconv('ISO-8859-1', 'UTF-8', (string) $string);
        }
    }
    
    /**
     * Polyfill for utf8_decode()
     */
    public static function utf8Decode($string)
    {
        if (version_compare(PHP_VERSION, '8.1.999', 'le'))
        {
            return utf8_decode((string) $string);
        }
        
        if (function_exists('mb_convert_encoding'))
        {
            return mb_convert_encoding((string) $string, 'ISO-8859-1', 'UTF-8');
        }
        
        if (class_exists('UConverter'))
        {
            return UConverter::transcode((string) $string, 'ISO-8859-1', 'UTF8');
        }
        
        if (function_exists('iconv'))
        {
            return iconv('UTF-8', 'ISO-8859-1', (string) $string);
        }
    }
    
    /**
     * Returns camel case string from underscore string
     */
    public static function camelCaseFromUnderscore($string, $spaces = FALSE)
    {
        $words = explode('_', mb_strtolower($string));

        $return = '';
        foreach ($words as $word)
        {
            $return .= ucfirst(trim($word));
            if ($spaces)
            {
                $return .= ' ';
            }
        }

        return trim($return);
    }

    /**
     * Returns underscore string from camel case string
     */
    public static function underscoreFromCamelCase($string, $spaces = FALSE)
    {
        $output = mb_strtolower(preg_replace('/([a-z])([A-Z])/', '$'.'1_$'.'2', $string));
        if ($spaces)
        {
            $output = str_replace(' ', '_', trim($output));
        }
        
        return $output;
    }
    
    /**
     * Remove accents from string
     */
    public static function removeAccent($str)
    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'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
      $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
      return str_replace($a, $b, $str);
    }
    
    /**
     * Returns the string as Unicode when needed
     */
    public static function assureUnicode($content)
    {
        if (is_scalar($content))
        {
            if (extension_loaded('mbstring') && extension_loaded('iconv'))
            {
                $enc_in = mb_detect_encoding( (string) $content, ['UTF-8', 'ISO-8859-1', 'ASCII'], true);
                if ($enc_in !== 'UTF-8')
                {
                    $converted = iconv($enc_in, "UTF-8", $content);
                    if ($converted === false)
                    {
                        return $content;
                    }
                
                    return $converted;
                }
            }
            else
            {
                if (self::utf8Encode(self::utf8Decode($content)) !== $content ) // NOT UTF
                {
                    return self::utf8Encode($content);
                }
            }
        }
        
        return $content;
    }
    
    
    /**
     * Assure ISO8859-1
     */
    public static function assureISO($content)
    {
        if (self::utf8Encode(self::utf8Decode($content)) == $content ) // UTF
        {
            return self::utf8Decode($content);
        }
        
        return $content;
    }
    
    
    /**
     * Returns the slug from string
     */
    public static function slug($content, $separator = '-', $tolower = true)
    {
        $content = self::assureUnicode($content);
        
        $table = array(
            'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
            'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
            'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
            'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
            'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
            'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
            'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
            'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
        );

        $content = strtr($content, $table);
        
        if ($tolower)
        {
            $content = mb_strtolower($content);
            //Strip any unwanted characters
            $content = preg_replace("/[^a-z0-9_\s-]/", "", $content);
        }
        else
        {
            $content = preg_replace("/[^a-zA-Z0-9_\s-]/", "", $content);
        }
        
        //Clean multiple dashes or whitespaces
        $content = preg_replace("/[\s-]+/", " ", $content);
        //Convert whitespaces and underscore to dash
        $content = preg_replace("/[\s_]/", $separator, trim($content));
        //Remove non visible chars
        $content = preg_replace('/[[:^print:]]/', "", $content);
        
        return $content;
    }
    
    /**
     * Replace text between
     * @param $str Text to be replaced
     * @param $needle_start Start mark
     * @param $needle_end End mark
     * @param $replacement Text to be inserted
     * @param $include_limits if the mark limits will be replaced
     */
    public static function replaceBetween($str, $needle_start, $needle_end, $replacement, $include_limits = true)
    {
        $pos = strpos($str, $needle_start);
        if ($pos === false)
        {
            return $str;
        }
        $start = $pos + ($include_limits ? strlen($needle_start) : 0);

        $pos = strpos($str, $needle_end, $start);
        if ($pos === false)
        {
            return $str;
        }
        $end = ($include_limits ? $pos : $pos + strlen($needle_end));

        return substr_replace($str, $replacement, $start, $end - $start);
    }
    
    /**
     * Replace text between
     * @param $str Text to be replaced
     * @param $needle_start Start mark
     * @param $needle_end End mark
     * @param $replacement Text to be inserted
     * @param $include_limits if the mark limits will be replaced
     */
    public static function getBetween($str, $needle_start, $needle_end, $include_limits = true)
    {
        $pos = strpos($str, $needle_start);
        if ($pos === false)
        {
            return '';
        }
        
        $start = $pos + ($include_limits ? strlen($needle_start) : 0);

        $pos = strpos($str, $needle_end, $start);
        if ($pos === false)
        {
            return '';
        }
        
        $end = ($include_limits ? $pos : $pos + strlen($needle_end));

        return substr($str, $start, $end - $start);
    }
}
