| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Extension\DiscussionTools; |
| 4 |
|
| 5 |
use LogicException; |
| 6 |
use MediaWiki\Html\HtmlHelper; |
| 7 |
use Wikimedia\RemexHtml\Serializer\SerializerNode; |
| 8 |
|
| 9 |
class BatchModifyElements { |
| 10 |
|
| 11 |
private array $modifications = []; |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
public function add( callable $shouldModifyCallback, callable $modifyCallback ): void { |
| 20 |
$this->modifications[] = [ $shouldModifyCallback, $modifyCallback ]; |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
public function apply( string $htmlFragment, bool $html5format = true ): string { |
| 31 |
if ( !count( $this->modifications ) ) { |
| 32 |
return $htmlFragment; |
| 33 |
} |
| 34 |
|
| 35 |
return HtmlHelper::modifyElements( |
| 36 |
$htmlFragment, |
| 37 |
function ( SerializerNode $node ) { |
| 38 |
foreach ( $this->modifications as [ $shouldModify, $modify ] ) { |
| 39 |
if ( $shouldModify( $node ) ) { |
| 40 |
return true; |
| 41 |
} |
| 42 |
} |
| 43 |
return false; |
| 44 |
}, |
| 45 |
function ( SerializerNode $node ) { |
| 46 |
$modified = null; |
| 47 |
foreach ( $this->modifications as [ $shouldModify, $modify ] ) { |
| 48 |
if ( $shouldModify( $node ) ) { |
| 49 |
if ( !$modified ) { |
| 50 |
$modified = $modify( $node ); |
| 51 |
} else { |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
throw new LogicException( 'Node matches multiple modifiers.' ); |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
return $modified ?? $node; |
| 60 |
}, |
| 61 |
$html5format |
| 62 |
); |
| 63 |
} |
| 64 |
} |