Wir laden dich herzlich auf den Star Citizen Wiki Discord Server ein! Du kannst uns auch auf unserem neuen YouTube-Chanel finden!

Modul:Common

From Star Citizen Wiki
Dokumentations-Unterseite Diese Dokumentationsseite spiegelt den Inhalt der Seite Modul:Common/Doku wieder.

Modulabhängigkeiten

Dieses Modul benötigt keine anderen Module.

Modulinfo

Das Modul Common stellt Funktionen bereit, welche allgemein in anderen Modulen weiterverwendet werden.

Öffentliche Methoden

Das Modul stellt folgende öffentliche Methoden bereit:

  • extractDataFromPrefix
    • Extrahiert alle Argumente, die mit 'argPrefix' beginnen, aus übergebenen Vorlageparametern
  • setDisplayTitle
    • Setzt den Abzeigetitel der aktuellen Seite
      • framm tabelle: Der zu bearbeitende Frame
      • title string: Seitentitel
      • flag string: Entweder 'noerror' oder 'noreplace'
  • removeTypeSuffix
    • Entfernt (...) Suffixe aus einer Zeichenkette
      • Beispiel:
        • Eingabe: Orion (Raumschiff)
        • Aufruf: common.removeTypeSuffix( 'Orion (Raumschiff)', 'Raumschiff' )
        • Ausgabe: Orion
  • checkSmwResult
    • Prüft, ob das Setzen von SMW-Daten erfolgreich war
  • checkApiResponse
    • Prüft, ob die Api-Anfrage erfolgreich war und ob die Antwort gültig ist
  • toNumber
    • Konvertiert eine Eingabe zu einer Zahl
  • formatNum
    • Formatiert eine Zahl entsprechend der Sprache des Inhalts
  • getImage
    • Findet das erste vorhandene Bild für die aktuelle Seite oder angegebene Namen
  • booleanToText
    • Ausgabe einer Zeichenkette basierend auf dem wahrheitsgemäßen Eingangswert
  • spairs
    • Sortiertes pairs
  • mapTranslation
    • Mapt { de_DE: '...', en_EN: '...' } zu einem Format was Semantic Media Wiki versteht
  • getLocaleForPage
    • Gibt den Sprachcode der aktuellen Seite zurück

Tests

✔ Alle Tests bestanden.

Name Expected Actual
testBooleanToTextFalseish
testBooleanToTextFalseishCustomText
testBooleanToTextTrueish
testExtractPrefixNumerical
testExtractPrefixNumericalEmpty
testFormatNum
testFormatNumberString
testFormatNumberStringFail
testRemoveTypeSuffix
testRemoveTypeSuffixNoMatch
testToNumberNum
testToNumberString
testToNumberStringFail

local common = {}

--- Extracts all arguments starting with 'argPrefix' form passed args
--- keyPrefix string Prefix of template parameters. Example: |template_param_1=foo, |template_param_2=bar PREFIX = template_param_
--- args table Frame arguments
--- mode string Param operation mode default %w = strings or integers. %a = strings, %d = digits. See https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Ustring_patterns
--- @param keyPrefix string
--- @param args table
--- @param mode string
--- @return table
function common.extractDataFromPrefix( keyPrefix, args, mode )
    local data = {}

    local operationMode = mode
    if operationMode == nil then
        operationMode = '%w'
    end

    for key, value in pairs( args ) do
        if mw.ustring.match( key, keyPrefix .. operationMode ) and value ~= nil then
            table.insert( data, value )
        end
    end

    return data
end

--- Set the Displaytitle of the current page
--- frame table The frame to operate on
--- title string Page title
--- flag string Either 'noerror' or 'noreplace'
--- @param frame table
--- @param title string
--- @param flag string
function common.setDisplayTitle( frame, title, flag )
    if flag ~= nil and ( flag ~= 'noerror' or flag ~= 'noreplace' ) then
        flag = nil
    end

    return frame:callParserFunction{
        name = 'DISPLAYTITLE:' .. title,
        args = {
            flag
        }
    }
