<?php
/**
 * Simple include path static wrapper
 *
 * @package home page
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */

/**
 * Class which wraps include path operation.
 *
 * It respects "/" as multipatform directory separator (see php documentation),
 * so it means that normalized windows path "C:/somewhere/somewhat" is same
 * as native windows path "C:\somewhere\somewhat".
 *
 * @package koubel homepage
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */
class IncludePath
{
    /**
     * Adds path to the include_path
     * If $path is currently in the include_path, make nothing.
     * @param string $path
     */
    public static function add($path)
    {
        if (empty($path)) return;

        $normPath = self::_normalizePath($path);
        if (in_array($normPath, self::getPathArray(true))) return;
        else set_include_path(get_include_path() . PATH_SEPARATOR . $path);
    }

    /**
     * Removes path from the include_path if a path is currently in the include path
     * @param string $path
     */
    public static function remove($path)
    {
        $normPath = self::_normalizePath($path);

        $pathArr = explode(PATH_SEPARATOR, get_include_path());

        foreach($pathArr as $key => $val) {
            if ($normPath == self::_normalizePath($val)) unset($pathArr[$key]);
        }
        set_include_path(implode(PATH_SEPARATOR, $pathArr));
    }

    /**
     * Gets include_path as an array path
     * @param bool $normalize normalize each path in the result array see {@link _normalizePath()}
     * @param array
     */
    public static function getPathArray($normalize = false)
    {
        $pathArr = explode(PATH_SEPARATOR, get_include_path());

        if (DIRECTORY_SEPARATOR != "/" && $normalize) {
            foreach($pathArr as $key => $val) {
                $pathArr[$key] = self::_normalizePath($val);
            }
        }
        return $pathArr;
    }

    /**
     * Returns path in the unix like format, "/" is a directory separator for every
     * platform.
     * @string $pathStr original path
     * @return string new norlamized path
     */
    private static function _normalizePath($pathStr)
    {
        if (DIRECTORY_SEPARATOR != "/") {
            return strtr($pathStr, DIRECTORY_SEPARATOR, "/");
        } else return $pathStr;
    }
}
