| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Extension\TextExtracts; |
| 4 |
|
| 5 |
use MediaWiki\MediaWikiServices; |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
class TextTruncator { |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
private $useTidy; |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
public function __construct( bool $useTidy ) { |
| 24 |
$this->useTidy = $useTidy; |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
public function getFirstSentences( $text, $requestedSentenceCount ) { |
| 35 |
if ( $requestedSentenceCount <= 0 ) { |
| 36 |
return ''; |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
$endchars = [ |
| 41 |
|
| 42 |
'\P{Lu}\.(?=[ \n]|$)', |
| 43 |
'[!?](?=[ \n]|$)', |
| 44 |
|
| 45 |
'。', |
| 46 |
|
| 47 |
'.', |
| 48 |
'!', |
| 49 |
'?', |
| 50 |
|
| 51 |
'。', |
| 52 |
]; |
| 53 |
|
| 54 |
$regexp = '/(?:' . implode( '|', $endchars ) . ')+/u'; |
| 55 |
$res = preg_match_all( $regexp, $text, $matches, PREG_OFFSET_CAPTURE ); |
| 56 |
|
| 57 |
if ( !$res ) { |
| 58 |
|
| 59 |
$lines = explode( "\n", $text, 2 ); |
| 60 |
return trim( $lines[0] ); |
| 61 |
} |
| 62 |
|
| 63 |
$index = min( $requestedSentenceCount, $res ) - 1; |
| 64 |
[ $tail, $length ] = $matches[0][$index]; |
| 65 |
|
| 66 |
$text = substr( $text, 0, $length ) . $tail; |
| 67 |
|
| 68 |
return $this->tidy( $text ); |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
public function getFirstChars( $text, $requestedLength ) { |
| 79 |
if ( $requestedLength <= 0 ) { |
| 80 |
return ''; |
| 81 |
} |
| 82 |
|
| 83 |
$length = mb_strlen( $text ); |
| 84 |
if ( $length <= $requestedLength ) { |
| 85 |
return $text; |
| 86 |
} |
| 87 |
|
| 88 |
|
| 89 |
$pattern = '/^[\w\/]*>?/su'; |
| 90 |
preg_match( $pattern, mb_substr( $text, $requestedLength ), $m ); |
| 91 |
$truncatedText = mb_substr( $text, 0, $requestedLength ) . $m[0]; |
| 92 |
if ( $truncatedText === $text ) { |
| 93 |
return $text; |
| 94 |
} |
| 95 |
|
| 96 |
return $this->tidy( $truncatedText ); |
| 97 |
} |
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
private function tidy( $text ) { |
| 104 |
if ( $this->useTidy ) { |
| 105 |
$text = MediaWikiServices::getInstance()->getTidy()->tidy( $text ); |
| 106 |
} |
| 107 |
|
| 108 |
return trim( $text ); |
| 109 |
} |
| 110 |
|
| 111 |
} |