<?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\Resolver\SparqlResolver\Sparql;

class Uplet
{
    private $_uplet;

    public function __construct($uplet)
    {
        if ($uplet instanceof Expression) {
            $this->_uplet = new Expression($uplet);
        } elseif (is_string($uplet)) {
            $this->_uplet = new Literal($uplet);
        } else {
            $this->_uplet = new Expression($uplet);
        }
    }

    public function __toString()
    {
        return (string) $this->_uplet;
    }

    private function validate()
    {
        $strUplet = (string) $this->_uplet;
        $strUplet = trim($strUplet);
        $firstChar = substr($strUplet, 0, 1);
        $match = [];
        switch ($firstChar) {
            case '<':
                preg_match("/^<([^A-Za-z0-9:\/\.#]*)>$/", $strUplet, $match);
                if (count($match)) {
                    throw new \UnexpectedValueException($strUplet.' Uri contain bad symbols', 1);
                }
                break;
            case '?':
                preg_match('([^A-Za-z0-9_?])', $strUplet, $match);
                if (count($match)) {
                    throw new \UnexpectedValueException($strUplet.' Variable contain bad symbols', 2);
                }
                break;
            case '"':
                $strUplet = substr($strUplet, 1, -1);
                $strUplet = str_replace('\\"', '"', $strUplet);
                $strUplet = addslashes($strUplet);
                $strUplet = '"'.$strUplet.'"';
                if ($strUplet !== (string) $this->_uplet) {
                    throw new \UnexpectedValueException($strUplet.' literal contain bad symbols', 4);
                }
                break;
            default:
                if ('a' != $strUplet && 'as' != $strUplet) {
                    throw new \UnexpectedValueException($strUplet.' character contain bad symbols', 4);
                }
                break;
        }
    }
}
