44
55namespace Cucumber \Gherkin ;
66
7+ use RuntimeException ;
8+
79/**
810 * Keeps common string operations in one place using correct unicode functions
911 * (and normalises naming with other implementations)
@@ -33,22 +35,46 @@ public static function substring(string $string, int $start, int $length = null)
3335
3436 public static function rtrim (string $ string ): string
3537 {
36- return preg_replace ('/ ' . self ::WHITESPACE_PATTERN . '$/u ' , '' , $ string );
38+ $ trimmed = preg_replace ('/ ' . self ::WHITESPACE_PATTERN . '$/u ' , '' , $ string );
39+
40+ if ($ trimmed === null ) {
41+ throw new RuntimeException ('Failed to trim the string: ' . preg_last_error_msg ());
42+ }
43+
44+ return $ trimmed ;
3745 }
3846
3947 public static function rtrimKeepNewLines (string $ string ): string
4048 {
41- return preg_replace ('/ ' . self ::WHITESPACE_PATTERN_NO_NEWLINE . '$/u ' , '' , $ string );
49+ $ trimmed = preg_replace ('/ ' . self ::WHITESPACE_PATTERN_NO_NEWLINE . '$/u ' , '' , $ string );
50+
51+ if ($ trimmed === null ) {
52+ throw new RuntimeException ('Failed to trim the string: ' . preg_last_error_msg ());
53+ }
54+
55+ return $ trimmed ;
4256 }
4357
4458 public static function ltrim (string $ string ): string
4559 {
46- return preg_replace ('/^ ' . self ::WHITESPACE_PATTERN . '/u ' , '' , $ string );
60+ $ trimmed = preg_replace ('/^ ' . self ::WHITESPACE_PATTERN . '/u ' , '' , $ string );
61+
62+ if ($ trimmed === null ) {
63+ throw new RuntimeException ('Failed to trim the string: ' . preg_last_error_msg ());
64+ }
65+
66+ return $ trimmed ;
4767 }
4868
4969 public static function ltrimKeepNewLines (string $ string ): string
5070 {
51- return preg_replace ('/^ ' . self ::WHITESPACE_PATTERN_NO_NEWLINE . '/u ' , '' , $ string );
71+ $ trimmed = preg_replace ('/^ ' . self ::WHITESPACE_PATTERN_NO_NEWLINE . '/u ' , '' , $ string );
72+
73+ if ($ trimmed === null ) {
74+ throw new RuntimeException ('Failed to trim the string: ' . preg_last_error_msg ());
75+ }
76+
77+ return $ trimmed ;
5278 }
5379
5480 public static function trim (string $ string ): string
@@ -61,7 +87,13 @@ public static function replace(string $string, array $replacements): string
6187 {
6288 $ patterns = array_map (fn ($ p ) => '/ ' . preg_quote ($ p ) . '/u ' , array_keys ($ replacements ));
6389
64- return preg_replace ($ patterns , array_values ($ replacements ), $ string );
90+ $ replaced = preg_replace ($ patterns , array_values ($ replacements ), $ string );
91+
92+ if ($ replaced === null ) {
93+ throw new RuntimeException ('Failed to replace patterns in string: ' . preg_last_error_msg ());
94+ }
95+
96+ return $ replaced ;
6597 }
6698
6799 /** @return array<non-empty-string> */
0 commit comments