MediaWiki master
TextDirection.php
Go to the documentation of this file.
1<?php
6
7namespace Wikimedia\Leximorph\Provider;
8
9use IntlChar;
10
21
29 private const array BIDI_CONTROL_CODES = [
30 // LEFT-TO-RIGHT EMBEDDING (LRE)
31 0x202A,
32 // RIGHT-TO-LEFT EMBEDDING (RLE)
33 0x202B,
34 // POP DIRECTIONAL FORMATTING (PDF)
35 0x202C,
36 // LEFT-TO-RIGHT OVERRIDE (LRO)
37 0x202D,
38 // RIGHT-TO-LEFT OVERRIDE (RLO)
39 0x202E,
40 // LEFT-TO-RIGHT ISOLATE (LRI)
41 0x2066,
42 // RIGHT-TO-LEFT ISOLATE (RLI)
43 0x2067,
44 // FIRST-STRONG ISOLATE (FSI)
45 0x2068,
46 // POP DIRECTIONAL ISOLATE (PDI)
47 0x2069,
48 ];
49
63 public function getDirection( string $text ): ?string {
64 $length = mb_strlen( $text, 'UTF-8' );
65 for ( $i = 0; $i < $length; $i++ ) {
66 $char = mb_substr( $text, $i, 1, 'UTF-8' );
67 $code = IntlChar::ord( $char );
68
69 // Skip BIDI control characters.
70 if ( in_array( $code, self::BIDI_CONTROL_CODES, true ) ) {
71 continue;
72 }
73
74 // Skip unallocated characters.
75 if ( !IntlChar::isdefined( $code ) ) {
76 continue;
77 }
78
79 $dir = IntlChar::charDirection( $code );
80 if ( $dir === IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT ) {
81 return 'ltr';
82 }
83 if (
84 $dir === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT ||
85 $dir === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC
86 ) {
87 return 'rtl';
88 }
89 }
90
91 return null;
92 }
93}
getDirection(string $text)
Determines the first strong directional Unicode codepoint.