<?php

/**
 * I18n class
 * Handle internationalization
 * @author Jérôme Brilland
 * @version 1.3
 * @copyright (c) 2009-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class I18n {

    /**
     * @var array Localized strings
     * @access private
     */
    private $messages = array();

    /**
     * @var string Locale
     * @access public
     */
    public $locale;

    /**
     * Class constructor
     * @param string locale Locale
     * @access public
     */
    public function __construct( $locale ) {
        $this->messages = array();
        $this->locale = $locale;
        setLocale( LC_ALL, $locale . '.UTF-8' );
    }

    /**
     * Load a translation file
     * @param string filename File name
     * @access public
     */
    public function load( $filename ) {
        if ( !is_readable( $filename ) ) {
            trigger_error( 'File ' . $filename . ' does not exist or is not readable.', E_USER_ERROR );
        }
        $this->messages = array_merge( $this->messages, parse_ini_file( $filename ) );
    }

    /**
     * Get a localized string
     * @param string key Key
     * @return string The localized string
     * @access public
     */
    public function __( string $key, ...$options ) {
        if ( array_key_exists( $key, $this->messages ) ) {
            return vsprintf( $this->messages[$key], $options );
        } else {
            return $key;
        }
    }
}

?>