end

--- Removes (...) suffixes
--- @param pageName string
--- @param suffix string|table
function common.removeTypeSuffix( pageName, suffix )
    if type( suffix ) == 'table' then
        for _, toRemove in pairs( suffix ) do
            pageName = common.removeTypeSuffix( pageName, toRemove )
        end

        return pageName
    end

    return mw.text.trim( pageName:gsub( '%(' .. suffix .. '%)', '' ), '_ ' )
end

--- Create interwiki links for a given title
--- @param pageName string
function common.generateInterWikiLinks( pageName )
	if pageName == nil or #pageName == '' then
		return ''
	end

	local prefixes = { 'en' }
	local suffixes = { 'Raumschiff', 'Sternensystem', 'Fahrzeug' }

	local out = ''

	for _, prefix in pairs( prefixes ) do
		out = out .. string.format( '[[%s:%s]]', prefix, common.removeTypeSuffix( pageName, suffixes ) )
	end
	
	return out
end

--- Checks if Setting SMW Data was successful
--- @param result table
function common.checkSmwResult( result )
    if result ~= true and result.error ~= nil then
        error( 'Semantic Mediawiki Fehler ' .. result.error )
    end
end

--- Checks if Api Request was successful and if the Response is valid
--- @param response table
--- @param errorOnData boolean
--- @param errorOnData boolean
function common.checkApiResponse( response, errorOnStatus, errorOnData )
    if response[ 'status_code' ] ~= nil and response[ 'status_code' ] ~= 200 then
        if errorOnStatus == nil or errorOnStatus == true then
            error( 'API Anfrage resultierte in Fehlercode ' .. response[ 'status_code' ] .. '(' .. response[ 'message' ] .. ')', 0 )
        end
    end

    if response[ 'data' ] == nil then
        if errorOnData == nil or errorOnData == true then
            error( 'API Daten entalten kein "data" Feld', 0 )
        end
    end
end

--- Convert an input to number
--- @param num string|integer Input
--- @param onFail string|integer Output if conversion fails
--- @param base integer Base for tonumber, defaults to 10
--- @return number
function common.toNumber( num, onFail, base )
	base = base or 10

    if num == nil then
        return onFail
    end

	local numCopy = num
    if type( num ) == 'string' then
        numCopy = num:gsub( ',', '.' )
    end

    numCopy = tonumber( numCopy, base )

    if numCopy == nil then
        return onFail
    end

    return numCopy
end

--- Formats a number according to the content language
--- @param num number|string
function common.formatNum( num, onFail )
    local converted = common.toNumber( num, false )

    if converted == nil or converted == false then
    	return onFail or false
	end

    return mw.language.getContentLanguage():formatNum( converted )
end

