Commit 1086bb10 authored by Sebastian Kaspari's avatar Sebastian Kaspari
Browse files

ktx: Add extension method: Uri.hostWithoutCommonPrefixes.

parent 8f35eadf
Loading
Loading
Loading
Loading
+23 −0
Original line number Diff line number Diff line
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package mozilla.components.support.ktx.android.net

import android.net.Uri

/**
 * Returns the host without common prefixes like "www" or "m".
 */
@Suppress("MagicNumber")
val Uri.hostWithoutCommonPrefixes: String?
    get() {
        val host = host ?: return null

        return when {
            host.startsWith("www.") -> host.substring(4)
            host.startsWith("mobile.") -> host.substring(7)
            host.startsWith("m.") -> host.substring(2)
            else -> host
        }
    }
+40 −0
Original line number Diff line number Diff line
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package mozilla.components.support.ktx.android.net

import mozilla.components.support.ktx.kotlin.toUri
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner

@RunWith(RobolectricTestRunner::class)
class UriTest {
    @Test
    fun hostWithoutCommonPrefixes() {
        assertEquals(
            "mozilla.org",
            "https://www.mozilla.org".toUri().hostWithoutCommonPrefixes)

        assertEquals(
            "twitter.com",
            "https://mobile.twitter.com/home".toUri().hostWithoutCommonPrefixes)

        assertNull("".toUri().hostWithoutCommonPrefixes)

        assertEquals(
            "",
            "http://".toUri().hostWithoutCommonPrefixes)

        assertEquals(
            "facebook.com",
            "https://m.facebook.com/".toUri().hostWithoutCommonPrefixes)

        assertEquals(
            "github.com",
            "https://github.com/mozilla-mobile/android-components".toUri().hostWithoutCommonPrefixes)
    }
}