Translate extension for MediaWiki
 
Loading...
Searching...
No Matches
RegexInsertablesSuggester.php
1<?php
2declare( strict_types = 1 );
3
4namespace MediaWiki\Extension\Translate\TranslatorInterface\Insertable;
5
6use InvalidArgumentException;
7
20 protected $regex = null;
26 protected $display = null;
31 protected $pre = null;
36 protected $post = null;
37
70 public function __construct( $params ) {
71 if ( is_string( $params ) ) {
72 $this->regex = $params;
73 } elseif ( is_array( $params ) ) {
74 // Validate if the array is in a proper format.
75 $this->regex = $params['regex'] ?? null;
76 $this->display = $params['display'] ?? null;
77 $this->pre = $params['pre'] ?? null;
78 $this->post = $params['post'] ?? null;
79 }
80
81 if ( $this->regex === null ) {
82 throw new InvalidArgumentException(
83 'Invalid configuration for the RegexInsertablesSuggester. Did not find a regex specified'
84 );
85 }
86
87 if ( $this->display !== null && $this->pre === null ) {
88 // if display value is set, and pre value is not set, set the display to pre.
89 // makes the configuration easier.
90 $this->pre = $this->display;
91 }
92 }
93
94 public function getInsertables( string $text ): array {
95 $matches = [];
96 preg_match_all( $this->regex, $text, $matches, PREG_SET_ORDER );
97
98 return array_map( [ $this, 'mapInsertables' ], $matches );
99 }
100
101 protected function mapInsertables( array $match ) {
102 if ( $this->display === null ) {
103 return new Insertable( $match[0], $match[0] );
104 }
105
106 $replacements = [];
107 // add '$' to the other keys for replacement.
108 foreach ( $match as $key => $value ) {
109 if ( !is_int( $key ) ) {
110 $tmpKey = '$' . $key;
111 $replacements[ $tmpKey ] = $value;
112 }
113 }
114
115 $displayVal = strtr( $this->display, $replacements );
116 $preVal = strtr( $this->pre, $replacements );
117 $postVal = '';
118 if ( $this->post !== null ) {
119 $postVal = strtr( $this->post, $replacements );
120 }
121
122 return new Insertable( $displayVal, $preVal, $postVal );
123 }
124}
Insertable is a string that usually does not need translation and is difficult to type manually.
Regex InsertablesSuggester implementation that can be extended or used for insertables in message gro...