Skip to content

Commit

Permalink
Merge "Prevent getAllStatements from returning mutable entity stateme…
Browse files Browse the repository at this point in the history
…nts"
  • Loading branch information
jenkins-bot authored and Gerrit Code Review committed Nov 1, 2024
2 parents 156eae1 + ed5f153 commit 6093f8c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
18 changes: 17 additions & 1 deletion client/includes/DataAccess/Scribunto/mw.wikibase.entity.lua
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,21 @@ function methodtable.getSitelink( entity, globalSiteId )
return sitelink.title
end

-- @param {table} original
local function deepCopyTable(original)
local copy = {}
for k, v in pairs(original) do
if type(v) == "table" then
-- Recursively copy tables
copy[k] = deepCopyTable(v)
else
-- Directly copy non-table values
copy[k] = v
end
end
return copy
end

-- @param {table} entity
-- @param {string} propertyLabelOrId
-- @param {string} funcName for error logging
Expand All @@ -266,7 +281,8 @@ local function getEntityStatements( entity, propertyLabelOrId, funcName )
end

if propertyId and entity.claims[propertyId] then
return entity.claims[propertyId]
-- Create a deep copy of the statements table to prevent entity mutability.
return deepCopyTable(entity.claims[propertyId])
end

return {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ local function testGetAllStatementsFormat()
return directBestAccess ~= directAccess and directAccess == entityAccess
end

local function testGetAllStatementsTableIsCloned()
local statements = mw.wikibase.getAllStatements( 'Q32487', 'P342' )
table.remove(statements)

-- We should get a freshly cloned table here, so the changes above won't persist
local newStatements = mw.wikibase.getAllStatements( 'Q32487', 'P342' )
return #statements == #newStatements -1
end

local function testGetEntityObjectIsCloned()
mw.wikibase.getEntityObject( 'Q199024' ).id = 'a'

Expand Down Expand Up @@ -170,6 +179,9 @@ local tests = {
{ name = 'mw.wikibase.getAllStatements (format)', func = testGetAllStatementsFormat,
expect = { true }
},
{ name = 'mw.wikibase.getAllStatements (is cloned)', func = testGetAllStatementsTableIsCloned,
expect = { true }
},
{ name = 'mw.wikibase.getEntityObject (is cloned)', func = testGetEntityObjectIsCloned, type='ToString',
expect = { 'Q199024' }
},
Expand Down

0 comments on commit 6093f8c

Please sign in to comment.