<?php
/**
 * This file is part of the DATAtourisme project.
 *
 *  @author Conjecto <contact@conjecto.com>
 *
 * For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Datatourisme\Api\Schema;

class PrefixMap
{
    /**
     * @var array
     */
    private $prefixes = [];

    /**
     * PrefixMap constructor.
     *
     * @param array $prefixes
     */
    public function __construct(array $prefixes)
    {
        $this->prefixes = $prefixes;
    }

    /**
     * @return array
     */
    public function getPrefixes()
    {
        return $this->prefixes;
    }

    /**
     * @param array $prefixes
     */
    public function setPrefixes($prefixes)
    {
        $this->prefixes = $prefixes;
    }

    /**
     * Expand an URI.
     *
     * @param $uri
     *
     * @return string
     */
    public function expandUri($uri)
    {
        if (substr_count($uri, '//')) {
            return $uri;
        }

        foreach ($this->prefixes as $prefix => $namespace) {
            if (0 === strpos($uri, $prefix.':')) {
                return $namespace.substr($uri, strlen($prefix) + 1);
            }
        }

        return $uri;
    }

    /**
     * Shorten an URI.
     *
     * @param $uri
     *
     * @return string
     */
    public function shortenUri($uri)
    {
        if (!substr_count($uri, '//')) {
            return $uri;
        }

        foreach ($this->prefixes as $prefix => $namespace) {
            if (0 === strpos($uri, $namespace)) {
                return $prefix.':'.substr($uri, strlen($namespace));
            }
        }

        return $uri;
    }

    /**
     * Return true if the given prefix exists.
     *
     * @param $uri
     *
     * @return string
     */
    public function hasPrefix($uri)
    {
        $prefix = explode(':', $uri)[0];

        return isset($this->getPrefixes()[$prefix]);
    }
}
