Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 10 |
|
0.00% |
0 / 2 |
CRAP | |
0.00% |
0 / 1 |
| TokenGenerator | |
0.00% |
0 / 10 |
|
0.00% |
0 / 2 |
30 | |
0.00% |
0 / 1 |
| __construct | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| generate | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
20 | |||
| 1 | <?php |
| 2 | declare( strict_types = 1 ); |
| 3 | |
| 4 | namespace Wikimedia\RemexHtml\Tokenizer; |
| 5 | |
| 6 | /** |
| 7 | * This class provides a convenient iterative view of the token stream, |
| 8 | * implemented as a Generator. It is intended to be used as follows: |
| 9 | * |
| 10 | * foreach ( TokenGenerator::generate( $html, [] ) as $token ) { |
| 11 | * ... |
| 12 | * } |
| 13 | * |
| 14 | * Performance is slightly slower than a plain TokenHandler, probably due to |
| 15 | * the need to convert event parameters to associative arrays. |
| 16 | */ |
| 17 | class TokenGenerator { |
| 18 | /** @var TokenGeneratorHandler */ |
| 19 | protected $handler; |
| 20 | |
| 21 | /** @var Tokenizer */ |
| 22 | protected $tokenizer; |
| 23 | |
| 24 | /** |
| 25 | * @param string $text |
| 26 | * @param array $options Options passed through to Tokenizer |
| 27 | */ |
| 28 | protected function __construct( $text, $options ) { |
| 29 | $this->handler = new TokenGeneratorHandler; |
| 30 | $this->tokenizer = new Tokenizer( $this->handler, $text, $options ); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Get a Generator which iterates over all tokens in the supplied HTML |
| 35 | * |
| 36 | * @param string $text The HTML |
| 37 | * @param array $options The Tokenizer options, see Tokenizer::__construct() |
| 38 | * @return \Generator |
| 39 | */ |
| 40 | public static function generate( $text, $options ) { |
| 41 | $tg = new self( $text, $options ); |
| 42 | $tg->tokenizer->beginStepping(); |
| 43 | while ( $tg->tokenizer->step() ) { |
| 44 | foreach ( $tg->handler->tokens as $token ) { |
| 45 | yield $token; |
| 46 | } |
| 47 | $tg->handler->tokens = []; |
| 48 | } |
| 49 | foreach ( $tg->handler->tokens as $token ) { |
| 50 | yield $token; |
| 51 | } |
| 52 | } |
| 53 | } |