پودمان:Protection banner/padlock/تمرین

از ویکی‌پدیا، دانشنامهٔ آزاد
توضیحات پودمان[ایجاد] [پاکسازی]
-- Creates a padlock object for use with [[Module:Protection banner]].

local mFileLink = require('Module:File link')
local libraryUtil = require('libraryUtil')
local checkType = libraryUtil.checkType

local padlock = {}

function padlock.new(options)
	checkType('padlock.new', 1, options, 'table')
	local obj, data = {}, {}
	
	local checkSelf = libraryUtil.makeCheckSelfFunction(
		'Module:Protection banner/padlock/تمرین',
		'padlock',
		obj,
		'padlock object'
	)

	local function validateOptionsField(field, nilOk)
		local val = options[field]
		local valType = type(val)
		if not (valType == 'string' or nilOk and valType == 'nil') then
			error(string.format(
				"bad value in field '%s' of the 'padlock.new' options table (expected string%s, got %s)",
				field,
				nilOk and ' or nil' or '',
				valType
			), 3)
		end
		return val
	end

	-- Import data from the options table.
	data.filename = validateOptionsField('filename')
	data.link     = validateOptionsField('link')
	data.alt      = validateOptionsField('alt')
	data.right    = validateOptionsField('right', true)

	function data:render()
		checkSelf(self, 'render')
		local image = mFileLink.new(data.filename)
			:link(data.link)
			:alt(data.alt)
			:render()
		local root = mw.html.create('div')
		root
			:addClass('metadata topicon nopopups')
			:attr('id', 'protected-icon')
			:css{display = 'none', right = data.right or '55px'}
			:wikitext(image)
		return tostring(root)
	end

	-- Define private and read-only fields for the object.
	local privateFields = {
		filename = true,
		link = true,
		alt = true,
		right = true
	}
	local readOnlyFields = {
		render = true
	}

	local function fieldError(field, status)
		error(string.format(
			"the '%s' field is %s",
			tostring(field),
			status
		), 3)
	end

	setmetatable(obj, {
		__index = function (t, k)
			if privateFields[k] then
				return nil
			else
				return data[k]
			end
		end,
		__newindex = function (t, k, v)
			if privateFields[k] then
				fieldError(k, 'private')
			elseif readOnlyFields[k] then
				fieldError(k, 'read-only')
			else
				data[k] = v
			end
		end,
		__tostring = function (t)
			return t:render()
		end,
		__pairs = function ()
			local temp = {}
			for k, v in pairs(data) do
				if not privateFields[k] then
					temp[k] = v
				end
			end
			return pairs(temp)
		end
	})
	return obj
end

return padlock