first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
define("core_table/local/dynamic/events",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;var eventName,_default={tableContentRefreshed:(eventName="tableContentRefreshed","core_table/dynamic:".concat(eventName))};return _exports.default=_default,_exports.default}));
//# sourceMappingURL=events.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"events.min.js","sources":["../../../src/local/dynamic/events.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Dynamic table selectors.\n *\n * @module core_table/local/dynamic/events\n * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nconst prefixEventName = eventName => `core_table/dynamic:${eventName}`;\n\nexport default {\n tableContentRefreshed: prefixEventName('tableContentRefreshed'),\n};\n"],"names":["eventName","tableContentRefreshed"],"mappings":"6JAuBwBA,mBAET,CACXC,uBAHoBD,UAGmB,qDAHgBA"}
+3
View File
@@ -0,0 +1,3 @@
define("core_table/local/dynamic/repository",["exports","core/ajax"],(function(_exports,_ajax){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.fetch=void 0;_exports.fetch=function(component,handler,uniqueid){let{sortData:sortData=[],joinType:joinType=null,filters:filters={},firstinitial:firstinitial=null,lastinitial:lastinitial=null,pageNumber:pageNumber=null,pageSize:pageSize=null,hiddenColumns:hiddenColumns={}}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},resetPreferences=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return(0,_ajax.call)([{methodname:"core_table_get_dynamic_table_content",args:{component:component,handler:handler,uniqueid:uniqueid,sortdata:sortData,jointype:joinType,filters:filters,firstinitial:firstinitial,lastinitial:lastinitial,pagenumber:pageNumber,pagesize:pageSize,hiddencolumns:hiddenColumns,resetpreferences:resetPreferences}}])[0]}}));
//# sourceMappingURL=repository.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"repository.min.js","sources":["../../../src/local/dynamic/repository.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * A javascript module to handle calendar ajax actions.\n *\n * @module core_table/local/dynamic/repository\n * @copyright 2017 Simey Lameze <lameze@moodle.com>\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nimport {call as fetchMany} from 'core/ajax';\n\n/**\n * Fetch table view.\n *\n * @method fetch\n * @param {String} component The component\n * @param {String} handler The name of the handler\n * @param {String} uniqueid The unique id of the table\n * @param {Object} options The options to use when updating the table\n * @param {Array} options.sortData The list of columns to sort by\n * @param {Number} options.joinType The filterset join type\n * @param {Object} options.filters The filters to apply when searching\n * @param {String} options.firstinitial The first name initial to filter on\n * @param {String} options.lastinitial The last name initial to filter on\n * @param {String} options.pageNumber The page number\n * @param {Number} options.pageSize The page size\n * @param {Object} options.hiddenColumns The columns to hide\n * @param {Bool} resetPreferences\n * @return {Promise} Resolved with requested table view\n */\nexport const fetch = (component, handler, uniqueid, {\n sortData = [],\n joinType = null,\n filters = {},\n firstinitial = null,\n lastinitial = null,\n pageNumber = null,\n pageSize = null,\n hiddenColumns = {}\n} = {}, resetPreferences = false) => fetchMany([{\n methodname: `core_table_get_dynamic_table_content`,\n args: {\n component,\n handler,\n uniqueid,\n sortdata: sortData,\n jointype: joinType,\n filters,\n firstinitial,\n lastinitial,\n pagenumber: pageNumber,\n pagesize: pageSize,\n hiddencolumns: hiddenColumns,\n resetpreferences: resetPreferences\n },\n}])[0];\n"],"names":["component","handler","uniqueid","sortData","joinType","filters","firstinitial","lastinitial","pageNumber","pageSize","hiddenColumns","resetPreferences","methodname","args","sortdata","jointype","pagenumber","pagesize","hiddencolumns","resetpreferences"],"mappings":"4LA2CqB,SAACA,UAAWC,QAASC,cAAUC,SAChDA,SAAW,GADqCC,SAEhDA,SAAW,KAFqCC,QAGhDA,QAAU,GAHsCC,aAIhDA,aAAe,KAJiCC,YAKhDA,YAAc,KALkCC,WAMhDA,WAAa,KANmCC,SAOhDA,SAAW,KAPqCC,cAQhDA,cAAgB,2DAChB,GAAIC,gFAA6B,cAAU,CAAC,CAC5CC,kDACAC,KAAM,CACFb,UAAAA,UACAC,QAAAA,QACAC,SAAAA,SACAY,SAAUX,SACVY,SAAUX,SACVC,QAAAA,QACAC,aAAAA,aACAC,YAAAA,YACAS,WAAYR,WACZS,SAAUR,SACVS,cAAeR,cACfS,iBAAkBR,qBAEtB"}
+3
View File
@@ -0,0 +1,3 @@
define("core_table/local/dynamic/selectors",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;return _exports.default={main:{region:'[data-region="core_table/dynamic"]',fromRegionId:regionId=>'[data-region="core_table/dynamic"][data-table-uniqueid="'.concat(regionId,'"]')},table:{links:{sortableColumn:'a[data-sortable="1"]',hide:'a[data-action="hide"]',show:'a[data-action="show"]'}},initialsBar:{links:{firstInitial:".firstinitial [data-initial]",lastInitial:".lastinitial [data-initial]"}},paginationBar:{links:{pageItem:".pagination [data-page-number]"}},showCount:{links:{toggle:'[data-action="showcount"]'}}},_exports.default}));
//# sourceMappingURL=selectors.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"selectors.min.js","sources":["../../../src/local/dynamic/selectors.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * Dynamic table selectors.\n *\n * @module core_table/local/dynamic/selectors\n * @copyright 2020 Simey Lameze <simey@moodle.com>\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nexport default {\n main: {\n region: '[data-region=\"core_table/dynamic\"]',\n fromRegionId: regionId => `[data-region=\"core_table/dynamic\"][data-table-uniqueid=\"${regionId}\"]`,\n },\n table: {\n links: {\n sortableColumn: 'a[data-sortable=\"1\"]',\n hide: 'a[data-action=\"hide\"]',\n show: 'a[data-action=\"show\"]',\n },\n },\n initialsBar: {\n links: {\n firstInitial: '.firstinitial [data-initial]',\n lastInitial: '.lastinitial [data-initial]',\n },\n },\n paginationBar: {\n links: {\n pageItem: '.pagination [data-page-number]'\n }\n },\n showCount: {\n links: {\n toggle: '[data-action=\"showcount\"]',\n },\n },\n};\n"],"names":["main","region","fromRegionId","regionId","table","links","sortableColumn","hide","show","initialsBar","firstInitial","lastInitial","paginationBar","pageItem","showCount","toggle"],"mappings":"oLAsBe,CACXA,KAAM,CACFC,OAAQ,qCACRC,aAAcC,4EAAuEA,gBAEzFC,MAAO,CACHC,MAAO,CACHC,eAAgB,uBAChBC,KAAM,wBACNC,KAAM,0BAGdC,YAAa,CACTJ,MAAO,CACHK,aAAc,+BACdC,YAAa,gCAGrBC,cAAe,CACXP,MAAO,CACHQ,SAAU,mCAGlBC,UAAW,CACPT,MAAO,CACHU,OAAQ"}
+472
View File
@@ -0,0 +1,472 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Module to handle dynamic table features.
*
* @module core_table/dynamic
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
import * as Selectors from 'core_table/local/dynamic/selectors';
import Events from './local/dynamic/events';
import Pending from 'core/pending';
import {addIconToContainer} from 'core/loadingicon';
import {fetch as fetchTableData} from 'core_table/local/dynamic/repository';
import Notification from 'core/notification';
let watching = false;
/**
* Ensure that a table is a dynamic table.
*
* @param {HTMLElement} tableRoot
* @returns {Bool}
*/
const checkTableIsDynamic = tableRoot => {
if (!tableRoot) {
// The table is not a dynamic table.
throw new Error("The table specified is not a dynamic table and cannot be updated");
}
if (!tableRoot.matches(Selectors.main.region)) {
// The table is not a dynamic table.
throw new Error("The table specified is not a dynamic table and cannot be updated");
}
return true;
};
/**
* Get the filterset data from a known dynamic table.
*
* @param {HTMLElement} tableRoot
* @returns {Object}
*/
const getFiltersetFromTable = tableRoot => {
return JSON.parse(tableRoot.dataset.tableFilters);
};
/**
* Update the specified table based on its current values.
*
* @param {HTMLElement} tableRoot
* @param {Bool} resetContent
* @returns {Promise}
*/
export const refreshTableContent = (tableRoot, resetContent = false) => {
const filterset = getFiltersetFromTable(tableRoot);
addIconToContainer(tableRoot);
const pendingPromise = new Pending('core_table/dynamic:refreshTableContent');
return fetchTableData(
tableRoot.dataset.tableComponent,
tableRoot.dataset.tableHandler,
tableRoot.dataset.tableUniqueid,
{
sortData: JSON.parse(tableRoot.dataset.tableSortData),
joinType: filterset.jointype,
filters: filterset.filters,
firstinitial: tableRoot.dataset.tableFirstInitial,
lastinitial: tableRoot.dataset.tableLastInitial,
pageNumber: tableRoot.dataset.tablePageNumber,
pageSize: tableRoot.dataset.tablePageSize,
hiddenColumns: JSON.parse(tableRoot.dataset.tableHiddenColumns),
},
resetContent,
)
.then(data => {
const placeholder = document.createElement('div');
placeholder.innerHTML = data.html;
tableRoot.replaceWith(...placeholder.childNodes);
// Update the tableRoot.
return getTableFromId(tableRoot.dataset.tableUniqueid);
}).then(tableRoot => {
tableRoot.dispatchEvent(new CustomEvent(Events.tableContentRefreshed, {
bubbles: true,
}));
return tableRoot;
})
.then(tableRoot => {
pendingPromise.resolve();
return tableRoot;
});
};
export const updateTable = (tableRoot, {
sortBy = null,
sortOrder = null,
filters = null,
firstInitial = null,
lastInitial = null,
pageNumber = null,
pageSize = null,
hiddenColumns = null,
} = {}, refreshContent = true) => {
checkTableIsDynamic(tableRoot);
const pendingPromise = new Pending('core_table/dynamic:updateTable');
let tableConfigChanged = false;
// Update sort fields.
if (sortBy && sortOrder) {
// Always update the table if requested and there were sort fields.
// These fields are only ever normalised in the backend.
tableConfigChanged = true;
const sortData = JSON.parse(tableRoot.dataset.tableSortData);
sortData.unshift({
sortby: sortBy,
sortorder: parseInt(sortOrder, 10),
});
tableRoot.dataset.tableSortData = JSON.stringify(sortData);
}
// Update initials.
if (firstInitial !== null) {
if (tableRoot.dataset.tableFirstInitial !== firstInitial) {
tableConfigChanged = true;
}
tableRoot.dataset.tableFirstInitial = firstInitial;
}
if (lastInitial !== null) {
if (tableRoot.dataset.tableLastInitial !== lastInitial) {
tableConfigChanged = true;
}
tableRoot.dataset.tableLastInitial = lastInitial;
}
if (pageSize !== null) {
if (tableRoot.dataset.tablePageSize != pageSize) {
tableConfigChanged = true;
}
tableRoot.dataset.tablePageSize = pageSize;
}
// Update filters.
if (filters) {
const filterJson = JSON.stringify(filters);
if (tableRoot.dataset.tableFilters !== filterJson) {
tableConfigChanged = true;
}
tableRoot.dataset.tableFilters = filterJson;
}
// Reset to page 1 when table content is being altered by filtering or sorting.
// This ensures the table page being loaded always exists, and gives a consistent experience.
if (tableConfigChanged) {
pageNumber = 1;
}
// Update hidden columns.
if (hiddenColumns) {
const columnJson = JSON.stringify(hiddenColumns);
if (tableRoot.dataset.tableHiddenColumns !== columnJson) {
tableConfigChanged = true;
}
tableRoot.dataset.tableHiddenColumns = columnJson;
}
if (pageNumber !== null) {
if (tableRoot.dataset.tablePageNumber != pageNumber) {
tableConfigChanged = true;
}
tableRoot.dataset.tablePageNumber = pageNumber;
}
// Refresh.
if (refreshContent && tableConfigChanged) {
return refreshTableContent(tableRoot)
.then(tableRoot => {
pendingPromise.resolve();
return tableRoot;
});
} else {
pendingPromise.resolve();
return Promise.resolve(tableRoot);
}
};
/**
* Get the table dataset for the specified tableRoot, ensuring that the provided table is a dynamic table.
*
* @param {HTMLElement} tableRoot
* @returns {DOMStringMap}
*/
const getTableData = tableRoot => {
checkTableIsDynamic(tableRoot);
return tableRoot.dataset;
};
/**
* Update the specified table using the new filters.
*
* @param {HTMLElement} tableRoot
* @param {Object} filters
* @param {Bool} refreshContent
* @returns {Promise}
*/
export const setFilters = (tableRoot, filters, refreshContent = true) =>
updateTable(tableRoot, {filters}, refreshContent);
/**
* Get the filter data for the specified table.
*
* @param {HTMLElement} tableRoot
* @returns {Object}
*/
export const getFilters = tableRoot => {
checkTableIsDynamic(tableRoot);
return getFiltersetFromTable(tableRoot);
};
/**
* Update the sort order.
*
* @param {HTMLElement} tableRoot
* @param {String} sortBy
* @param {Number} sortOrder
* @param {Bool} refreshContent
* @returns {Promise}
*/
export const setSortOrder = (tableRoot, sortBy, sortOrder, refreshContent = true) =>
updateTable(tableRoot, {sortBy, sortOrder}, refreshContent);
/**
* Set the page number.
*
* @param {HTMLElement} tableRoot
* @param {String} pageNumber
* @param {Bool} refreshContent
* @returns {Promise}
*/
export const setPageNumber = (tableRoot, pageNumber, refreshContent = true) =>
updateTable(tableRoot, {pageNumber}, refreshContent);
/**
* Get the current page number.
*
* @param {HTMLElement} tableRoot
* @returns {Number}
*/
export const getPageNumber = tableRoot => getTableData(tableRoot).tablePageNumber;
/**
* Set the page size.
*
* @param {HTMLElement} tableRoot
* @param {Number} pageSize
* @param {Bool} refreshContent
* @returns {Promise}
*/
export const setPageSize = (tableRoot, pageSize, refreshContent = true) =>
updateTable(tableRoot, {pageSize, pageNumber: 1}, refreshContent);
/**
* Get the current page size.
*
* @param {HTMLElement} tableRoot
* @returns {Number}
*/
export const getPageSize = tableRoot => getTableData(tableRoot).tablePageSize;
/**
* Update the first initial to show.
*
* @param {HTMLElement} tableRoot
* @param {String} firstInitial
* @param {Bool} refreshContent
* @returns {Promise}
*/
export const setFirstInitial = (tableRoot, firstInitial, refreshContent = true) =>
updateTable(tableRoot, {firstInitial}, refreshContent);
/**
* Get the current first initial filter.
*
* @param {HTMLElement} tableRoot
* @returns {String}
*/
export const getFirstInitial = tableRoot => getTableData(tableRoot).tableFirstInitial;
/**
* Update the last initial to show.
*
* @param {HTMLElement} tableRoot
* @param {String} lastInitial
* @param {Bool} refreshContent
* @returns {Promise}
*/
export const setLastInitial = (tableRoot, lastInitial, refreshContent = true) =>
updateTable(tableRoot, {lastInitial}, refreshContent);
/**
* Get the current last initial filter.
*
* @param {HTMLElement} tableRoot
* @returns {String}
*/
export const getLastInitial = tableRoot => getTableData(tableRoot).tableLastInitial;
/**
* Hide a column in the participants table.
*
* @param {HTMLElement} tableRoot
* @param {String} columnToHide
* @param {Bool} refreshContent
* @returns {Promise}
*/
export const hideColumn = (tableRoot, columnToHide, refreshContent = true) => {
const hiddenColumns = JSON.parse(tableRoot.dataset.tableHiddenColumns);
hiddenColumns.push(columnToHide);
return updateTable(tableRoot, {hiddenColumns}, refreshContent);
};
/**
* Make a hidden column visible in the participants table.
*
* @param {HTMLElement} tableRoot
* @param {String} columnToShow
* @param {Bool} refreshContent
* @returns {Promise}
*/
export const showColumn = (tableRoot, columnToShow, refreshContent = true) => {
let hiddenColumns = JSON.parse(tableRoot.dataset.tableHiddenColumns);
hiddenColumns = hiddenColumns.filter(columnName => columnName !== columnToShow);
return updateTable(tableRoot, {hiddenColumns}, refreshContent);
};
/**
* Reset table preferences.
*
* @param {HTMLElement} tableRoot
* @returns {Promise}
*/
const resetTablePreferences = tableRoot => refreshTableContent(tableRoot, true);
/**
* Set up listeners to handle table updates.
*/
export const init = () => {
if (watching) {
// Already watching.
return;
}
watching = true;
document.addEventListener('click', e => {
const tableRoot = e.target.closest(Selectors.main.region);
if (!tableRoot) {
return;
}
const sortableLink = e.target.closest(Selectors.table.links.sortableColumn);
if (sortableLink) {
e.preventDefault();
setSortOrder(tableRoot, sortableLink.dataset.sortby, sortableLink.dataset.sortorder)
.catch(Notification.exception);
}
const firstInitialLink = e.target.closest(Selectors.initialsBar.links.firstInitial);
if (firstInitialLink !== null) {
e.preventDefault();
setFirstInitial(tableRoot, firstInitialLink.dataset.initial).catch(Notification.exception);
}
const lastInitialLink = e.target.closest(Selectors.initialsBar.links.lastInitial);
if (lastInitialLink !== null) {
e.preventDefault();
setLastInitial(tableRoot, lastInitialLink.dataset.initial).catch(Notification.exception);
}
const pageItem = e.target.closest(Selectors.paginationBar.links.pageItem);
if (pageItem) {
e.preventDefault();
setPageNumber(tableRoot, pageItem.dataset.pageNumber).catch(Notification.exception);
}
const hide = e.target.closest(Selectors.table.links.hide);
if (hide) {
e.preventDefault();
hideColumn(tableRoot, hide.dataset.column).catch(Notification.exception);
}
const show = e.target.closest(Selectors.table.links.show);
if (show) {
e.preventDefault();
showColumn(tableRoot, show.dataset.column).catch(Notification.exception);
}
const resetTablePreferencesLink = e.target.closest('.resettable a');
if (resetTablePreferencesLink) {
e.preventDefault();
resetTablePreferences(tableRoot).catch(Notification.exception);
}
const showCountLink = e.target.closest(Selectors.showCount.links.toggle);
if (showCountLink) {
e.preventDefault();
setPageSize(tableRoot, showCountLink.dataset.targetPageSize).catch(Notification.exception);
}
});
};
/**
* Fetch the table via its table region id.
*
* @param {String} tableRegionId
* @returns {HTMLElement}
*/
export const getTableFromId = tableRegionId => {
const tableRoot = document.querySelector(Selectors.main.fromRegionId(tableRegionId));
if (!tableRoot) {
// The table is not a dynamic table.
throw new Error("The table specified is not a dynamic table and cannot be updated");
}
return tableRoot;
};
export {
Events
};
+28
View File
@@ -0,0 +1,28 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Dynamic table selectors.
*
* @module core_table/local/dynamic/events
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
const prefixEventName = eventName => `core_table/dynamic:${eventName}`;
export default {
tableContentRefreshed: prefixEventName('tableContentRefreshed'),
};
@@ -0,0 +1,69 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* A javascript module to handle calendar ajax actions.
*
* @module core_table/local/dynamic/repository
* @copyright 2017 Simey Lameze <lameze@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
import {call as fetchMany} from 'core/ajax';
/**
* Fetch table view.
*
* @method fetch
* @param {String} component The component
* @param {String} handler The name of the handler
* @param {String} uniqueid The unique id of the table
* @param {Object} options The options to use when updating the table
* @param {Array} options.sortData The list of columns to sort by
* @param {Number} options.joinType The filterset join type
* @param {Object} options.filters The filters to apply when searching
* @param {String} options.firstinitial The first name initial to filter on
* @param {String} options.lastinitial The last name initial to filter on
* @param {String} options.pageNumber The page number
* @param {Number} options.pageSize The page size
* @param {Object} options.hiddenColumns The columns to hide
* @param {Bool} resetPreferences
* @return {Promise} Resolved with requested table view
*/
export const fetch = (component, handler, uniqueid, {
sortData = [],
joinType = null,
filters = {},
firstinitial = null,
lastinitial = null,
pageNumber = null,
pageSize = null,
hiddenColumns = {}
} = {}, resetPreferences = false) => fetchMany([{
methodname: `core_table_get_dynamic_table_content`,
args: {
component,
handler,
uniqueid,
sortdata: sortData,
jointype: joinType,
filters,
firstinitial,
lastinitial,
pagenumber: pageNumber,
pagesize: pageSize,
hiddencolumns: hiddenColumns,
resetpreferences: resetPreferences
},
}])[0];
@@ -0,0 +1,51 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Dynamic table selectors.
*
* @module core_table/local/dynamic/selectors
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
export default {
main: {
region: '[data-region="core_table/dynamic"]',
fromRegionId: regionId => `[data-region="core_table/dynamic"][data-table-uniqueid="${regionId}"]`,
},
table: {
links: {
sortableColumn: 'a[data-sortable="1"]',
hide: 'a[data-action="hide"]',
show: 'a[data-action="show"]',
},
},
initialsBar: {
links: {
firstInitial: '.firstinitial [data-initial]',
lastInitial: '.lastinitial [data-initial]',
},
},
paginationBar: {
links: {
pageItem: '.pagination [data-page-number]'
}
},
showCount: {
links: {
toggle: '[data-action="showcount"]',
},
},
};
+47
View File
@@ -0,0 +1,47 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the dynamic interface.
*
* @package core_table
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
declare(strict_types=1);
namespace core_table;
/**
* Interface to identify this table as a table which can be dynamically updated via webservice calls.
*
* For a table to be defined as dynamic it must meet the following requirements:
*
* # it must be located with a namespaced class of \[component]\table\[tablename]
* # it must define a \core_table\local\filter\filterset implementation in \[component]\table\[tablename]_filterset
* # it must override the {{guess_base_url}} function and specify a base URL to be used when constructing URLs
* # it must override the {{get_context}} function to specify the correct context
*
* @package core_table
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface dynamic {
// Classes implementing this interface must define function `public has_capability(): bool`
// If it is not defined, the web service `core_table_get_dynamic_table_content` will check capability
// 'moodle/site:config' in the system context, allowing only admins to access the table data.
}
+290
View File
@@ -0,0 +1,290 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_table\external\dynamic;
use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_multiple_structure;
use core_external\external_single_structure;
use core_external\external_value;
use core_external\external_warnings;
/**
* Core table external functions.
*
* @package core_table
* @category external
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class get extends external_api {
/**
* Describes the parameters for fetching the table html.
*
* @return external_function_parameters
* @since Moodle 3.9
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters ([
'component' => new external_value(
PARAM_COMPONENT,
'Component',
VALUE_REQUIRED
),
'handler' => new external_value(
// Note: We do not have a PARAM_CLASSNAME which would have been ideal.
PARAM_ALPHANUMEXT,
'Handler',
VALUE_REQUIRED
),
'uniqueid' => new external_value(
PARAM_ALPHANUMEXT,
'Unique ID for the container',
VALUE_REQUIRED
),
'sortdata' => new external_multiple_structure(
new external_single_structure([
'sortby' => new external_value(
PARAM_ALPHANUMEXT,
'The name of a sortable column',
VALUE_REQUIRED
),
'sortorder' => new external_value(
PARAM_ALPHANUMEXT,
'The direction that this column should be sorted by',
VALUE_REQUIRED
),
]),
'The combined sort order of the table. Multiple fields can be specified.',
VALUE_OPTIONAL,
[]
),
'filters' => new external_multiple_structure(
new external_single_structure([
'name' => new external_value(PARAM_ALPHANUM, 'Name of the filter', VALUE_REQUIRED),
'jointype' => new external_value(PARAM_INT, 'Type of join for filter values', VALUE_REQUIRED),
'values' => new external_multiple_structure(
new external_value(PARAM_RAW, 'Filter value'),
'The value to filter on',
VALUE_REQUIRED
),
'filteroptions' => new external_multiple_structure(
new external_single_structure([
'name' => new external_value(PARAM_ALPHANUM, 'Name of the filter option', VALUE_REQUIRED),
'value' => new external_value(PARAM_RAW, 'Value of the filter option', VALUE_REQUIRED),
]),
'Additional options for this filter',
VALUE_OPTIONAL,
),
]),
'The filters that will be applied in the request',
VALUE_OPTIONAL
),
'jointype' => new external_value(PARAM_INT, 'Type of join to join all filters together', VALUE_REQUIRED),
'firstinitial' => new external_value(
PARAM_RAW,
'The first initial to sort filter on',
VALUE_REQUIRED,
null
),
'lastinitial' => new external_value(
PARAM_RAW,
'The last initial to sort filter on',
VALUE_REQUIRED,
null
),
'pagenumber' => new external_value(
PARAM_INT,
'The page number',
VALUE_REQUIRED,
null
),
'pagesize' => new external_value(
PARAM_INT,
'The number of records per page',
VALUE_REQUIRED,
null
),
'hiddencolumns' => new external_multiple_structure(
new external_value(
PARAM_ALPHANUMEXT,
'Name of column',
VALUE_REQUIRED,
null
)
),
'resetpreferences' => new external_value(
PARAM_BOOL,
'Whether the table preferences should be reset',
VALUE_REQUIRED,
null
),
]);
}
/**
* External function to get the table view content.
*
* @param string $component The component.
* @param string $handler Dynamic table class name.
* @param string $uniqueid Unique ID for the container.
* @param array $sortdata The columns and order to sort by
* @param array $filters The filters that will be applied in the request.
* @param string $jointype The join type.
* @param string $firstinitial The first name initial to filter on
* @param string $lastinitial The last name initial to filter on
* @param int $pagenumber The page number.
* @param int $pagesize The number of records.
* @param string $jointype The join type.
* @param bool $resetpreferences Whether it is resetting table preferences or not.
*
* @return array
*/
public static function execute(
string $component,
string $handler,
string $uniqueid,
array $sortdata,
?array $filters = null,
?string $jointype = null,
?string $firstinitial = null,
?string $lastinitial = null,
?int $pagenumber = null,
?int $pagesize = null,
?array $hiddencolumns = null,
?bool $resetpreferences = null
) {
global $PAGE;
[
'component' => $component,
'handler' => $handler,
'uniqueid' => $uniqueid,
'sortdata' => $sortdata,
'filters' => $filters,
'jointype' => $jointype,
'firstinitial' => $firstinitial,
'lastinitial' => $lastinitial,
'pagenumber' => $pagenumber,
'pagesize' => $pagesize,
'hiddencolumns' => $hiddencolumns,
'resetpreferences' => $resetpreferences,
] = self::validate_parameters(self::execute_parameters(), [
'component' => $component,
'handler' => $handler,
'uniqueid' => $uniqueid,
'sortdata' => $sortdata,
'filters' => $filters,
'jointype' => $jointype,
'firstinitial' => $firstinitial,
'lastinitial' => $lastinitial,
'pagenumber' => $pagenumber,
'pagesize' => $pagesize,
'hiddencolumns' => $hiddencolumns,
'resetpreferences' => $resetpreferences,
]);
$tableclass = "\\{$component}\\table\\{$handler}";
if (!class_exists($tableclass)) {
throw new \UnexpectedValueException("Table handler class {$tableclass} not found. " .
"Please make sure that your table handler class is under the \\{$component}\\table namespace.");
}
if (!is_subclass_of($tableclass, \core_table\dynamic::class)) {
throw new \UnexpectedValueException("Table handler class {$tableclass} does not support dynamic updating.");
}
$filtersetclass = $tableclass::get_filterset_class();
if (!class_exists($filtersetclass)) {
throw new \UnexpectedValueException("The filter specified ({$filtersetclass}) is invalid.");
}
$filterset = new $filtersetclass();
$filterset->set_join_type($jointype);
foreach ($filters as $rawfilter) {
$filterset->add_filter_from_params(
$rawfilter['name'],
$rawfilter['jointype'],
$rawfilter['values']
);
}
$instance = new $tableclass($uniqueid);
$instance->set_filterset($filterset);
self::validate_context($instance->get_context());
if (!method_exists($instance, 'has_capability')) {
// Method \core_table\dynamic::has_capability() will be added in Moodle 4.5. Until then if it is not
// implemented, we will require the admin capability.
require_capability('moodle/site:config', \context_system::instance());
} else if (!$instance->has_capability()) {
throw new \moodle_exception('nopermissiontoaccesspage');
}
$instance->set_sortdata($sortdata);
$alphabet = get_string('alphabet', 'langconfig');
if ($firstinitial !== null && ($firstinitial === '' || strpos($alphabet, $firstinitial) !== false)) {
$instance->set_first_initial($firstinitial);
}
if ($lastinitial !== null && ($lastinitial === '' || strpos($alphabet, $lastinitial) !== false)) {
$instance->set_last_initial($lastinitial);
}
if ($pagenumber !== null) {
$instance->set_page_number($pagenumber);
}
if ($pagesize === null) {
$pagesize = 20;
}
if ($hiddencolumns !== null) {
$instance->set_hidden_columns($hiddencolumns);
}
if ($resetpreferences === true) {
$instance->mark_table_to_reset();
}
$PAGE->set_url($instance->baseurl);
ob_start();
$instance->out($pagesize, true);
$tablehtml = ob_get_contents();
ob_end_clean();
return [
'html' => $tablehtml,
'warnings' => []
];
}
/**
* Describes the data returned from the external function.
*
* @return external_single_structure
* @since Moodle 3.9
*/
public static function execute_returns(): external_single_structure {
return new external_single_structure([
'html' => new external_value(PARAM_RAW, 'The raw html of the requested table.'),
'warnings' => new external_warnings()
]);
}
}
+271
View File
@@ -0,0 +1,271 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Table filterset.
*
* @package core
* @category table
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
declare(strict_types=1);
namespace core_table\local\filter;
use Countable;
use JsonSerializable;
use InvalidArgumentException;
use Iterator;
/**
* Class representing a generic filter of any type.
*
* @package core
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class filter implements Countable, Iterator, JsonSerializable {
/** @var int The default filter type (ANY) */
const JOINTYPE_DEFAULT = 1;
/** @var int None of the following match */
const JOINTYPE_NONE = 0;
/** @var int Any of the following match */
const JOINTYPE_ANY = 1;
/** @var int All of the following match */
const JOINTYPE_ALL = 2;
/** @var string The name of this filter */
protected $name = null;
/** @var int The join type currently in use */
protected $jointype = self::JOINTYPE_DEFAULT;
/** @var array The list of active filter values */
protected $filtervalues = [];
/** @var int[] valid join types */
protected $jointypes = [
self::JOINTYPE_NONE,
self::JOINTYPE_ANY,
self::JOINTYPE_ALL,
];
/** @var int The current iterator position */
protected $iteratorposition = null;
/**
* Constructor for the generic filter class.
*
* @param string $name The name of the current filter.
* @param int $jointype The join to use when combining the filters.
* See the JOINTYPE_ constants for further information on the field.
* @param mixed[] $values An array of filter objects to be applied.
*/
public function __construct(string $name, ?int $jointype = null, ?array $values = null) {
$this->name = $name;
if ($jointype !== null) {
$this->set_join_type($jointype);
}
if (!empty($values)) {
foreach ($values as $value) {
$this->add_filter_value($value);
}
}
}
/**
* Reset the iterator position.
*/
public function reset_iterator(): void {
$this->iteratorposition = null;
}
/**
* Return the current filter value.
*/
#[\ReturnTypeWillChange]
public function current() {
if ($this->iteratorposition === null) {
$this->rewind();
}
if ($this->iteratorposition === null) {
return null;
}
return $this->filtervalues[$this->iteratorposition];
}
/**
* Returns the current position of the iterator.
*
* @return int
*/
#[\ReturnTypeWillChange]
public function key() {
if ($this->iteratorposition === null) {
$this->rewind();
}
return $this->iteratorposition;
}
/**
* Rewind the Iterator position to the start.
*/
public function rewind(): void {
if ($this->iteratorposition === null) {
$this->sort_filter_values();
}
if (count($this->filtervalues)) {
$this->iteratorposition = 0;
}
}
/**
* Move to the next value in the list.
*/
public function next(): void {
++$this->iteratorposition;
}
/**
* Check if the current position is valid.
*
* @return bool
*/
public function valid(): bool {
return isset($this->filtervalues[$this->iteratorposition]);
}
/**
* Return the number of contexts.
*
* @return int
*/
public function count(): int {
return count($this->filtervalues);
}
/**
* Return the name of the filter.
*
* @return string
*/
public function get_name(): string {
return $this->name;
}
/**
* Specify the type of join to employ for the filter.
*
* @param int $jointype The join type to use using one of the supplied constants
* @return self
*/
public function set_join_type(int $jointype): self {
if (array_search($jointype, $this->jointypes) === false) {
throw new InvalidArgumentException('Invalid join type specified');
}
$this->jointype = $jointype;
return $this;
}
/**
* Return the currently specified join type.
*
* @return int
*/
public function get_join_type(): int {
return $this->jointype;
}
/**
* Add a value to the filter.
*
* @param mixed $value
* @return self
*/
public function add_filter_value($value): self {
if ($value === null) {
// Null values are usually invalid.
return $this;
}
if ($value === '') {
// Empty strings are invalid.
return $this;
}
if (array_search($value, $this->filtervalues) !== false) {
// Remove duplicates.
return $this;
}
$this->filtervalues[] = $value;
// Reset the iterator position.
$this->reset_iterator();
return $this;
}
/**
* Sort the filter values to ensure reliable, and consistent output.
*/
protected function sort_filter_values(): void {
// Sort the filter values to ensure consistent output.
// Note: This is not a locale-aware sort, but we don't need this.
// It's primarily for consistency, not for actual sorting.
sort($this->filtervalues);
$this->reset_iterator();
}
/**
* Return the current filter values.
*
* @return mixed[]
*/
public function get_filter_values(): array {
$this->sort_filter_values();
return $this->filtervalues;
}
/**
* Serialize filter.
*
* @return mixed|object
*/
#[\ReturnTypeWillChange]
public function jsonSerialize() {
return (object) [
'name' => $this->get_name(),
'jointype' => $this->get_join_type(),
'values' => $this->get_filter_values(),
];
}
}
@@ -0,0 +1,305 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Table filterset.
*
* @package core
* @category table
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
declare(strict_types=1);
namespace core_table\local\filter;
use InvalidArgumentException;
use JsonSerializable;
use UnexpectedValueException;
use moodle_exception;
/**
* Class representing a set of filters.
*
* @package core
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class filterset implements JsonSerializable {
/** @var int The default filter type (ALL) */
const JOINTYPE_DEFAULT = 2;
/** @var int None of the following match */
const JOINTYPE_NONE = 0;
/** @var int Any of the following match */
const JOINTYPE_ANY = 1;
/** @var int All of the following match */
const JOINTYPE_ALL = 2;
/** @var int The join type currently in use */
protected $jointype = null;
/** @var array The list of combined filter types */
protected $filtertypes = null;
/** @var array The list of active filters */
protected $filters = [];
/** @var int[] valid join types */
protected $jointypes = [
self::JOINTYPE_NONE,
self::JOINTYPE_ANY,
self::JOINTYPE_ALL,
];
/**
* Specify the type of join to employ for the filter.
*
* @param int $jointype The join type to use using one of the supplied constants
* @return self
*/
public function set_join_type(int $jointype): self {
if (array_search($jointype, $this->jointypes) === false) {
throw new InvalidArgumentException('Invalid join type specified');
}
$this->jointype = $jointype;
return $this;
}
/**
* Return the currently specified join type.
*
* @return int
*/
public function get_join_type(): int {
if ($this->jointype === null) {
$this->jointype = self::JOINTYPE_DEFAULT;
}
return $this->jointype;
}
/**
* Add the specified filter.
*
* @param filter $filter
* @return self
*/
public function add_filter(filter $filter): self {
$filtername = $filter->get_name();
if (array_key_exists($filtername, $this->filters)) {
// This filter already exists.
if ($this->filters[$filtername] === $filter) {
// This is the same value as already added.
// Just ignore it.
return $this;
}
// This is a different value to last time. Fail as this is not supported.
throw new UnexpectedValueException(
"A filter of type '{$filtername}' has already been added. Check that you have the correct filter."
);
}
// Ensure that the filter is both known, and is of the correct type.
$validtypes = $this->get_all_filtertypes();
if (!array_key_exists($filtername, $validtypes)) {
// Unknown filter.
throw new InvalidArgumentException(
"The filter '{$filtername}' was not recognised."
);
}
// Check that the filter is of the correct type.
if (!is_a($filter, $validtypes[$filtername])) {
$actualtype = get_class($filter);
$requiredtype = $validtypes[$filtername];
throw new InvalidArgumentException(
"The filter '{$filtername}' was incorrectly specified as a {$actualtype}. It must be a {$requiredtype}."
);
}
// All good. Add the filter.
$this->filters[$filtername] = $filter;
return $this;
}
/**
* Add the specified filter from the supplied params.
*
* @param string $filtername The name of the filter to create
* @param mixed[] ...$args Additional arguments used to create this filter type
* @return self
*/
public function add_filter_from_params(string $filtername, ...$args): self {
// Fetch the list of valid filters by name.
$validtypes = $this->get_all_filtertypes();
if (!array_key_exists($filtername, $validtypes)) {
// Unknown filter.
throw new InvalidArgumentException(
"The filter '{$filtername}' was not recognised."
);
}
$filterclass = $validtypes[$filtername];
if (!class_exists($filterclass)) {
// Filter class cannot be class autoloaded.
throw new InvalidArgumentException(
"The filter class '{$filterclass}' for filter '{$filtername}' could not be found."
);
}
// Pass all supplied arguments to the constructor when adding a new filter.
// This allows for a wider definition of the the filter in child classes.
$this->add_filter(new $filterclass($filtername, ...$args));
return $this;
}
/**
* Return the current set of filters.
*
* @return filter[]
*/
public function get_filters(): array {
// Sort the filters by their name to ensure consistent output.
// Note: This is not a locale-aware sort, but we don't need this.
// It's primarily for consistency, not for actual sorting.
asort($this->filters);
return $this->filters;
}
/**
* Check whether the filter has been added or not.
*
* @param string $filtername
* @return bool
*/
public function has_filter(string $filtername): bool {
// We do not check if the filtername is valid, only that it exists.
// This is an existence check and there is no benefit to doing any more.
return array_key_exists($filtername, $this->filters);
}
/**
* Get the named filter.
*
* @param string $filtername
* @return filter
*/
public function get_filter(string $filtername): filter {
if (!array_key_exists($filtername, $this->get_all_filtertypes())) {
throw new UnexpectedValueException("The filter specified ({$filtername}) is invalid.");
}
if (!array_key_exists($filtername, $this->filters)) {
throw new UnexpectedValueException("The filter specified ({$filtername}) has not been created.");
}
return $this->filters[$filtername];
}
/**
* Confirm whether the filter has been correctly specified.
*
* @throws moodle_exception
*/
public function check_validity(): void {
// Ensure that all required filters are present.
$missing = [];
foreach (array_keys($this->get_required_filters()) as $filtername) {
if (!array_key_exists($filtername, $this->filters)) {
$missing[] = $filtername;
}
}
if (!empty($missing)) {
throw new moodle_exception(
'missingrequiredfields',
'core_table',
'',
implode(get_string('listsep', 'langconfig') . ' ', $missing)
);
}
}
/**
* Get the list of required filters in an array of filtername => filter class type.
*
* @return array
*/
protected function get_required_filters(): array {
return [];
}
/**
* Get the list of optional filters in an array of filtername => filter class type.
*
* @return array
*/
protected function get_optional_filters(): array {
return [];
}
/**
* Get all filter valid types in an array of filtername => filter class type.
*
* @return array
*/
public function get_all_filtertypes(): array {
if ($this->filtertypes === null) {
$required = $this->get_required_filters();
$optional = $this->get_optional_filters();
$conflicts = array_keys(array_intersect_key($required, $optional));
if (!empty($conflicts)) {
throw new InvalidArgumentException(
"Some filter types are both required, and optional: " . implode(', ', $conflicts)
);
}
$this->filtertypes = array_merge($required, $optional);
asort($this->filtertypes);
}
return $this->filtertypes;
}
/**
* Serialize filterset.
*
* @return mixed|object
*/
#[\ReturnTypeWillChange]
public function jsonSerialize() {
return (object) [
'jointype' => $this->get_join_type(),
'filters' => $this->get_filters(),
];
}
}
@@ -0,0 +1,65 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Integer filter.
*
* @package core
* @category table
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
declare(strict_types=1);
namespace core_table\local\filter;
use TypeError;
/**
* Class representing an integer filter.
*
* @package core
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class integer_filter extends filter {
/**
* Add a value to the filter.
*
* @param int $values
* @return self
*/
public function add_filter_value($value): parent {
if (!is_int($value)) {
$type = gettype($value);
if ($type === 'object') {
$type = get_class($value);
}
throw new TypeError("The value supplied was of type '{$type}'. An integer was expected.");
}
if (array_search($value, $this->filtervalues) !== false) {
// Remove duplicates.
return $this;
}
$this->filtervalues[] = $value;
return $this;
}
}
@@ -0,0 +1,133 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Integer comparison filter to allow a comparison such as "> 42".
*
* @package core
* @category table
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
declare(strict_types=1);
namespace core_table\local\filter;
use InvalidArgumentException;
use TypeError;
/**
* Class representing an integer filter.
*
* @package core
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class numeric_comparison_filter extends filter {
/**
* Get the authoritative direction.
*
* @param string $direction The supplied direction
* @return string The authoritative direction
*/
protected function get_direction(string $direction): string {
$validdirections = [
'=' => '==',
'==' => '==',
'===' => '===',
'>' => '>',
'=>' => '=>',
'<' => '<',
'<=' => '<=',
];
if (!array_key_exists($direction, $validdirections)) {
throw new InvalidArgumentException("Invalid direction specified '{$direction}'.");
}
return $validdirections[$direction];
}
/**
* Add a value to the filter.
*
* @param string $value A json-encoded array containing a direction, and comparison value
* @return self
*/
public function add_filter_value($value): parent {
if (!is_string($value)) {
$type = gettype($value);
if ($type === 'object') {
$type = get_class($value);
}
throw new TypeError(
"The value supplied was of type '{$type}'. A string representing a json-encoded value was expected."
);
}
$data = json_decode($value);
if ($data === null) {
throw new InvalidArgumentException(
"A json-encoded object containing both a direction, and comparison value was expected."
);
}
if (!is_object($data)) {
$type = gettype($value);
throw new InvalidArgumentException(
"The value supplied was a json encoded '{$type}'. " .
"An object containing both a direction, and comparison value was expected."
);
}
if (!property_exists($data, 'direction')) {
throw new InvalidArgumentException("A 'direction' must be provided.");
}
$direction = $this->get_direction($data->direction);
if (!property_exists($data, 'value')) {
throw new InvalidArgumentException("A 'value' must be provided.");
}
$value = $data->value;
if (!is_numeric($value)) {
$type = gettype($value);
if ($type === 'object') {
$type = get_class($value);
}
throw new TypeError("The value supplied was of type '{$type}'. A numeric value was expected.");
}
$fullvalue = (object) [
'direction' => $direction,
'value' => $value,
];
if (array_search($fullvalue, $this->filtervalues) !== false) {
// Remove duplicates.
return $this;
}
$this->filtervalues[] = $fullvalue;
return $this;
}
}
@@ -0,0 +1,65 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* String filter.
*
* @package core
* @category table
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
declare(strict_types=1);
namespace core_table\local\filter;
use TypeError;
/**
* Class representing a string filter.
*
* @package core
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class string_filter extends filter {
/**
* Add a value to the filter.
*
* @param string $values
* @return self
*/
public function add_filter_value($value): parent {
if (!is_string($value)) {
$type = gettype($value);
if ($type === 'object') {
$type = get_class($value);
}
throw new TypeError("The value supplied was of type '{$type}'. A string was expected.");
}
if (array_search($value, $this->filtervalues) !== false) {
// Remove duplicates.
return $this;
}
$this->filtervalues[] = $value;
return $this;
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem for core_table API.
*
* @package core_table
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
declare(strict_types=1);
namespace core_table\privacy;
defined('MOODLE_INTERNAL') || die();
use core_privacy\local\metadata\null_provider;
/**
* Privacy Subsystem for core_table API.
*
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
}
+210
View File
@@ -0,0 +1,210 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for core_table\external\dynamic\get;
*
* @package core_table
* @category test
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
declare(strict_types = 1);
namespace core_table\external\dynamic;
use core_table\local\filter\filter;
use advanced_testcase;
/**
* Unit tests for core_table\external\dynamic\get;
*
* @package core_table
* @category test
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class get_test extends advanced_testcase {
/**
* Test execute invalid component format.
*/
public function test_execute_invalid_component_format(): void {
$this->resetAfterTest();
$this->expectException(\invalid_parameter_exception::class);
get::execute(
"core-user",
"participants",
"",
$this->get_sort_array(['email' => SORT_ASC]),
[],
(string) filter::JOINTYPE_ANY,
null,
null,
null,
null,
[],
null
);
}
/**
* Test execute invalid component.
*/
public function test_execute_invalid_component(): void {
$this->resetAfterTest();
$this->expectException(\UnexpectedValueException::class);
get::execute(
"core_users",
"participants",
"",
$this->get_sort_array(['email' => SORT_ASC]),
[],
(string) filter::JOINTYPE_ANY,
null,
null,
null,
null,
[],
null
);
}
/**
* Test execute invalid handler.
*/
public function test_execute_invalid_handler(): void {
$this->resetAfterTest();
$this->expectException('UnexpectedValueException');
$handler = "\\core_user\\table\\users_participants_table";
$this->expectExceptionMessage("Table handler class {$handler} not found. Please make sure that your table handler class is under the \\core_user\\table namespace.");
// Tests that invalid users_participants_table class gets an exception.
get::execute(
"core_user",
"users_participants_table",
"",
$this->get_sort_array(['email' => SORT_ASC]),
[],
(string) filter::JOINTYPE_ANY,
null,
null,
null,
null,
[],
null
);
}
/**
* Test execute invalid filter.
*/
public function test_execute_invalid_filter(): void {
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
// Filter with an invalid name.
$filter = [
[
'fullname' => 'courseid',
'jointype' => filter::JOINTYPE_ANY,
'values' => [(int) $course->id]
]
];
$this->expectException(\invalid_parameter_exception::class);
$this->expectExceptionMessage("Invalid parameter value detected (filters => Invalid parameter value detected " .
"(Missing required key in single structure: name): Missing required key in single structure: name");
get::execute(
"core_user",
"participants", "user-index-participants-{$course->id}",
$this->get_sort_array(['firstname' => SORT_ASC]),
$filter,
(string) filter::JOINTYPE_ANY
);
}
/**
* Test execute method.
*/
public function test_table_get_execute(): void {
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
$user1 = $this->getDataGenerator()->create_and_enrol($course, 'student', ['email' => 's1@moodle.com']);
$user2 = $this->getDataGenerator()->create_and_enrol($course, 'student', ['email' => 's2@moodle.com']);
$user3 = $this->getDataGenerator()->create_user(['email' => 's3@moodle.com']);
$teacher = $this->getDataGenerator()->create_and_enrol($course, 'teacher', ['email' => 't1@moodle.com']);
$this->setUser($teacher);
$this->get_sort_array(['email' => SORT_ASC]);
$filter = [
[
'name' => 'courseid',
'jointype' => filter::JOINTYPE_ANY,
'values' => [(int) $course->id]
]
];
$participantstable = get::execute(
"core_user",
"participants",
"user-index-participants-{$course->id}",
$this->get_sort_array(['firstname' => SORT_ASC]),
$filter,
(string) filter::JOINTYPE_ANY,
null,
null,
null,
null,
[],
null
);
$html = $participantstable['html'];
$this->assertStringContainsString($user1->email, $html);
$this->assertStringContainsString($user2->email, $html);
$this->assertStringContainsString($teacher->email, $html);
$this->assertStringNotContainsString($user3->email, $html);
}
/**
* Convert a traditional sort order into a sortorder for the web service.
*
* @param array $sortdata
* @return array
*/
protected function get_sort_array(array $sortdata): array {
$newsortorder = [];
foreach ($sortdata as $sortby => $sortorder) {
$newsortorder[] = [
'sortby' => $sortby,
'sortorder' => $sortorder,
];
}
return $newsortorder;
}
}
@@ -0,0 +1,344 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
declare(strict_types=1);
namespace core_table\local\filter;
use advanced_testcase;
use InvalidArgumentException;
/**
* Unit tests for core_table\local\filter\filter.
*
* @package core_table
* @category test
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @covers \core_table\local\filter\filter
*/
class filter_test extends advanced_testcase {
/**
* Test that the constructor correctly handles a number of conditions.
*
* @dataProvider constructor_provider
* @param array $args
* @param int $jointype
* @param array $values
*/
public function test_constructor(array $args, int $jointype, array $values): void {
$filter = new filter(...$args);
// We should always get a filter.
$this->assertInstanceOf(filter::class, $filter);
// We should always get the correct join type.
$this->assertEquals($jointype, $filter->get_join_type());
// The values should be the expected ones.
$this->assertSame($values, $filter->get_filter_values());
}
/**
* Data provider for the constructor providing a range of valid constructor arguments.
*
* @return array
*/
public function constructor_provider(): array {
return [
'Name without values' => [['keyword'], filter::JOINTYPE_DEFAULT, []],
'Name with valid join type ANY' => [[
'keyword',
filter::JOINTYPE_ANY,
], filter::JOINTYPE_ANY, []],
'Name with valid join type ALL' => [[
'keyword',
filter::JOINTYPE_ALL,
], filter::JOINTYPE_ALL, []],
'Name with valid join type NONE' => [[
'keyword',
filter::JOINTYPE_NONE,
], filter::JOINTYPE_NONE, []],
'Name, no join type, with set of values' => [
[
'keyword',
null,
[
's1',
'janine',
],
],
filter::JOINTYPE_DEFAULT,
[
'janine',
's1',
],
],
'Name, and ANY, with set of values' => [
[
'keyword',
filter::JOINTYPE_ANY,
[
's1',
'kevin',
'james',
'janine',
],
],
filter::JOINTYPE_ANY,
[
'james',
'janine',
'kevin',
's1',
],
],
'Name, and ANY, with set of values which contains duplicates' => [
[
'keyword',
filter::JOINTYPE_ANY,
[
's1',
'kevin',
'james',
'janine',
'kevin',
],
],
filter::JOINTYPE_ANY,
[
'james',
'janine',
'kevin',
's1',
],
],
];
}
/**
* Test that the constructor throws a relevant exception when passed an invalid join.
*
* @dataProvider constructor_invalid_join_provider
* @param mixed $jointype
*/
public function test_constructor_invalid_joins($jointype): void {
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid join type specified');
new filter('invalid', $jointype);
}
/**
* Data provider for the constructor providing a range of invalid join types to the constructor.
*
* @return array
*/
public function constructor_invalid_join_provider(): array {
return [
'Too low' => [-1],
'Too high' => [4],
];
}
/**
* Enusre that adding filter values works as expected.
*/
public function test_add_filter_value(): void {
$filter = new filter('example');
// Initially an empty list.
$this->assertEmpty($filter->get_filter_values());
// Adding null should do nothing.
$filter->add_filter_value(null);
$this->assertEmpty($filter->get_filter_values());
// Adding empty string should do nothing.
$filter->add_filter_value('');
$this->assertEmpty($filter->get_filter_values());
// Adding a value should return that value.
$filter->add_filter_value('rosie');
$this->assertSame([
'rosie',
], $filter->get_filter_values());
// Adding a second value should add that value.
// The values should sorted.
$filter->add_filter_value('arthur');
$this->assertSame([
'arthur',
'rosie',
], $filter->get_filter_values());
// Adding a duplicate value should not lead to that value being added again.
$filter->add_filter_value('arthur');
$this->assertSame([
'arthur',
'rosie',
], $filter->get_filter_values());
}
/**
* Ensure that it is possibly to set the join type.
*/
public function test_set_join_type(): void {
$filter = new filter('example');
// Initial set with the default type should just work.
// The setter should be chainable.
$this->assertEquals($filter, $filter->set_join_type(filter::JOINTYPE_DEFAULT));
$this->assertEquals(filter::JOINTYPE_DEFAULT, $filter->get_join_type());
// It should be possible to update the join type later.
$this->assertEquals($filter, $filter->set_join_type(filter::JOINTYPE_NONE));
$this->assertEquals(filter::JOINTYPE_NONE, $filter->get_join_type());
$this->assertEquals($filter, $filter->set_join_type(filter::JOINTYPE_ANY));
$this->assertEquals(filter::JOINTYPE_ANY, $filter->get_join_type());
$this->assertEquals($filter, $filter->set_join_type(filter::JOINTYPE_ALL));
$this->assertEquals(filter::JOINTYPE_ALL, $filter->get_join_type());
}
/**
* Ensure that it is not possible to provide a value out of bounds when setting the join type.
*/
public function test_set_join_type_invalid_low(): void {
$filter = new filter('example');
// Valid join types are current 0, 1, or 2.
// A value too low should be rejected.
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("Invalid join type specified");
$filter->set_join_type(-1);
}
/**
* Ensure that it is not possible to provide a value out of bounds when setting the join type.
*/
public function test_set_join_type_invalid_high(): void {
$filter = new filter('example');
// Valid join types are current 0, 1, or 2.
// A value too low should be rejected.
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("Invalid join type specified");
$filter->set_join_type(4);
}
/**
* Ensure that the name getter is callable.
*/
public function test_get_name(): void {
$filter = new filter('examplename');
$this->assertEquals('examplename', $filter->get_name());
}
/**
* Data provider for the countable tests.
*
* @return array
*/
public function filter_value_provider(): array {
return [
'Empty' => [[], 0],
'Single value' => [[10], 1],
'Single repeated value' => [[10, 10, 10, 10], 1],
'Multiple values, no repeats' => [[1, 2, 3, 4, 5], 5],
'Multiple values, including repeats' => [[1, 2, 1, 3, 1, 3, 4, 1, 5], 5],
];
}
/**
* Ensure that the filter is countable.
*
* @dataProvider filter_value_provider
* @param array $values List of context IDs
* @param int $count Expected count
*/
public function test_countable($values, $count): void {
$filter = new filter('example', null, $values);
$this->assertCount($count, $filter);
}
/**
* Ensure that the contextlist_base iterates over the set of contexts.
*/
public function test_filter_iteration(): void {
$filter = new filter('example');
// The iterator position should be at the start.
$this->assertEquals(0, $filter->key());
foreach ($filter as $filtervalue) {
// This should not be called.
$this->assertFalse(true);
}
// The iterator position should still be at the start.
$this->assertEquals(0, $filter->key());
// Adding filter values should cause the values in the Iterator to be sorted.
$filter = new filter('example');
$filter->add_filter_value(6);
$filter->add_filter_value(5);
$filter->add_filter_value(4);
$filter->add_filter_value(3);
$filter->add_filter_value(2);
// The iterator position should be at the start after adding values.
$this->assertEquals(0, $filter->key());
$foundvalues = [];
foreach ($filter as $filtervalue) {
$foundvalues[] = $filtervalue;
}
$this->assertEquals([2, 3, 4, 5, 6], $foundvalues);
// The iterator position should now be at position 5.
// The position is automatically updated prior to moving.
$this->assertEquals(5, $filter->key());
// Adding another value shoudl cause the Iterator to be re-sorted.
$filter->add_filter_value(1);
// The iterator position should be at the start after adding values.
$this->assertEquals(0, $filter->key());
$foundvalues = [];
foreach ($filter as $filtervalue) {
$foundvalues[] = $filtervalue;
}
$this->assertEquals([1, 2, 3, 4, 5, 6], $foundvalues);
// The iterator position should now be at position 6.
$this->assertEquals(6, $filter->key());
}
/**
* Tests for the count function of a filter.
*/
public function test_filter_current(): void {
$filter = new filter('example', null, [42]);
$this->assertEquals(42, $filter->current());
}
}
@@ -0,0 +1,545 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for core_table\local\filter\filterset.
*
* @package core_table
* @category test
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
declare(strict_types=1);
namespace core_table\local\filter;
use InvalidArgumentException;
use UnexpectedValueException;
use advanced_testcase;
use moodle_exception;
/**
* Unit tests for core_table\local\filter\filterset.
*
* @package core_table
* @category test
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class filterset_test extends advanced_testcase {
/**
* Ensure that it is possibly to set the join type.
*/
public function test_set_join_type(): void {
$filterset = $this->get_mocked_filterset();
// Initial set with the default type should just work.
// The setter should be chainable.
$this->assertEquals($filterset, $filterset->set_join_type(filterset::JOINTYPE_DEFAULT));
$this->assertEquals(filterset::JOINTYPE_DEFAULT, $filterset->get_join_type());
// It should be possible to update the join type later.
$this->assertEquals($filterset, $filterset->set_join_type(filterset::JOINTYPE_NONE));
$this->assertEquals(filterset::JOINTYPE_NONE, $filterset->get_join_type());
$this->assertEquals($filterset, $filterset->set_join_type(filterset::JOINTYPE_ANY));
$this->assertEquals(filterset::JOINTYPE_ANY, $filterset->get_join_type());
$this->assertEquals($filterset, $filterset->set_join_type(filterset::JOINTYPE_ALL));
$this->assertEquals(filterset::JOINTYPE_ALL, $filterset->get_join_type());
}
/**
* Ensure that it is not possible to provide a value out of bounds when setting the join type.
*/
public function test_set_join_type_invalid_low(): void {
$filterset = $this->get_mocked_filterset();
// Valid join types are current 0, 1, or 2.
// A value too low should be rejected.
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("Invalid join type specified");
$filterset->set_join_type(-1);
}
/**
* Ensure that it is not possible to provide a value out of bounds when setting the join type.
*/
public function test_set_join_type_invalid_high(): void {
$filterset = $this->get_mocked_filterset();
// Valid join types are current 0, 1, or 2.
// A value too low should be rejected.
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("Invalid join type specified");
$filterset->set_join_type(4);
}
/**
* Ensure that adding filter values works as expected.
*/
public function test_add_filter_value(): void {
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
'name' => filter::class,
'species' => filter::class,
]));
// Initially an empty list.
$this->assertEmpty($filterset->get_filters());
// Test data.
$speciesfilter = new filter('species', null, ['canine']);
$namefilter = new filter('name', null, ['rosie']);
// Add a filter to the list.
$filterset->add_filter($speciesfilter);
$this->assertSame([
$speciesfilter,
], array_values($filterset->get_filters()));
// Adding a second value should add that value.
// The values should sorted.
$filterset->add_filter($namefilter);
$this->assertSame([
$namefilter,
$speciesfilter,
], array_values($filterset->get_filters()));
// Adding an existing filter again should be ignored.
$filterset->add_filter($speciesfilter);
$this->assertSame([
$namefilter,
$speciesfilter,
], array_values($filterset->get_filters()));
}
/**
* Ensure that it is possible to add a filter of a validated filter type.
*/
public function test_add_filter_validated_type(): void {
$namefilter = $this->getMockBuilder(filter::class)
->setConstructorArgs(['name'])
->onlyMethods([])
->getMock();
$namefilter->add_filter_value('rosie');
// Mock the get_optional_filters function.
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
'name' => get_class($namefilter),
]));
// Add a filter to the list.
// This is the 'name' filter.
$filterset->add_filter($namefilter);
$this->assertNull($filterset->check_validity());
}
/**
* Ensure that it is not possible to add a type which is not expected.
*/
public function test_add_filter_unexpected_key(): void {
// Mock the get_optional_filters function.
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([]));
// Add a filter to the list.
// This is the 'name' filter.
$namefilter = new filter('name');
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("The filter 'name' was not recognised.");
$filterset->add_filter($namefilter);
}
/**
* Ensure that it is not possible to add a validated type where the type is incorrect.
*/
public function test_add_filter_validated_type_incorrect(): void {
$filtername = "name";
$otherfilter = $this->createMock(filter::class);
// Mock the get_optional_filters function.
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
$filtername => get_class($otherfilter),
]));
// Add a filter to the list.
// This is the 'name' filter.
$namefilter = $this->getMockBuilder(filter::class)
->onlyMethods([])
->setConstructorArgs([$filtername])
->getMock();
$actualtype = get_class($namefilter);
$requiredtype = get_class($otherfilter);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
"The filter '{$filtername}' was incorrectly specified as a {$actualtype}. It must be a {$requiredtype}."
);
$filterset->add_filter($namefilter);
}
/**
* Ensure that a filter can be added from parameters provided to a web service.
*/
public function test_add_filter_from_params(): void {
$filtername = "name";
$otherfilter = $this->getMockBuilder(filter::class)
->onlyMethods([])
->setConstructorArgs([$filtername])
->getMock();
// Mock the get_optional_filters function.
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
$filtername => get_class($otherfilter),
]));
$result = $filterset->add_filter_from_params($filtername, filter::JOINTYPE_DEFAULT, ['kevin']);
// The function is chainable.
$this->assertEquals($filterset, $result);
// Get the filter back.
$filter = $filterset->get_filter($filtername);
$this->assertEquals($filtername, $filter->get_name());
$this->assertEquals(filter::JOINTYPE_DEFAULT, $filter->get_join_type());
$this->assertEquals(['kevin'], $filter->get_filter_values());
}
/**
* Ensure that an unknown filter is not added.
*/
public function test_add_filter_from_params_unable_to_autoload(): void {
// Mock the get_optional_filters function.
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
'name' => '\\moodle\\this\\is\\a\\fake\\class\\name',
]));
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
"The filter class '\\moodle\\this\\is\\a\\fake\\class\\name' for filter 'name' could not be found."
);
$filterset->add_filter_from_params('name', filter::JOINTYPE_DEFAULT, ['kevin']);
}
/**
* Ensure that an unknown filter is not added.
*/
public function test_add_filter_from_params_invalid(): void {
$filtername = "name";
$otherfilter = $this->getMockBuilder(filter::class)
->onlyMethods([])
->setConstructorArgs([$filtername])
->getMock();
// Mock the get_optional_filters function.
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
$filtername => get_class($otherfilter),
]));
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("The filter 'unknownfilter' was not recognised.");
$filterset->add_filter_from_params('unknownfilter', filter::JOINTYPE_DEFAULT, ['kevin']);
}
/**
* Ensure that adding a different filter with a different object throws an Exception.
*/
public function test_duplicate_filter_value(): void {
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
'name' => filter::class,
'species' => filter::class,
]));
// Add a filter to the list.
// This is the 'name' filter.
$namefilter = new filter('name', null, ['rosie']);
$filterset->add_filter($namefilter);
// Add another filter to the list.
// This one has been incorrectly called the 'name' filter when it should be 'species'.
$this->expectException(UnexpectedValueException::Class);
$this->expectExceptionMessage("A filter of type 'name' has already been added. Check that you have the correct filter.");
$speciesfilter = new filter('name', null, ['canine']);
$filterset->add_filter($speciesfilter);
}
/**
* Ensure that validating a filterset correctly compares filter types.
*/
public function test_check_validity_optional_filters_not_specified(): void {
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
'name' => filter::class,
'species' => filter::class,
]));
$this->assertNull($filterset->check_validity());
}
/**
* Ensure that validating a filterset correctly requires required filters.
*/
public function test_check_validity_required_filter(): void {
$filterset = $this->get_mocked_filterset(['get_required_filters']);
$filterset->expects($this->any())
->method('get_required_filters')
->willReturn([
'name' => filter::class
]);
// Add a filter to the list.
// This is the 'name' filter.
$filterset->add_filter(new filter('name'));
$this->assertNull($filterset->check_validity());
}
/**
* Ensure that validating a filterset excepts correctly when a required fieldset is missing.
*/
public function test_check_validity_filter_missing_required(): void {
$filterset = $this->get_mocked_filterset(['get_required_filters']);
$filterset->expects($this->any())
->method('get_required_filters')
->willReturn([
'name' => filter::class,
'species' => filter::class,
]);
$this->expectException(moodle_exception::Class);
$this->expectExceptionMessage("One or more required filters were missing (name, species)");
$filterset->check_validity();
}
/**
* Ensure that getting the filters returns a sorted list of filters.
*/
public function test_get_filters(): void {
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
// Filters are not defined lexically.
'd' => filter::class,
'b' => filter::class,
'a' => filter::class,
'c' => filter::class,
]));
// Filters are added in a different non-lexical order.
$c = new filter('c');
$filterset->add_filter($c);
$b = new filter('b');
$filterset->add_filter($b);
$d = new filter('d');
$filterset->add_filter($d);
$a = new filter('a');
$filterset->add_filter($a);
// But they are returned lexically sorted.
$this->assertEquals([
'a' => $a,
'b' => $b,
'c' => $c,
'd' => $d,
], $filterset->get_filters());
}
/**
* Ensure that getting a singlel filter returns the correct filter.
*/
public function test_get_filter(): void {
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
// Filters are not defined lexically.
'd' => filter::class,
'b' => filter::class,
'a' => filter::class,
'c' => filter::class,
]));
// Filters are added in a different non-lexical order.
$c = new filter('c');
$filterset->add_filter($c);
$b = new filter('b');
$filterset->add_filter($b);
$d = new filter('d');
$filterset->add_filter($d);
$a = new filter('a');
$filterset->add_filter($a);
// Filters can be individually retrieved in any order.
$this->assertEquals($d, $filterset->get_filter('d'));
$this->assertEquals($a, $filterset->get_filter('a'));
$this->assertEquals($b, $filterset->get_filter('b'));
$this->assertEquals($c, $filterset->get_filter('c'));
}
/**
* Ensure that it is not possible to retrieve an unknown filter.
*/
public function test_get_filter_unknown(): void {
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
'a' => filter::class,
]));
$a = new filter('a');
$filterset->add_filter($a);
$this->expectException(UnexpectedValueException::Class);
$this->expectExceptionMessage("The filter specified (d) is invalid.");
$filterset->get_filter('d');
}
/**
* Ensure that it is not possible to retrieve a valid filter before it is created.
*/
public function test_get_filter_not_yet_added(): void {
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
'a' => filter::class,
]));
$this->expectException(UnexpectedValueException::Class);
$this->expectExceptionMessage("The filter specified (a) has not been created.");
$filterset->get_filter('a');
}
/**
* Ensure that the get_all_filtertypes function correctly returns the combined filterset.
*/
public function test_get_all_filtertypes(): void {
$otherfilter = $this->createMock(filter::class);
$filterset = $this->get_mocked_filterset([
'get_optional_filters',
'get_required_filters',
]);
$filterset->method('get_optional_filters')
->will($this->returnValue([
'a' => filter::class,
'c' => get_class($otherfilter),
]));
$filterset->method('get_required_filters')
->will($this->returnValue([
'b' => get_class($otherfilter),
'd' => filter::class,
]));
$this->assertEquals([
'a' => filter::class,
'b' => get_class($otherfilter),
'c' => get_class($otherfilter),
'd' => filter::class,
], $filterset->get_all_filtertypes());
}
/**
* Ensure that the get_all_filtertypes function correctly returns the combined filterset.
*/
public function test_get_all_filtertypes_conflict(): void {
$otherfilter = $this->createMock(filter::class);
$filterset = $this->get_mocked_filterset([
'get_optional_filters',
'get_required_filters',
]);
$filterset->method('get_optional_filters')
->will($this->returnValue([
'a' => filter::class,
'b' => get_class($otherfilter),
'd' => filter::class,
]));
$filterset->method('get_required_filters')
->will($this->returnValue([
'b' => get_class($otherfilter),
'c' => filter::class,
'd' => filter::class,
]));
$this->expectException(InvalidArgumentException::Class);
$this->expectExceptionMessage("Some filter types are both required, and optional: b, d");
$filterset->get_all_filtertypes();
}
/**
* Ensure that the has_filter function works as expected.
*/
public function test_has_filter(): void {
$filterset = $this->get_mocked_filterset(['get_optional_filters']);
$filterset->method('get_optional_filters')
->will($this->returnValue([
// Define filters 'a', and 'b'.
'a' => filter::class,
'b' => filter::class,
]));
// Only add filter 'a'.
$a = new filter('a');
$filterset->add_filter($a);
// Filter 'a' should exist.
$this->assertTrue($filterset->has_filter('a'));
// Filter 'b' is defined, but has not been added.
$this->assertFalse($filterset->has_filter('b'));
// Filter 'c' is not defined.
// No need to throw any kind of exception - this is an existence check.
$this->assertFalse($filterset->has_filter('c'));
}
/**
* Get a mocked copy of the filterset, mocking the specified methods.
*
* @param array $mockedmethods anonymous array containing the list of mocked methods
* @return filterset Mock of the filterset
*/
protected function get_mocked_filterset(array $mockedmethods = []): filterset {
return $this->getMockForAbstractClass(filterset::class, [], '', true, true, true, $mockedmethods);
}
}
@@ -0,0 +1,109 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for core_table\local\filter\filter.
*
* @package core_table
* @category test
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
declare(strict_types=1);
namespace core_table\local\filter;
use advanced_testcase;
use TypeError;
/**
* Unit tests for core_table\local\filter\integer_filter.
*
* @package core_table
* @category test
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class integer_filter_test extends advanced_testcase {
/**
* Ensure that the add_filter_value function works as expected with valid values.
*/
public function test_add_filter_value_int(): void {
$filter = new integer_filter('example');
// Initially an empty list.
$this->assertEmpty($filter->get_filter_values());
// Adding a value should return that value.
$filter->add_filter_value(10);
$this->assertSame([
10,
], $filter->get_filter_values());
// Adding a second value should add that value.
// The values should sorted.
$filter->add_filter_value(2);
$this->assertSame([
2,
10,
], $filter->get_filter_values());
// Adding a duplicate value should not lead to that value being added again.
$filter->add_filter_value(10);
$this->assertSame([
2,
10,
], $filter->get_filter_values());
}
/**
* Ensure that the add_filter_value function rejects invalid types.
*
* @dataProvider add_filter_value_invalid_types_provider
* @param mixed $value
* @param string $type
*/
public function test_add_filter_value_type_invalid($value, string $type): void {
$filter = new integer_filter('example');
// Adding empty string is not supported.
$this->expectException(TypeError::class);
$this->expectExceptionMessage("The value supplied was of type '{$type}'. An integer was expected.");
$filter->add_filter_value($value);
}
/**
* Data provider for add_filter_value tests with invalid types.
*
* @return array
*/
public function add_filter_value_invalid_types_provider(): array {
return [
'Null' => [null, 'NULL'],
'Empty string' => ['', 'string'],
'Filled string' => ['example', 'string'],
'Float 1.0' => [1.0, 'double'],
'Float 1.1' => [1.1, 'double'],
'bool' => [false, 'boolean'],
'array' => [[], 'array'],
'stdClass' => [(object) [], 'stdClass'],
// Note: The comparison value will be a fully-qualfied class name.
'Class' => [new filter('example'), filter::class],
];
}
}
@@ -0,0 +1,280 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for core_table\local\filter\numeric_comparison_filter.
*
* @package core_table
* @category test
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
declare(strict_types=1);
namespace core_table\local\filter;
use advanced_testcase;
use InvalidArgumentException;
use TypeError;
/**
* Unit tests for core_table\local\filter\numeric_comparison_filter.
*
* @package core_table
* @category test
* @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class numeric_comparison_filter_test extends advanced_testcase {
/**
* Ensure that the add_filter_value function works as expected with valid values.
*/
public function test_add_filter_value_valid(): void {
$filter = new numeric_comparison_filter('example');
// Initially an empty list.
$this->assertEmpty($filter->get_filter_values());
// Adding a value should return that value.
$filter->add_filter_value(json_encode((object) [
'direction' => '>',
'value' => 100,
]));
$this->assertEquals([
(object) [
'direction' => '>',
'value' => 100,
],
], $filter->get_filter_values());
// Adding a second value should add that value.
// The values should sorted.
$filter->add_filter_value(json_encode((object) [
'direction' => '<=',
'value' => 1000,
]));
$this->assertEquals([
(object) [
'direction' => '<=',
'value' => 1000,
],
(object) [
'direction' => '>',
'value' => 100,
],
], $filter->get_filter_values());
// Adding a duplicate value should not lead to that value being added again.
$filter->add_filter_value(json_encode((object) [
'direction' => '>',
'value' => 100,
]));
$this->assertEquals([
(object) [
'direction' => '<=',
'value' => 1000,
],
(object) [
'direction' => '>',
'value' => 100,
],
], $filter->get_filter_values());
}
/**
* Ensure that the add_filter_value function rejects invalid types.
*
* @dataProvider add_filter_value_invalid_types_provider
* @param mixed $values
* @param string $exceptiontype
* @param string $exceptionmessage
*/
public function test_add_filter_value_type_invalid($values, string $exceptiontype, string $exceptionmessage): void {
$filter = new numeric_comparison_filter('example');
// Adding empty string is not supported.
$this->expectException($exceptiontype);
$this->expectExceptionMessage($exceptionmessage);
call_user_func_array([$filter, 'add_filter_value'], $values);
}
/**
* Data provider for add_filter_value tests with invalid types.
*
* @return array
*/
public function add_filter_value_invalid_types_provider(): array {
return [
'Null' => [
[null],
TypeError::class,
"The value supplied was of type 'NULL'. A string representing a json-encoded value was expected.",
],
'Single value string' => [
[''],
InvalidArgumentException::class,
"A json-encoded object containing both a direction, and comparison value was expected.",
],
'Single value integer' => [
[42],
TypeError::class,
"The value supplied was of type 'integer'. A string representing a json-encoded value was expected.",
],
'Single value float' => [
[4.2],
TypeError::class,
"The value supplied was of type 'double'. A string representing a json-encoded value was expected.",
],
'Single value bool' => [
[false],
TypeError::class,
"The value supplied was of type 'boolean'. A string representing a json-encoded value was expected.",
],
'Single value array' => [
[[]],
TypeError::class,
"The value supplied was of type 'array'. A string representing a json-encoded value was expected.",
],
'Single value object' => [
[(object) []],
TypeError::class,
"The value supplied was of type 'stdClass'. A string representing a json-encoded value was expected.",
],
'Single value class' => [
[new filter('example')],
TypeError::class,
"The value supplied was of type '" . filter::class . "'. A string representing a json-encoded value was expected.",
],
'json-encoded single value null' => [
// Note a json-encoded null is the stringy 'null'.
[json_encode(null)],
InvalidArgumentException::class,
"A json-encoded object containing both a direction, and comparison value was expected.",
],
'json-encoded single value string' => [
[json_encode('')],
InvalidArgumentException::class,
"The value supplied was a json encoded 'string'. " .
"An object containing both a direction, and comparison value was expected.",
],
'json-encoded single value integer' => [
[json_encode(42)],
InvalidArgumentException::class,
"The value supplied was a json encoded 'string'. " .
"An object containing both a direction, and comparison value was expected.",
],
'json-encoded single value double' => [
[json_encode(4.2)],
InvalidArgumentException::class,
"The value supplied was a json encoded 'string'. " .
"An object containing both a direction, and comparison value was expected.",
],
'json-encoded single value bool' => [
[json_encode(false)],
InvalidArgumentException::class,
"The value supplied was a json encoded 'string'. " .
"An object containing both a direction, and comparison value was expected.",
],
'json-encoded single value array' => [
[json_encode([])],
InvalidArgumentException::class,
"The value supplied was a json encoded 'string'. " .
"An object containing both a direction, and comparison value was expected.",
],
'json-encoded empty object' => [
[json_encode((object) [])],
InvalidArgumentException::class,
"A 'direction' must be provided.",
],
'json-encoded single value class' => [
// A class will contain any public properties when json-encoded. It is treated in the same was a stdClass.
[json_encode(new filter('example'))],
InvalidArgumentException::class,
"A 'direction' must be provided.",
],
'Direction provided, value missing' => [
[json_encode([
'direction' => '>',
])],
InvalidArgumentException::class,
"A 'value' must be provided.",
],
'Direction invalid +' => [
[json_encode([
'direction' => '+',
'value' => 100,
])],
InvalidArgumentException::class,
"Invalid direction specified '+'."
],
'Direction invalid -' => [
[json_encode([
'direction' => '-',
'value' => 100,
])],
InvalidArgumentException::class,
"Invalid direction specified '-'."
],
'Value string' => [
[json_encode([
'direction' => '>',
'value' => "example",
])],
TypeError::class,
"The value supplied was of type 'string'. A numeric value was expected."
],
'Value bool' => [
[json_encode([
'direction' => '>',
'value' => false,
])],
TypeError::class,
"The value supplied was of type 'boolean'. A numeric value was expected."
],
'Value array' => [
[json_encode([
'direction' => '>',
'value' => [],
])],
TypeError::class,
"The value supplied was of type 'array'. A numeric value was expected."
],
'Value stdClass' => [
[json_encode([
'direction' => '>',
'value' => (object) [],
])],
TypeError::class,
"The value supplied was of type 'stdClass'. A numeric value was expected."
],
'Value class' => [
// A class will contain any public properties when json-encoded. It is treated in the same was a stdClass.
[json_encode([
'direction' => '>',
'value' => new filter('example'),
])],
TypeError::class,
"The value supplied was of type 'stdClass'. A numeric value was expected."
],
];
}
}
@@ -0,0 +1,109 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for core_table\local\filter\string_filter.
*
* @package core_table
* @category test
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
declare(strict_types=1);
namespace core_table\local\filter;
use advanced_testcase;
use TypeError;
/**
* Unit tests for core_table\local\filter\string_filter.
*
* @package core_table
* @category test
* @copyright 2020 Simey Lameze <simey@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class string_filter_test extends advanced_testcase {
/**
* Ensure that the add_filter_value function works as expected with valid values.
*/
public function test_add_filter_value_string(): void {
$filter = new string_filter('example');
// Initially an empty list.
$this->assertEmpty($filter->get_filter_values());
// Adding a value should return that value.
$filter->add_filter_value('apple');
$this->assertSame([
'apple',
], $filter->get_filter_values());
// Adding a second value should add that value.
// The values should sorted.
$filter->add_filter_value('pear');
$this->assertSame([
'apple',
'pear',
], $filter->get_filter_values());
// Adding a duplicate value should not lead to that value being added again.
$filter->add_filter_value('apple');
$this->assertSame([
'apple',
'pear',
], $filter->get_filter_values());
}
/**
* Ensure that the add_filter_value function rejects invalid types.
*
* @dataProvider add_filter_value_invalid_types_provider
* @param mixed $value
* @param string $type
*/
public function test_add_filter_value_type_invalid($value, string $type): void {
$filter = new string_filter('example');
// Adding empty string is not supported.
$this->expectException(TypeError::class);
$this->expectExceptionMessage("The value supplied was of type '{$type}'. A string was expected.");
$filter->add_filter_value($value);
}
/**
* Data provider for add_filter_value tests with invalid types.
*
* @return array
*/
public function add_filter_value_invalid_types_provider(): array {
return [
'Null' => [null, 'NULL'],
'1' => [1, 'integer'],
'2' => [2, 'integer'],
'Float 1.0' => [1.0, 'double'],
'Float 1.1' => [1.1, 'double'],
'bool' => [false, 'boolean'],
'array' => [[], 'array'],
'stdClass' => [(object) [], 'stdClass'],
// Note: The comparison value will be a fully-qualified class name.
'Class' => [new filter('example'), filter::class],
];
}
}