<?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 Literal
{
    private $_literal;

    public function __construct($literal)
    {
        $this->_literal = $literal;
        $this->validate();
    }

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

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