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