| 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 qualified rule, eg. `div { color: red }` |
| 14 |
*/ |
| 15 |
class QualifiedRule extends Rule { |
| 16 |
|
| 17 |
/** @var ComponentValueList */ |
| 18 |
protected $prelude; |
| 19 |
|
| 20 |
/** @var SimpleBlock */ |
| 21 |
protected $block; |
| 22 |
|
| 23 |
/** @inheritDoc */ |
| 24 |
public function __construct( ?Token $token = null ) { |
| 25 |
parent::__construct( $token ?: new Token( Token::T_EOF ) ); |
| 26 |
$this->prelude = new ComponentValueList(); |
| 27 |
$this->block = SimpleBlock::newFromDelimiter( Token::T_LEFT_BRACE ); |
| 28 |
} |
| 29 |
|
| 30 |
public function __clone() { |
| 31 |
$this->prelude = clone $this->prelude; |
| 32 |
$this->block = clone $this->block; |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Return the rule's prelude |
| 37 |
* @return ComponentValueList |
| 38 |
*/ |
| 39 |
public function getPrelude() { |
| 40 |
return $this->prelude; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Return the rule's block |
| 45 |
* @return SimpleBlock |
| 46 |
*/ |
| 47 |
public function getBlock() { |
| 48 |
return $this->block; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Set the block |
| 53 |
* @param SimpleBlock|null $block |
| 54 |
*/ |
| 55 |
public function setBlock( ?SimpleBlock $block = null ) { |
| 56 |
if ( $block->getStartTokenType() !== Token::T_LEFT_BRACE ) { |
| 57 |
throw new InvalidArgumentException( 'Qualified rule block must be delimited by {}' ); |
| 58 |
} |
| 59 |
$this->block = $block; |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
* @param string $function Function to call, toTokenArray() or toComponentValueArray() |
| 64 |
* @return Token[]|ComponentValue[] |
| 65 |
*/ |
| 66 |
private function toTokenOrCVArray( $function ) { |
| 67 |
$ret = []; |
| 68 |
|
| 69 |
// Manually looping and appending turns out to be noticeably faster than array_merge. |
| 70 |
foreach ( $this->prelude->$function() as $v ) { |
| 71 |
$ret[] = $v; |
| 72 |
} |
| 73 |
foreach ( $this->block->$function() as $v ) { |
| 74 |
$ret[] = $v; |
| 75 |
} |
| 76 |
return $ret; |
| 77 |
} |
| 78 |
|
| 79 |
/** @inheritDoc */ |
| 80 |
public function toTokenArray() { |
| 81 |
return $this->toTokenOrCVArray( __FUNCTION__ ); |
| 82 |
} |
| 83 |
|
| 84 |
/** @inheritDoc */ |
| 85 |
public function toComponentValueArray() { |
| 86 |
return $this->toTokenOrCVArray( __FUNCTION__ ); |
| 87 |
} |
| 88 |
|
| 89 |
public function __toString() { |
| 90 |
return Util::stringify( $this ); |
| 91 |
} |
| 92 |
} |