Module:Zabytek/lib

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Lua

CodeDiscussionEditHistoryLinksLink count Subpages:DocumentationTestsResultsSandboxLive code All modules


Usage

[edit]

See: Module:Zabytek/lib/testcases

Used inside {{Zabytek nieruchomy}} for Polish WLM campaign.


Code

local p = {}

--[[
Test: User:Nux/test zabytek module
]] 

--[[
	Przetwarza Q na ID w bazie WLM (P2186 bez prefksu).
	
	"-" -- nieprawidłowe Q (np. jakieś losowe liter, cyfry itp)
	"" -- brak WLM ID w Q
]] 
function p.readWlmId(frame) 
	local qid = trim(frame.args[1])
	local ok, re = pcall(readWlmId, qid)
	if ok then
		return re.id
	else
        return "-"
    end
end

--[[
	Typ podanego parametru.
	
	"Q" -- identyfikator WD
	"+" -- liczba całkowita większa od zera
	"NN" -- inne
]] 
function p.whatId(frame) 
	local id = trim(frame.args[1])
	local ok, re = pcall(whatId, id)
	if ok then
		return re
	else
        return "NN"
    end
end

--[[
	Utnij prefiks dla WLM ID.
]] 
function p.chopPrefix(frame) 
	local wlmid = trim(frame.args[1])
	local num = wlmid:match("[A-Z]+[- ](%d+)$")
    return num
end

--[[
	Przetwarza Q na ID w bazie WLM (P2186 bez prefksu).
	
	qid = potencjalne Q1234 (string)
]]
function readWlmId(qid) 
	if (not mw.wikibase.isValidEntityId(qid)) then
		error('invalid qid')
	end
	local entity = mw.wikibase.getEntity(qid)
	local wlmid = entity and entity:formatPropertyValues('P2186').value
	local prefix = ""
	local sufix = ""
	if wlmid then
		prefix, sufix = wlmid:match("([A-Z]+)-(%d+)$")
	end
	return {wlmid=wlmid, prefix=prefix, id=sufix}
end

--[[
	Typ podanego parametru.
	
	"Q" -- identyfikator WD
	"+" -- liczba całkowita większa od zera
]] 
function whatId(id)
	if (isPositiveInteger(id)) then
		return "+"
	end
	if (isPrefixedWlmId(id)) then
		return "PL"
	end
	if (mw.wikibase.isValidEntityId(id)) then
		return "Q"
	end
	error('unknown')
end

--[[
	WLM ID with PL prefix.
]]
function isPrefixedWlmId(id)
    local pattern = "^PL[ -][0-9]+$"
    return string.find(id, pattern) ~= nil
end

--[[
	int+
]]
function isPositiveInteger(str)
    local num = tonumber(str)
    return num ~= nil and num > 0 and num == math.floor(num)
end

--[[
	trim string
]]
function trim(s)
	return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end

return p