1<?php
2
3namespace Sabberworm\CSS\Value;
4
5use Sabberworm\CSS\Parsing\ParserState;
6use Sabberworm\CSS\Parsing\SourceException;
7
8class CSSString extends PrimitiveValue {
9
10	private $sString;
11
12	public function __construct($sString, $iLineNo = 0) {
13		$this->sString = $sString;
14		parent::__construct($iLineNo);
15	}
16
17	public static function parse(ParserState $oParserState) {
18		$sBegin = $oParserState->peek();
19		$sQuote = null;
20		if ($sBegin === "'") {
21			$sQuote = "'";
22		} else if ($sBegin === '"') {
23			$sQuote = '"';
24		}
25		if ($sQuote !== null) {
26			$oParserState->consume($sQuote);
27		}
28		$sResult = "";
29		$sContent = null;
30		if ($sQuote === null) {
31			// Unquoted strings end in whitespace or with braces, brackets, parentheses
32			while (!preg_match('/[\\s{}()<>\\[\\]]/isu', $oParserState->peek())) {
33				$sResult .= $oParserState->parseCharacter(false);
34			}
35		} else {
36			while (!$oParserState->comes($sQuote)) {
37				$sContent = $oParserState->parseCharacter(false);
38				if ($sContent === null) {
39					throw new SourceException("Non-well-formed quoted string {$oParserState->peek(3)}", $oParserState->currentLine());
40				}
41				$sResult .= $sContent;
42			}
43			$oParserState->consume($sQuote);
44		}
45		return new CSSString($sResult, $oParserState->currentLine());
46	}
47
48	public function setString($sString) {
49		$this->sString = $sString;
50	}
51
52	public function getString() {
53		return $this->sString;
54	}
55
56	public function __toString() {
57		return $this->render(new \Sabberworm\CSS\OutputFormat());
58	}
59
60	public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) {
61		$sString = addslashes($this->sString);
62		$sString = str_replace("\n", '\A', $sString);
63		return $oOutputFormat->getStringQuotingType() . $sString . $oOutputFormat->getStringQuotingType();
64	}
65
66}