4 * @license https://opensource.org/licenses/Apache-2.0 Apache-2.0
7 namespace Wikimedia\CSS\Objects;
9 use Wikimedia\CSS\Util;
12 * Represent a CSS at-rule
14 class AtRule extends Rule implements DeclarationOrAtRule {
19 /** @var ComponentValueList */
22 /** @var SimpleBlock|null */
23 protected $block = null;
26 * @param Token $token An at-keyword token
28 public function __construct( Token $token ) {
29 if ( $token->type() !== Token::T_AT_KEYWORD ) {
30 throw new \InvalidArgumentException(
31 "At rule must begin with an at-keyword token, got {$token->type()}"
35 parent::__construct( $token );
36 $this->name = $token->value();
37 $this->prelude = new ComponentValueList();
40 public function __clone() {
41 $this->prelude = clone( $this->prelude );
43 $this->block = clone( $this->block );
48 * Create an at-rule by name
52 public static function newFromName( $name ) {
53 return new static( new Token( Token::T_AT_KEYWORD, $name ) );
57 * Return the at-rule's name, e.g. "media"
60 public function getName() {
65 * Return the at-rule's prelude
66 * @return ComponentValueList
68 public function getPrelude() {
69 return $this->prelude;
73 * Return the at-rule's block
74 * @return SimpleBlock|null
76 public function getBlock() {
82 * @param SimpleBlock|null $block
84 public function setBlock( SimpleBlock $block = null ) {
85 if ( $block->getStartTokenType() !== Token::T_LEFT_BRACE ) {
86 throw new \InvalidArgumentException( 'At-rule block must be delimited by {}' );
88 $this->block = $block;
92 * @param string $function Function to call, toTokenArray() or toComponentValueArray()
94 private function toTokenOrCVArray( $function ) {
98 Token::T_AT_KEYWORD, [ 'value' => $this->name, 'position' => [ $this->line, $this->pos ] ]
100 // Manually looping and appending turns out to be noticably faster than array_merge.
101 foreach ( $this->prelude->$function() as $v ) {
104 if ( $this->block ) {
105 foreach ( $this->block->$function() as $v ) {
109 $ret[] = new Token( Token::T_SEMICOLON );
115 public function toTokenArray() {
116 return $this->toTokenOrCVArray( __FUNCTION__ );
119 public function toComponentValueArray() {
120 return $this->toTokenOrCVArray( __FUNCTION__ );
123 public function __toString() {
124 return Util::stringify( $this );