From 37fcedbb3ff7ebf0ce97b0cc28291a3af1138380 Mon Sep 17 00:00:00 2001 From: Aryeh Gregor Date: Sun, 14 Apr 2019 11:59:59 +0300 Subject: [PATCH] New Title::castFromLinkTarget/TitleValue These behave the same as newFromLinkTarget/TitleValue, but accept null as well (and then just return null). This makes things much easier when converting code from using Title to LinkTarget, because you can wrap in castFromLinkTarget without adding null checks. Change-Id: Id61f91d40b81ad226532917c43e51f0b69af712c --- includes/Title.php | 13 +++++++++++++ tests/phpunit/includes/TitleTest.php | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/includes/Title.php b/includes/Title.php index 12ab532558..27baeb2a7e 100644 --- a/includes/Title.php +++ b/includes/Title.php @@ -246,6 +246,8 @@ class Title implements LinkTarget, IDBAccessObject { * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue * is already a Title instance, that instance is copied using the clone operator. * + * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget + * * @param TitleValue $titleValue Assumed to be safe. * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned. * @@ -283,6 +285,17 @@ class Title implements LinkTarget, IDBAccessObject { ); } + /** + * Same as newFromLinkTarget, but if passed null, returns null. + * + * @param LinkTarget|null $linkTarget Assumed to be safe (if not null). + * + * @return Title|null + */ + public static function castFromLinkTarget( $linkTarget ) { + return $linkTarget ? self::newFromLinkTarget( $linkTarget ) : null; + } + /** * Create a new Title from text, such as what one would find in a link. De- * codes any HTML entities in the text. diff --git a/tests/phpunit/includes/TitleTest.php b/tests/phpunit/includes/TitleTest.php index e29b7e7a3e..41a8d8514c 100644 --- a/tests/phpunit/includes/TitleTest.php +++ b/tests/phpunit/includes/TitleTest.php @@ -598,6 +598,27 @@ class TitleTest extends MediaWikiTestCase { $this->assertTrue( $clone->equals( $title ) ); } + public function provideCastFromLinkTarget() { + return array_merge( [ [ null ] ], self::provideNewFromTitleValue() ); + } + + /** + * @covers Title::castFromLinkTarget + * @dataProvider provideCastFromLinkTarget + */ + public function testCastFromLinkTarget( $value ) { + $title = Title::castFromLinkTarget( $value ); + + if ( $value === null ) { + $this->assertNull( $title ); + } else { + $dbkey = str_replace( ' ', '_', $value->getText() ); + $this->assertSame( $dbkey, $title->getDBkey() ); + $this->assertSame( $value->getNamespace(), $title->getNamespace() ); + $this->assertSame( $value->getFragment(), $title->getFragment() ); + } + } + public static function provideGetTitleValue() { return [ [ 'Foo' ], -- 2.20.1