Debian Codegraph @

vendor/wikimedia/parsoid/src/Html2Wt/ConstrainedText/RegExpConstrainedText.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Html2Wt\ConstrainedText;
5
6 /**
7 * This subclass allows specification of a regular expression for
8 * acceptable (or prohibited) leading (and/or trailing) contexts.
9 *
10 * This is an abstract class; it's intended to be subclassed, not
11 * used directly, and so it not included in the lists of types
12 * tried by `fromSelSer`.
13 */
14 abstract class RegExpConstrainedText extends ConstrainedText {
15 /** @var \Closure(string):bool */
16 public $prefixMatcher;
17 /** @var \Closure(string):bool */
18 public $suffixMatcher;
19
20 protected function __construct( array $args ) {
21 parent::__construct( $args );
22 $this->prefix ??= '<nowiki/>';
23 $this->suffix ??= '<nowiki/>';
24 // functions which return true if escape prefix/suffix need to be added
25 $matcher = static function ( string $re, bool $invert ): callable {
26 return ( static function ( string $context ) use ( $re, $invert ): bool {
27 return ( preg_match( $re, $context ) ) ? !$invert : $invert;
28 } );
29 };
30 $false = static function ( string $context ): bool {
31 return false;
32 };
33 $this->prefixMatcher =
34 ( $args['goodPrefix'] ?? false ) ?
35 $matcher( $args['goodPrefix'], true ) :
36 ( ( $args['badPrefix'] ?? false ) ?
37 $matcher( $args['badPrefix'], false ) : $false );
38 $this->suffixMatcher =
39 ( $args['goodSuffix'] ?? false ) ?
40 $matcher( $args['goodSuffix'], true ) :
41 ( ( $args['badSuffix'] ?? false ) ?
42 $matcher( $args['badSuffix'], false ) : $false );
43 }
44
45 /** @inheritDoc */
46 public function escape( State $state ): Result {
47 $result = new Result( $this->text );
48 if ( call_user_func( $this->prefixMatcher, $state->leftContext ) ) {
49 $result->prefix = $this->prefix;
50 }
51 if ( call_user_func( $this->suffixMatcher, $state->rightContext ) ) {
52 $result->suffix = $this->suffix;
53 }
54 return $result;
55 }
56 }