Debian Codegraph @

vendor/wikimedia/css-sanitizer/src/Objects/CSSFunction.php

raw
1 <?php
2 /**
3 * @file
4 * @license https://opensource.org/licenses/Apache-2.0 Apache-2.0
5 */
6
7 namespace Wikimedia\CSS\Objects;
8
9 use InvalidArgumentException;
10 use Wikimedia\CSS\Util;
11
12 /**
13 * Represent a CSS function, eg. `rgb(255, 0, 0)`
14 */
15 class CSSFunction extends ComponentValue {
16
17 /** @var string */
18 protected $name;
19
20 /** @var ComponentValueList */
21 protected $value;
22
23 /**
24 * @param Token $token Function token starting the rule
25 */
26 public function __construct( Token $token ) {
27 if ( $token->type() !== Token::T_FUNCTION ) {
28 throw new InvalidArgumentException(
29 "CSS function must begin with a function token, got {$token->type()}"
30 );
31 }
32
33 [ $this->line, $this->pos ] = $token->getPosition();
34 $this->name = $token->value();
35 $this->value = new ComponentValueList();
36 }
37
38 public function __clone() {
39 $this->value = clone $this->value;
40 }
41
42 /**
43 * Create a function by name
44 * @param string $name
45 * @return CSSFunction
46 */
47 public static function newFromName( $name ) {
48 return new static( new Token( Token::T_FUNCTION, $name ) );
49 }
50
51 /**
52 * Return the function's name
53 * @return string
54 */
55 public function getName() {
56 return $this->name;
57 }
58
59 /**
60 * Return the function's value
61 * @return ComponentValueList
62 */
63 public function getValue() {
64 return $this->value;
65 }
66
67 /**
68 * Return an array of Tokens that correspond to this object.
69 * @return Token[]
70 */
71 public function toTokenArray() {
72 $ret = [];
73
74 $ret[] = new Token(
75 Token::T_FUNCTION,
76 [ 'value' => $this->name, 'position' => [ $this->line, $this->pos ] ]
77 );
78 // Manually looping and appending turns out to be noticeably faster than array_merge.
79 foreach ( $this->value->toTokenArray() as $v ) {
80 $ret[] = $v;
81 }
82 $ret[] = new Token( Token::T_RIGHT_PAREN );
83
84 return $ret;
85 }
86
87 public function __toString() {
88 return Util::stringify( $this );
89 }
90 }