Translate extension for MediaWiki
 
Loading...
Searching...
No Matches
PageTitleRenamer.php
1<?php
2declare( strict_types = 1 );
3
4namespace MediaWiki\Extension\Translate\PageTranslation;
5
6use MediaWiki\Title\Title;
7
17 public const NO_ERROR = 0;
18 public const UNKNOWN_PAGE = 1;
19 public const NS_TALK_UNSUPPORTED = 2;
20 public const RENAME_FAILED = 3;
21 public const INVALID_TITLE = 4;
22
23 private const IMPOSSIBLE = null;
25 private $map = [];
26
27 public function __construct( Title $source, Title $target ) {
28 $this->map[$source->getNamespace()] = [
29 $target->getNamespace(),
30 $source->getText(),
31 $target->getText(),
32 ];
33
34 $sourceTalkPage = $source->getTalkPageIfDefined();
35 $targetTalkPage = $target->getTalkPageIfDefined();
36 if ( $sourceTalkPage ) {
37 if ( !$targetTalkPage ) {
38 $this->map[$sourceTalkPage->getNamespace()] = [
39 self::IMPOSSIBLE,
40 null,
41 null,
42 ];
43 } else {
44 $this->map[$sourceTalkPage->getNamespace()] = [
45 $targetTalkPage->getNamespace(),
46 $source->getText(),
47 $target->getText(),
48 ];
49 }
50 }
51
52 $this->map[NS_TRANSLATIONS] = [
53 NS_TRANSLATIONS,
54 $source->getPrefixedText(),
55 $target->getPrefixedText(),
56 ];
57
58 $this->map[NS_TRANSLATIONS_TALK] = [
59 NS_TRANSLATIONS_TALK,
60 $source->getPrefixedText(),
61 $target->getPrefixedText(),
62 ];
63 }
64
65 public function getNewTitle( Title $title ): Title {
66 $instructions = $this->map[$title->getNamespace()] ?? null;
67 if ( $instructions === null ) {
68 throw new InvalidPageTitleRename(
69 'Trying to move a page which is not part of the translatable page', self::UNKNOWN_PAGE
70 );
71 }
72
73 [ $newNamespace, $search, $replace ] = $instructions;
74
75 if ( $newNamespace === self::IMPOSSIBLE ) {
76 throw new InvalidPageTitleRename(
77 'Trying to move a talk page to a namespace which does not have talk pages',
78 self::NS_TALK_UNSUPPORTED
79 );
80 }
81
82 $oldTitleText = $title->getText();
83
84 // Check if the old title matches the string being replaced, if so there is no
85 // need to run preg_replace. This will happen if the page is being moved from
86 // one namespace to another.
87 if ( $oldTitleText === $replace ) {
88 return Title::makeTitleSafe( $newNamespace, $replace );
89 }
90
91 $searchQuoted = preg_quote( $search, '~' );
92 $newText = preg_replace( "~^$searchQuoted~", $replace, $oldTitleText, 1 );
93
94 // If old and new title + namespace are same, the renaming failed.
95 if ( $oldTitleText === $newText && $newNamespace === $title->getNamespace() ) {
96 throw new InvalidPageTitleRename( 'Renaming failed', self::RENAME_FAILED );
97 }
98
99 $title = Title::makeTitleSafe( $newNamespace, $newText );
100 if ( $title === null ) {
101 throw new InvalidPageTitleRename( 'Invalid target title', self::INVALID_TITLE );
102 }
103
104 return $title;
105 }
106}
Contains logic to determine the new title of translatable pages and dependent pages being moved.