--- https://github.com/mirven/underscore.lua/blob/master/lib/underscore.lua
--- Slices an array
--- @param array table
--- @param start_index number
--- @param length number
function common.slice( array, start_index, length )
    local sliced_array = {}

    start_index = math.max( start_index, 1 )
    local end_index = math.min( start_index + length - 1, #array )
    for i = start_index, end_index do
        sliced_array[ #sliced_array + 1 ] = array[ i ]
    end

    return sliced_array
end

--- Find the first existing image for the current page or provided names
--- @param imageNames string|table names to check
--- @return string|boolean String if image found false if not
function common.getImage( imageNames )
    local names = {
        mw.title.getCurrentTitle().rootText,
        mw.title.getCurrentTitle().text
    }

	local argNames = {}

    local function checkName( image )
        local title = mw.ustring.gsub( image, '.jpg', '' )
        title = mw.ustring.gsub( title, '.png', '' )
        title = mw.ustring.gsub( title, '.webp', '' )

        local file = mw.title.new( title .. '.jpg', 6 )
        if file ~= nil and file.exists then
            return file.prefixedText
        end

        file = mw.title.new( title .. '.png', 6 )
        if file ~= nil and file.exists then
            return file.prefixedText
        end

        file = mw.title.new( title .. '.webp', 6 )
        if file ~= nil and file.exists then
            return file.prefixedText
        end

        return nil
	end

    if imageNames ~= nil then
        if type( imageNames ) == 'string' then
            imageNames = { imageNames }
        end

        for _, name in pairs( imageNames ) do
            if name ~= nil then
                table.insert( argNames, mw.uri.decode( name, 'WIKI' ) )
            end
        end
    end

    for _, image in pairs( argNames ) do
		local found = checkName( image )
		if found ~= nil then
			return found
		end
    end

    for _, image in pairs( names ) do
		local found = checkName( image )
		if found ~= nil then
			return found
		end
    end

    return false
end

--- Output a string based on the trueish input value
--- Note: Nil is considered to be false
--- @param input string|number|bolean Input to check
--- @param trueString string|number Output if true, defaults to 'Ja'
--- @param falseString string|number Output if true, defaults to 'Nein'
--- @return string|number|boolean
function common.booleanToText( input, trueString, falseString )
	trueString = trueString or 'Ja'
	falseString = falseString or 'Nein'

    if input == nil or
       input == false or
       input == 'false' or
       input == 0 or
       input == '0' or
       input == 'Nein' or
       input == 'nein' then
        return falseString
    end

    return trueString
end



--- Walks a table in order, can be used like pairs()
--- @param t table
--- @param order function - Sorting function OPTIONAL
function common.spairs( t, order )
    -- collect the keys
    local keys = {}
    for k in pairs(t) do keys[#keys+1] = k end

    -- if order function given, sort by it by passing the table and keys a, b,
    -- otherwise just sort the keys
    if order then
        table.sort(keys, function(a,b) return order(t, a, b) end)
    else
        table.sort(keys)
    end

    -- return the iterator function
    local i = 0
    return function()
        i = i + 1
        if keys[i] then
            return keys[i], t[keys[i]]
        end
    end
end


--- Maps an array from the api to monolingual text format
--- @param input table - Form of { "de_DE" = "...", "en_EN" = "..." } or table of tables
--- @param ucFirst boolean - Whether to uppercase the first character
--- @return table
function common.mapTranslation( input, ucFirst )
    input = input or {}
    ucFirst = ucFirst or false

    if type( input ) ~= 'table' then
        return input
    end

    local out = {}

    local function add( msg, locale )
        if ucFirst then
            msg = mw.language.getContentLanguage():ucfirst( msg )
        end

        table.insert( out, msg .. '@' .. string.sub( locale, 1, 2 ) )
    end

    for locale, translation in pairs( input ) do
        if type( translation ) == 'table' then
            for locale, msg in pairs( translation ) do
                add( msg, locale )
            end
        elseif type( translation ) == 'string' then
            add( translation, locale )
        end
    end

    return out
end


--- Returns the language code based on subpage name
--- Defaults to 'de'
--- @return string
function common.getLocaleForPage()
    local title = mw.title.getCurrentTitle()
    if not title.isSubpage then
        return 'de'
    end

    return title.subpageText
end


-- Titleparts Lib
common.titleparts = {}

--- https://github.com/wikimedia/mediawiki-extensions-ParserFunctions/blob/master/includes/ParserFunctions.php
--- @param title string
--- @param parts number
--- @param offset number
function common.titleparts.get( title, parts, offset )
    local ntitle = mw.title.new( title )

    parts = tonumber( parts )
    offset = tonumber( offset )

    if ntitle.exists == false then
        return title
    end

    local bits = mw.text.split( title, '/', true )

    if #bits <= 0 then
        return ntitle.prefixedText()
    else
        if parts == 0 then
            return table.concat( slice( bits, offset ), '/' )
        else
            return table.concat( slice( bits, offset, parts ), '/' )
        end
    end
end

return common
Cookies help us deliver our services. By using our services, you agree to our use of cookies.