Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
RegExpConstrainedText
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 2
90
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
42
 escape
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2declare( strict_types = 1 );
3
4namespace 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 */
14abstract class RegExpConstrainedText extends ConstrainedText {
15    /** @var \Closure(string):bool */
16    public $prefixMatcher;
17    /** @var \Closure(string):bool */
18    public $suffixMatcher;
19
20    /**
21     * @param array $args
22     */
23    protected function __construct( array $args ) {
24        parent::__construct( $args );
25        $this->prefix ??= '<nowiki/>';
26        $this->suffix ??= '<nowiki/>';
27        // functions which return true if escape prefix/suffix need to be added
28        $matcher = static function ( string $re, bool $invert ): callable {
29            return ( static function ( string $context ) use ( $re, $invert ): bool {
30                return ( preg_match( $re, $context ) ) ? !$invert : $invert;
31            } );
32        };
33        $false = static function ( string $context ): bool {
34            return false;
35        };
36        $this->prefixMatcher =
37            ( $args['goodPrefix'] ?? false ) ?
38                $matcher( $args['goodPrefix'], true ) :
39            ( ( $args['badPrefix'] ?? false ) ?
40                $matcher( $args['badPrefix'], false ) : $false );
41        $this->suffixMatcher =
42            ( $args['goodSuffix'] ?? false ) ?
43                $matcher( $args['goodSuffix'], true ) :
44            ( ( $args['badSuffix'] ?? false ) ?
45                $matcher( $args['badSuffix'], false ) : $false );
46    }
47
48    /** @inheritDoc */
49    public function escape( State $state ): Result {
50        $result = new Result( $this->text );
51        if ( call_user_func( $this->prefixMatcher, $state->leftContext ) ) {
52            $result->prefix = $this->prefix;
53        }
54        if ( call_user_func( $this->suffixMatcher, $state->rightContext ) ) {
55            $result->suffix = $this->suffix;
56        }
57        return $result;
58    }
59}