| 1 |
<?php |
| 2 |
/** |
| 3 |
* @file |
| 4 |
* @license https://opensource.org/licenses/Apache-2.0 Apache-2.0 |
| 5 |
*/ |
| 6 |
|
| 7 |
namespace Wikimedia\CSS\Grammar; |
| 8 |
|
| 9 |
use Wikimedia\CSS\Objects\ComponentValueList; |
| 10 |
use Wikimedia\CSS\Objects\Token; |
| 11 |
|
| 12 |
/** |
| 13 |
* Matcher that matches runs of whitespace. |
| 14 |
*/ |
| 15 |
class WhitespaceMatcher extends Matcher { |
| 16 |
|
| 17 |
/** @var bool */ |
| 18 |
protected $significant; |
| 19 |
|
| 20 |
/** |
| 21 |
* @param array $options |
| 22 |
* - significant: (bool) Whether the whitespace being matched is significant. |
| 23 |
* This also controls whether it behaves as `<ws>*` (false) or `<ws>+` (true). |
| 24 |
*/ |
| 25 |
public function __construct( array $options = [] ) { |
| 26 |
$this->significant = !empty( $options['significant'] ); |
| 27 |
} |
| 28 |
|
| 29 |
/** @inheritDoc */ |
| 30 |
protected function generateMatches( ComponentValueList $values, $start, array $options ) { |
| 31 |
$end = $start; |
| 32 |
// @phan-suppress-next-line PhanRedundantConditionInLoop https://github.com/phan/phan/issues/5441 |
| 33 |
while ( isset( $values[$end] ) && |
| 34 |
// @phan-suppress-next-line PhanUndeclaredMethod False positive |
| 35 |
$values[$end] instanceof Token && $values[$end]->type() === Token::T_WHITESPACE |
| 36 |
) { |
| 37 |
$end++; |
| 38 |
} |
| 39 |
|
| 40 |
// If it's not significant, return whatever we found. |
| 41 |
if ( !$this->significant ) { |
| 42 |
yield $this->makeMatch( $values, $start, $end ); |
| 43 |
return; |
| 44 |
} |
| 45 |
|
| 46 |
// If we found zero whitespace, $options says we're skipping |
| 47 |
// whitespace, and whitespace was actually skipped, rewind one token. |
| 48 |
// Otherwise, return no match. |
| 49 |
if ( $end === $start ) { |
| 50 |
$start--; |
| 51 |
// @phan-suppress-next-line PhanRedundantCondition https://github.com/phan/phan/issues/5441 |
| 52 |
if ( !$options['skip-whitespace'] || !isset( $values[$start] ) || |
| 53 |
// @phan-suppress-next-line PhanUndeclaredMethod False positive |
| 54 |
!$values[$start] instanceof Token || $values[$start]->type() !== Token::T_WHITESPACE |
| 55 |
) { |
| 56 |
return; |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
// Return the match. Include a 'significantWhitespace' capture. |
| 61 |
yield $this->makeMatch( $values, $start, $end, |
| 62 |
new GrammarMatch( $values, $start, 1, 'significantWhitespace' ) |
| 63 |
); |
| 64 |
} |
| 65 |
} |