| 1 |
<?php |
| 2 |
declare( strict_types = 1 ); |
| 3 |
|
| 4 |
namespace Wikimedia\Parsoid\Wt2Html\DOM\Processors; |
| 5 |
|
| 6 |
use Wikimedia\Parsoid\DOM\Element; |
| 7 |
use Wikimedia\Parsoid\DOM\Node; |
| 8 |
use Wikimedia\Parsoid\Utils\DOMCompat; |
| 9 |
use Wikimedia\Parsoid\Utils\DOMUtils; |
| 10 |
|
| 11 |
class PWrapState { |
| 12 |
|
| 13 |
private const RANGE_TYPE_RE = '!^mw:(Transclusion(/|$)|Param(/|$)|Annotation/)!'; |
| 14 |
|
| 15 |
/** @var ?Element */ |
| 16 |
public $p = null; |
| 17 |
|
| 18 |
/** @var bool */ |
| 19 |
private $hasOptionalNode = false; |
| 20 |
|
| 21 |
/** |
| 22 |
* About ids of starts we've seen in this paragraph |
| 23 |
* |
| 24 |
* @var array |
| 25 |
*/ |
| 26 |
private $seenStarts = []; |
| 27 |
|
| 28 |
/** |
| 29 |
* Unwrap + reset |
| 30 |
*/ |
| 31 |
public function reset() { |
| 32 |
$this->unwrapTrailingPWrapOptionalNodes(); |
| 33 |
|
| 34 |
$this->p = null; |
| 35 |
$this->hasOptionalNode = false; |
| 36 |
$this->seenStarts = []; |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Record that we've encountered an optional node to potentially unwrap |
| 41 |
* |
| 42 |
* @param Node $n |
| 43 |
*/ |
| 44 |
public function processOptionalNode( Node $n ) { |
| 45 |
$t = DOMUtils::matchNameAndTypeOf( $n, 'meta', self::RANGE_TYPE_RE ); |
| 46 |
$this->hasOptionalNode = (bool)$t || $this->hasOptionalNode; |
| 47 |
if ( $t && !str_ends_with( $t, '/End' ) ) { |
| 48 |
'@phan-var Element $n'; // @var Element $n |
| 49 |
$about = DOMCompat::getAttribute( $n, 'about' ); |
| 50 |
if ( $about !== null ) { |
| 51 |
$this->seenStarts[$about] = true; |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Unwrap a run of trailing nodes that don't need p-wrapping. |
| 58 |
* This only matters for meta tags representing transclusions |
| 59 |
* and annotations. Unwrapping can prevent unnecessary expansion |
| 60 |
* of template/annotation ranges. |
| 61 |
*/ |
| 62 |
private function unwrapTrailingPWrapOptionalNodes() { |
| 63 |
if ( $this->hasOptionalNode ) { |
| 64 |
$lastChild = $this->p->lastChild; |
| 65 |
while ( PWrap::pWrapOptional( $lastChild ) ) { |
| 66 |
$t = DOMUtils::matchNameAndTypeOf( $lastChild, 'meta', self::RANGE_TYPE_RE ); |
| 67 |
if ( $t && str_ends_with( $t, '/End' ) ) { |
| 68 |
'@phan-var Element $lastChild'; // @var Element $lastChild |
| 69 |
// Check if one of its prior siblings has a matching opening tag. |
| 70 |
// If so, we are done with unwrapping here since we don't want to |
| 71 |
// hoist this closing tag by itself. |
| 72 |
$aboutId = DOMCompat::getAttribute( $lastChild, 'about' ); |
| 73 |
if ( $this->seenStarts[$aboutId] ?? null ) { |
| 74 |
break; |
| 75 |
} |
| 76 |
} |
| 77 |
$this->p->parentNode->insertBefore( $lastChild, $this->p->nextSibling ); |
| 78 |
$lastChild = $this->p->lastChild; |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
} |