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
66 public function getNewTitle( Title $title ): Title {
67 $instructions = $this->map[$title->getNamespace()] ?? null;
68 if ( $instructions === null ) {
69 throw new InvalidPageTitleRename(
70 'Trying to move a page which is not part of the translatable page', self::UNKNOWN_PAGE
71 );
72 }
73
74 [ $newNamespace, $search, $replace ] = $instructions;
75
76 if ( $newNamespace === self::IMPOSSIBLE ) {
77 throw new InvalidPageTitleRename(
78 'Trying to move a talk page to a namespace which does not have talk pages',
79 self::NS_TALK_UNSUPPORTED
80 );
81 }
82
83 $oldTitleText = $title->getText();
84
85 // Check if the old title matches the string being replaced, if so there is no
86 // need to run preg_replace. This will happen if the page is being moved from
87 // one namespace to another.
88 if ( $oldTitleText === $replace ) {
89 return Title::makeTitleSafe( $newNamespace, $replace );
90 }
91
92 $searchQuoted = preg_quote( $search, '~' );
93 $newText = preg_replace( "~^$searchQuoted~", $replace, $oldTitleText, 1 );
94
95 // If old and new title + namespace are same, the renaming failed.
96 if ( $oldTitleText === $newText && $newNamespace === $title->getNamespace() ) {
97 throw new InvalidPageTitleRename( 'Renaming failed', self::RENAME_FAILED );
98 }
99
100 $title = Title::makeTitleSafe( $newNamespace, $newText );
101 if ( $title === null ) {
102 throw new InvalidPageTitleRename( 'Invalid target title', self::INVALID_TITLE );
103 }
104
105 return $title;
106 }
107}
Contains logic to determine the new title of translatable pages and dependent pages being moved.