| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Diff\TextDiffer; |
| 4 |
|
| 5 |
use MediaWiki\Language\Language; |
| 6 |
use Wikimedia\Diff\Diff; |
| 7 |
use Wikimedia\Diff\TableDiffFormatter; |
| 8 |
use Wikimedia\Diff\UnifiedDiffFormatter; |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
class PhpTextDiffer extends BaseTextDiffer { |
| 14 |
|
| 15 |
private $contentLanguage; |
| 16 |
|
| 17 |
public function __construct( ?Language $contentLanguage ) { |
| 18 |
$this->contentLanguage = $contentLanguage; |
| 19 |
} |
| 20 |
|
| 21 |
public function getName(): string { |
| 22 |
return 'php'; |
| 23 |
} |
| 24 |
|
| 25 |
public function getFormats(): array { |
| 26 |
return [ 'table', 'unified' ]; |
| 27 |
} |
| 28 |
|
| 29 |
public function getFormatContext( string $format ) { |
| 30 |
return $format === 'table' ? self::CONTEXT_ROW : self::CONTEXT_PRE; |
| 31 |
} |
| 32 |
|
| 33 |
protected function doRenderBatch( string $oldText, string $newText, array $formats ): array { |
| 34 |
$language = $this->contentLanguage; |
| 35 |
if ( $language ) { |
| 36 |
$oldText = $language->segmentForDiff( $oldText ); |
| 37 |
$newText = $language->segmentForDiff( $newText ); |
| 38 |
} |
| 39 |
$oldLines = explode( "\n", $oldText ); |
| 40 |
$newLines = explode( "\n", $newText ); |
| 41 |
$diff = new Diff( $oldLines, $newLines ); |
| 42 |
$result = []; |
| 43 |
foreach ( $formats as $format ) { |
| 44 |
switch ( $format ) { |
| 45 |
case 'unified': |
| 46 |
$formatter = new UnifiedDiffFormatter(); |
| 47 |
$diffText = $formatter->format( $diff ); |
| 48 |
break; |
| 49 |
|
| 50 |
default: |
| 51 |
$formatter = new TableDiffFormatter(); |
| 52 |
$diffText = $formatter->format( $diff ); |
| 53 |
break; |
| 54 |
} |
| 55 |
if ( $language ) { |
| 56 |
$diffText = $language->unsegmentForDiff( $diffText ); |
| 57 |
} |
| 58 |
$result[$format] = $diffText; |
| 59 |
} |
| 60 |
|
| 61 |
return $result; |
| 62 |
} |
| 63 |
|
| 64 |
public function localize( string $format, string $diff, array $options = [] ): string { |
| 65 |
return $this->localizeLineNumbers( $diff, $options['reducedLineNumbers'] ?? false ); |
| 66 |
} |
| 67 |
} |