1<?php
2/**
3 * The attribute parser parses a simple attribute selector.
4 *
5 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
6 * @copyright Copyright 2010-2014 PhpCss Team
7 */
8
9namespace PhpCss\Parser {
10
11  use PhpCss;
12  use PhpCss\Ast;
13  use PhpCss\Scanner;
14
15  /**
16   * The attribute parser parses a simple attribute selector.
17   *
18   * The attribute value can be an string if a string start is found it delegates to a string
19   * parser.
20   */
21  class Attribute extends PhpCss\Parser {
22
23    private $_operators = [
24      '^=' => Ast\Selector\Simple\Attribute::MATCH_PREFIX,
25      '$=' => Ast\Selector\Simple\Attribute::MATCH_SUFFIX,
26      '*=' => Ast\Selector\Simple\Attribute::MATCH_SUBSTRING,
27      '=' => Ast\Selector\Simple\Attribute::MATCH_EQUALS,
28      '~=' => Ast\Selector\Simple\Attribute::MATCH_INCLUDES,
29      '|=' => Ast\Selector\Simple\Attribute::MATCH_DASHMATCH,
30    ];
31
32    /**
33     * @return Ast\Node
34     * @throws PhpCss\Exception\ParserException
35     */
36    public function parse(): Ast\Node {
37      $token = $this->read(Scanner\Token::IDENTIFIER);
38      $attribute = new Ast\Selector\Simple\Attribute($token->content);
39      $token = $this->read(
40        [
41          Scanner\Token::ATTRIBUTE_OPERATOR,
42          Scanner\Token::ATTRIBUTE_SELECTOR_END,
43        ]
44      );
45      if ($token->type === Scanner\Token::ATTRIBUTE_OPERATOR) {
46        $attribute->match = $this->_operators[$token->content];
47        $token = $this->read(
48          [
49            Scanner\Token::NUMBER,
50            Scanner\Token::IDENTIFIER,
51            Scanner\Token::SINGLEQUOTE_STRING_START,
52            Scanner\Token::DOUBLEQUOTE_STRING_START,
53          ]
54        );
55        switch ($token->type) {
56        case Scanner\Token::NUMBER :
57        case Scanner\Token::IDENTIFIER :
58          $attribute->literal = new Ast\Value\Literal($token->content);
59          break;
60        case Scanner\Token::SINGLEQUOTE_STRING_START :
61        case Scanner\Token::DOUBLEQUOTE_STRING_START :
62          $attribute->literal = $this->delegate(Text::CLASS);
63          break;
64        }
65        $this->read(Scanner\Token::ATTRIBUTE_SELECTOR_END);
66      }
67      return $attribute;
68    }
69  }
70}
71