diff --git a/assets/js/lcp-beacon.js b/assets/js/lcp-beacon.js index eb74ebfee5..9150860ba3 100644 --- a/assets/js/lcp-beacon.js +++ b/assets/js/lcp-beacon.js @@ -255,7 +255,7 @@ class RocketLcpBeacon { _fillATFWithoutDuplications(elements) { elements.forEach(({ element, elementInfo }) => { - if ( this._isDuplicateImage(element) ) { + if ( this._isDuplicateImage(element) || !elementInfo ) { return; } diff --git a/assets/js/lcp-beacon.min.js b/assets/js/lcp-beacon.min.js index 9695b4792f..1eca46f9ff 100644 --- a/assets/js/lcp-beacon.min.js +++ b/assets/js/lcp-beacon.min.js @@ -1,2 +1,2 @@ -!function n(r,s,o){function c(t,e){if(!s[t]){if(!r[t]){var i="function"==typeof require&&require;if(!e&&i)return i(t,!0);if(a)return a(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}i=s[t]={exports:{}},r[t][0].call(i.exports,function(e){return c(r[t][1][e]||e)},i,i.exports,n,r,s,o)}return s[t].exports}for(var a="function"==typeof require&&require,e=0;e{this._handleInfiniteLoop()},1e4);try{var e=this._generateLcpCandidates(1/0);e&&(this._initWithFirstElementWithInfo(e),this._fillATFWithoutDuplications(e))}catch(e){this.errorCode="script_error",this._logMessage("Script Error: "+e)}this._saveFinalResultIntoDB()}else this._finalize()}async _isValidPreconditions(){return this._isNotValidScreensize()?(this._logMessage("Bailing out because screen size is not acceptable"),!1):!this._isPageCached()||!await this._isGeneratedBefore()||(this._logMessage("Bailing out because data is already available"),!1)}_isPageCached(){var e=document.documentElement.nextSibling&&document.documentElement.nextSibling.data?document.documentElement.nextSibling.data:"";return e&&e.includes("Debug: cached")}async _isGeneratedBefore(){var e=new FormData;return e.append("action","rocket_check_lcp"),e.append("rocket_lcp_nonce",this.config.nonce),e.append("url",this.config.url),e.append("is_mobile",this.config.is_mobile),(e=await fetch(this.config.ajax_url,{method:"POST",credentials:"same-origin",body:e}).then(e=>e.json())).success}_isNotValidScreensize(){var e=window.innerWidth||document.documentElement.clientWidth,t=window.innerHeight||document.documentElement.clientHeight,i=this.config.is_mobile&&(e>this.config.width_threshold||t>this.config.height_threshold),e=!this.config.is_mobile&&(e{if("img"===e.nodeName.toLowerCase()&&"picture"===e.parentElement.nodeName.toLowerCase())return null;let t;if("picture"===e.nodeName.toLowerCase()){var i=e.querySelector("img");if(!i)return null;t=i.getBoundingClientRect()}else t=e.getBoundingClientRect();return{element:e,rect:t}}).filter(e=>null!==e).filter(e=>0({item:e,area:this._getElementArea(e.rect),elementInfo:this._getElementInfo(e.element)})).sort((e,t)=>t.area-e.area).slice(0,e).map(e=>({element:e.item.element,elementInfo:e.elementInfo}))}_isIntersecting(e){return 0<=e.bottom&&0<=e.right&&e.top<=(window.innerHeight||document.documentElement.clientHeight)&&e.left<=(window.innerWidth||document.documentElement.clientWidth)}_getElementArea(e){return Math.min(e.width,(window.innerWidth||document.documentElement.clientWidth)-e.left)*Math.min(e.height,(window.innerHeight||document.documentElement.clientHeight)-e.top)}_getElementInfo(e){var t=e.nodeName.toLowerCase(),i={type:"",src:"",srcset:"",sizes:"",sources:[],bg_set:[],current_src:""};if("img"===t&&e.srcset)i.type="img-srcset",i.src=e.src,i.srcset=e.srcset,i.sizes=e.sizes,i.current_src=e.currentSrc;else if("img"===t)i.type="img",i.src=e.src,i.current_src=e.currentSrc;else if("video"===t){i.type="img";var n=e.querySelector("source");i.src=e.poster||(n?n.src:""),i.current_src=i.src}else if("svg"===t)(n=e.querySelector("image"))&&(i.type="img",i.src=n.getAttribute("href")||"",i.current_src=i.src);else if("picture"===t)i.type="picture",n=e.querySelector("img"),i.src=n?n.src:"",i.sources=Array.from(e.querySelectorAll("source")).map(e=>({srcset:e.srcset||"",media:e.media||"",type:e.type||"",sizes:e.sizes||""}));else{if(0===(t=[window.getComputedStyle(e,null).getPropertyValue("background-image"),getComputedStyle(e,":after").getPropertyValue("background-image"),getComputedStyle(e,":before").getPropertyValue("background-image")].filter(e=>"none"!==e)).length)return null;if(n=t[0],i.type="bg-img",n.includes("image-set(")&&(i.type="bg-img-set"),!n||""===n||n.includes("data:image"))return null;e=[...n.matchAll(/url\(\s*?['"]?\s*?(.+?)\s*?["']?\s*?\)/gi)],i.bg_set=e.map(e=>e[1]?{src:e[1].trim()+(e[2]?" "+e[2].trim():"")}:{}),i.bg_set.every(e=>""===e.src)&&(i.bg_set=e.map(e=>e[1]?{src:e[1].trim()}:{})),0null!==e.elementInfo))?this.performanceImages=[{...e.elementInfo,label:"lcp"}]:(this._logMessage("No LCP candidate found."),this.performanceImages=[])}_fillATFWithoutDuplications(e){e.forEach(e=>{var{element:e,elementInfo:t}=e;this._isDuplicateImage(e)||this.performanceImages.push({...t,label:"above-the-fold"})})}_isDuplicateImage(e){const t=this._getElementInfo(e);var i;return null!==t&&(e="img"===t.type||"img-srcset"===t.type||"video"===t.type,i="bg-img"===t.type||"bg-img-set"===t.type||"picture"===t.type,e||i)&&this.performanceImages.some(e=>e.src===t.src)}_getFinalStatus(){return""!==this.errorCode?this.errorCode:10<=(new Date-this.scriptTimer)/1e3?"timeout":"success"}_saveFinalResultIntoDB(){var e=new FormData;e.append("action","rocket_lcp"),e.append("rocket_lcp_nonce",this.config.nonce),e.append("url",this.config.url),e.append("is_mobile",this.config.is_mobile),e.append("images",JSON.stringify(this.performanceImages)),e.append("status",this._getFinalStatus()),fetch(this.config.ajax_url,{method:"POST",credentials:"same-origin",body:e,headers:{"wpr-saas-no-intercept":!0}}).then(e=>e.json()).then(e=>{this._logMessage(e)}).catch(e=>{this._logMessage(e)}).finally(()=>{this._finalize()})}_handleInfiniteLoop(){this._saveFinalResultIntoDB()}_finalize(){document.querySelector('[data-name="wpr-lcp-beacon"]').setAttribute("beacon-completed","true"),clearTimeout(this.infiniteLoopId)}_logMessage(e){this.config.debug&&console.log(e)}static run(){if(window.rocket_lcp_data){const e=new n(window.rocket_lcp_data);"loading"!==document.readyState?setTimeout(()=>{e.init()},window.rocket_lcp_data.delay):document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>{e.init()},window.rocket_lcp_data.delay)})}}}).run()},{}]},{},[1]); +!function n(r,s,o){function c(t,e){if(!s[t]){if(!r[t]){var i="function"==typeof require&&require;if(!e&&i)return i(t,!0);if(a)return a(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}i=s[t]={exports:{}},r[t][0].call(i.exports,function(e){return c(r[t][1][e]||e)},i,i.exports,n,r,s,o)}return s[t].exports}for(var a="function"==typeof require&&require,e=0;e{this._handleInfiniteLoop()},1e4);try{var e=this._generateLcpCandidates(1/0);e&&(this._initWithFirstElementWithInfo(e),this._fillATFWithoutDuplications(e))}catch(e){this.errorCode="script_error",this._logMessage("Script Error: "+e)}this._saveFinalResultIntoDB()}else this._finalize()}async _isValidPreconditions(){return this._isNotValidScreensize()?(this._logMessage("Bailing out because screen size is not acceptable"),!1):!this._isPageCached()||!await this._isGeneratedBefore()||(this._logMessage("Bailing out because data is already available"),!1)}_isPageCached(){var e=document.documentElement.nextSibling&&document.documentElement.nextSibling.data?document.documentElement.nextSibling.data:"";return e&&e.includes("Debug: cached")}async _isGeneratedBefore(){var e=new FormData;return e.append("action","rocket_check_lcp"),e.append("rocket_lcp_nonce",this.config.nonce),e.append("url",this.config.url),e.append("is_mobile",this.config.is_mobile),(e=await fetch(this.config.ajax_url,{method:"POST",credentials:"same-origin",body:e}).then(e=>e.json())).success}_isNotValidScreensize(){var e=window.innerWidth||document.documentElement.clientWidth,t=window.innerHeight||document.documentElement.clientHeight,i=this.config.is_mobile&&(e>this.config.width_threshold||t>this.config.height_threshold),e=!this.config.is_mobile&&(e{if("img"===e.nodeName.toLowerCase()&&"picture"===e.parentElement.nodeName.toLowerCase())return null;let t;if("picture"===e.nodeName.toLowerCase()){var i=e.querySelector("img");if(!i)return null;t=i.getBoundingClientRect()}else t=e.getBoundingClientRect();return{element:e,rect:t}}).filter(e=>null!==e).filter(e=>0({item:e,area:this._getElementArea(e.rect),elementInfo:this._getElementInfo(e.element)})).sort((e,t)=>t.area-e.area).slice(0,e).map(e=>({element:e.item.element,elementInfo:e.elementInfo}))}_isIntersecting(e){return 0<=e.bottom&&0<=e.right&&e.top<=(window.innerHeight||document.documentElement.clientHeight)&&e.left<=(window.innerWidth||document.documentElement.clientWidth)}_getElementArea(e){return Math.min(e.width,(window.innerWidth||document.documentElement.clientWidth)-e.left)*Math.min(e.height,(window.innerHeight||document.documentElement.clientHeight)-e.top)}_getElementInfo(e){var t=e.nodeName.toLowerCase(),i={type:"",src:"",srcset:"",sizes:"",sources:[],bg_set:[],current_src:""};if("img"===t&&e.srcset)i.type="img-srcset",i.src=e.src,i.srcset=e.srcset,i.sizes=e.sizes,i.current_src=e.currentSrc;else if("img"===t)i.type="img",i.src=e.src,i.current_src=e.currentSrc;else if("video"===t){i.type="img";var n=e.querySelector("source");i.src=e.poster||(n?n.src:""),i.current_src=i.src}else if("svg"===t)(n=e.querySelector("image"))&&(i.type="img",i.src=n.getAttribute("href")||"",i.current_src=i.src);else if("picture"===t)i.type="picture",n=e.querySelector("img"),i.src=n?n.src:"",i.sources=Array.from(e.querySelectorAll("source")).map(e=>({srcset:e.srcset||"",media:e.media||"",type:e.type||"",sizes:e.sizes||""}));else{if(0===(t=[window.getComputedStyle(e,null).getPropertyValue("background-image"),getComputedStyle(e,":after").getPropertyValue("background-image"),getComputedStyle(e,":before").getPropertyValue("background-image")].filter(e=>"none"!==e)).length)return null;if(n=t[0],i.type="bg-img",n.includes("image-set(")&&(i.type="bg-img-set"),!n||""===n||n.includes("data:image"))return null;e=[...n.matchAll(/url\(\s*?['"]?\s*?(.+?)\s*?["']?\s*?\)/gi)],i.bg_set=e.map(e=>e[1]?{src:e[1].trim()+(e[2]?" "+e[2].trim():"")}:{}),i.bg_set.every(e=>""===e.src)&&(i.bg_set=e.map(e=>e[1]?{src:e[1].trim()}:{})),0null!==e.elementInfo))?this.performanceImages=[{...e.elementInfo,label:"lcp"}]:(this._logMessage("No LCP candidate found."),this.performanceImages=[])}_fillATFWithoutDuplications(e){e.forEach(e=>{var{element:e,elementInfo:t}=e;!this._isDuplicateImage(e)&&t&&this.performanceImages.push({...t,label:"above-the-fold"})})}_isDuplicateImage(e){const t=this._getElementInfo(e);var i;return null!==t&&(e="img"===t.type||"img-srcset"===t.type||"video"===t.type,i="bg-img"===t.type||"bg-img-set"===t.type||"picture"===t.type,e||i)&&this.performanceImages.some(e=>e.src===t.src)}_getFinalStatus(){return""!==this.errorCode?this.errorCode:10<=(new Date-this.scriptTimer)/1e3?"timeout":"success"}_saveFinalResultIntoDB(){var e=new FormData;e.append("action","rocket_lcp"),e.append("rocket_lcp_nonce",this.config.nonce),e.append("url",this.config.url),e.append("is_mobile",this.config.is_mobile),e.append("images",JSON.stringify(this.performanceImages)),e.append("status",this._getFinalStatus()),fetch(this.config.ajax_url,{method:"POST",credentials:"same-origin",body:e,headers:{"wpr-saas-no-intercept":!0}}).then(e=>e.json()).then(e=>{this._logMessage(e)}).catch(e=>{this._logMessage(e)}).finally(()=>{this._finalize()})}_handleInfiniteLoop(){this._saveFinalResultIntoDB()}_finalize(){document.querySelector('[data-name="wpr-lcp-beacon"]').setAttribute("beacon-completed","true"),clearTimeout(this.infiniteLoopId)}_logMessage(e){this.config.debug&&console.log(e)}static run(){if(window.rocket_lcp_data){const e=new n(window.rocket_lcp_data);"loading"!==document.readyState?setTimeout(()=>{e.init()},window.rocket_lcp_data.delay):document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>{e.init()},window.rocket_lcp_data.delay)})}}}).run()},{}]},{},[1]); //# sourceMappingURL=lcp-beacon.min.js.map diff --git a/assets/js/lcp-beacon.min.js.map b/assets/js/lcp-beacon.min.js.map index 4db70f4121..3db9f48fc2 100644 --- a/assets/js/lcp-beacon.min.js.map +++ b/assets/js/lcp-beacon.min.js.map @@ -1 +1 @@ -{"version":3,"names":[],"mappings":"","sources":["lcp-beacon.min.js"],"sourcesContent":["!function n(r,s,o){function c(t,e){if(!s[t]){if(!r[t]){var i=\"function\"==typeof require&&require;if(!e&&i)return i(t,!0);if(a)return a(t,!0);throw(e=new Error(\"Cannot find module '\"+t+\"'\")).code=\"MODULE_NOT_FOUND\",e}i=s[t]={exports:{}},r[t][0].call(i.exports,function(e){return c(r[t][1][e]||e)},i,i.exports,n,r,s,o)}return s[t].exports}for(var a=\"function\"==typeof require&&require,e=0;e{this._handleInfiniteLoop()},1e4);try{var e=this._generateLcpCandidates(1/0);e&&(this._initWithFirstElementWithInfo(e),this._fillATFWithoutDuplications(e))}catch(e){this.errorCode=\"script_error\",this._logMessage(\"Script Error: \"+e)}this._saveFinalResultIntoDB()}else this._finalize()}async _isValidPreconditions(){return this._isNotValidScreensize()?(this._logMessage(\"Bailing out because screen size is not acceptable\"),!1):!this._isPageCached()||!await this._isGeneratedBefore()||(this._logMessage(\"Bailing out because data is already available\"),!1)}_isPageCached(){var e=document.documentElement.nextSibling&&document.documentElement.nextSibling.data?document.documentElement.nextSibling.data:\"\";return e&&e.includes(\"Debug: cached\")}async _isGeneratedBefore(){var e=new FormData;return e.append(\"action\",\"rocket_check_lcp\"),e.append(\"rocket_lcp_nonce\",this.config.nonce),e.append(\"url\",this.config.url),e.append(\"is_mobile\",this.config.is_mobile),(e=await fetch(this.config.ajax_url,{method:\"POST\",credentials:\"same-origin\",body:e}).then(e=>e.json())).success}_isNotValidScreensize(){var e=window.innerWidth||document.documentElement.clientWidth,t=window.innerHeight||document.documentElement.clientHeight,i=this.config.is_mobile&&(e>this.config.width_threshold||t>this.config.height_threshold),e=!this.config.is_mobile&&(e{if(\"img\"===e.nodeName.toLowerCase()&&\"picture\"===e.parentElement.nodeName.toLowerCase())return null;let t;if(\"picture\"===e.nodeName.toLowerCase()){var i=e.querySelector(\"img\");if(!i)return null;t=i.getBoundingClientRect()}else t=e.getBoundingClientRect();return{element:e,rect:t}}).filter(e=>null!==e).filter(e=>0({item:e,area:this._getElementArea(e.rect),elementInfo:this._getElementInfo(e.element)})).sort((e,t)=>t.area-e.area).slice(0,e).map(e=>({element:e.item.element,elementInfo:e.elementInfo}))}_isIntersecting(e){return 0<=e.bottom&&0<=e.right&&e.top<=(window.innerHeight||document.documentElement.clientHeight)&&e.left<=(window.innerWidth||document.documentElement.clientWidth)}_getElementArea(e){return Math.min(e.width,(window.innerWidth||document.documentElement.clientWidth)-e.left)*Math.min(e.height,(window.innerHeight||document.documentElement.clientHeight)-e.top)}_getElementInfo(e){var t=e.nodeName.toLowerCase(),i={type:\"\",src:\"\",srcset:\"\",sizes:\"\",sources:[],bg_set:[],current_src:\"\"};if(\"img\"===t&&e.srcset)i.type=\"img-srcset\",i.src=e.src,i.srcset=e.srcset,i.sizes=e.sizes,i.current_src=e.currentSrc;else if(\"img\"===t)i.type=\"img\",i.src=e.src,i.current_src=e.currentSrc;else if(\"video\"===t){i.type=\"img\";var n=e.querySelector(\"source\");i.src=e.poster||(n?n.src:\"\"),i.current_src=i.src}else if(\"svg\"===t)(n=e.querySelector(\"image\"))&&(i.type=\"img\",i.src=n.getAttribute(\"href\")||\"\",i.current_src=i.src);else if(\"picture\"===t)i.type=\"picture\",n=e.querySelector(\"img\"),i.src=n?n.src:\"\",i.sources=Array.from(e.querySelectorAll(\"source\")).map(e=>({srcset:e.srcset||\"\",media:e.media||\"\",type:e.type||\"\",sizes:e.sizes||\"\"}));else{if(0===(t=[window.getComputedStyle(e,null).getPropertyValue(\"background-image\"),getComputedStyle(e,\":after\").getPropertyValue(\"background-image\"),getComputedStyle(e,\":before\").getPropertyValue(\"background-image\")].filter(e=>\"none\"!==e)).length)return null;if(n=t[0],i.type=\"bg-img\",n.includes(\"image-set(\")&&(i.type=\"bg-img-set\"),!n||\"\"===n||n.includes(\"data:image\"))return null;e=[...n.matchAll(/url\\(\\s*?['\"]?\\s*?(.+?)\\s*?[\"']?\\s*?\\)/gi)],i.bg_set=e.map(e=>e[1]?{src:e[1].trim()+(e[2]?\" \"+e[2].trim():\"\")}:{}),i.bg_set.every(e=>\"\"===e.src)&&(i.bg_set=e.map(e=>e[1]?{src:e[1].trim()}:{})),0null!==e.elementInfo))?this.performanceImages=[{...e.elementInfo,label:\"lcp\"}]:(this._logMessage(\"No LCP candidate found.\"),this.performanceImages=[])}_fillATFWithoutDuplications(e){e.forEach(e=>{var{element:e,elementInfo:t}=e;this._isDuplicateImage(e)||this.performanceImages.push({...t,label:\"above-the-fold\"})})}_isDuplicateImage(e){const t=this._getElementInfo(e);var i;return null!==t&&(e=\"img\"===t.type||\"img-srcset\"===t.type||\"video\"===t.type,i=\"bg-img\"===t.type||\"bg-img-set\"===t.type||\"picture\"===t.type,e||i)&&this.performanceImages.some(e=>e.src===t.src)}_getFinalStatus(){return\"\"!==this.errorCode?this.errorCode:10<=(new Date-this.scriptTimer)/1e3?\"timeout\":\"success\"}_saveFinalResultIntoDB(){var e=new FormData;e.append(\"action\",\"rocket_lcp\"),e.append(\"rocket_lcp_nonce\",this.config.nonce),e.append(\"url\",this.config.url),e.append(\"is_mobile\",this.config.is_mobile),e.append(\"images\",JSON.stringify(this.performanceImages)),e.append(\"status\",this._getFinalStatus()),fetch(this.config.ajax_url,{method:\"POST\",credentials:\"same-origin\",body:e,headers:{\"wpr-saas-no-intercept\":!0}}).then(e=>e.json()).then(e=>{this._logMessage(e)}).catch(e=>{this._logMessage(e)}).finally(()=>{this._finalize()})}_handleInfiniteLoop(){this._saveFinalResultIntoDB()}_finalize(){document.querySelector('[data-name=\"wpr-lcp-beacon\"]').setAttribute(\"beacon-completed\",\"true\"),clearTimeout(this.infiniteLoopId)}_logMessage(e){this.config.debug&&console.log(e)}static run(){if(window.rocket_lcp_data){const e=new n(window.rocket_lcp_data);\"loading\"!==document.readyState?setTimeout(()=>{e.init()},window.rocket_lcp_data.delay):document.addEventListener(\"DOMContentLoaded\",()=>{setTimeout(()=>{e.init()},window.rocket_lcp_data.delay)})}}}).run()},{}]},{},[1]);"],"file":"lcp-beacon.min.js"} \ No newline at end of file +{"version":3,"names":[],"mappings":"","sources":["lcp-beacon.min.js"],"sourcesContent":["!function n(r,s,o){function c(t,e){if(!s[t]){if(!r[t]){var i=\"function\"==typeof require&&require;if(!e&&i)return i(t,!0);if(a)return a(t,!0);throw(e=new Error(\"Cannot find module '\"+t+\"'\")).code=\"MODULE_NOT_FOUND\",e}i=s[t]={exports:{}},r[t][0].call(i.exports,function(e){return c(r[t][1][e]||e)},i,i.exports,n,r,s,o)}return s[t].exports}for(var a=\"function\"==typeof require&&require,e=0;e{this._handleInfiniteLoop()},1e4);try{var e=this._generateLcpCandidates(1/0);e&&(this._initWithFirstElementWithInfo(e),this._fillATFWithoutDuplications(e))}catch(e){this.errorCode=\"script_error\",this._logMessage(\"Script Error: \"+e)}this._saveFinalResultIntoDB()}else this._finalize()}async _isValidPreconditions(){return this._isNotValidScreensize()?(this._logMessage(\"Bailing out because screen size is not acceptable\"),!1):!this._isPageCached()||!await this._isGeneratedBefore()||(this._logMessage(\"Bailing out because data is already available\"),!1)}_isPageCached(){var e=document.documentElement.nextSibling&&document.documentElement.nextSibling.data?document.documentElement.nextSibling.data:\"\";return e&&e.includes(\"Debug: cached\")}async _isGeneratedBefore(){var e=new FormData;return e.append(\"action\",\"rocket_check_lcp\"),e.append(\"rocket_lcp_nonce\",this.config.nonce),e.append(\"url\",this.config.url),e.append(\"is_mobile\",this.config.is_mobile),(e=await fetch(this.config.ajax_url,{method:\"POST\",credentials:\"same-origin\",body:e}).then(e=>e.json())).success}_isNotValidScreensize(){var e=window.innerWidth||document.documentElement.clientWidth,t=window.innerHeight||document.documentElement.clientHeight,i=this.config.is_mobile&&(e>this.config.width_threshold||t>this.config.height_threshold),e=!this.config.is_mobile&&(e{if(\"img\"===e.nodeName.toLowerCase()&&\"picture\"===e.parentElement.nodeName.toLowerCase())return null;let t;if(\"picture\"===e.nodeName.toLowerCase()){var i=e.querySelector(\"img\");if(!i)return null;t=i.getBoundingClientRect()}else t=e.getBoundingClientRect();return{element:e,rect:t}}).filter(e=>null!==e).filter(e=>0({item:e,area:this._getElementArea(e.rect),elementInfo:this._getElementInfo(e.element)})).sort((e,t)=>t.area-e.area).slice(0,e).map(e=>({element:e.item.element,elementInfo:e.elementInfo}))}_isIntersecting(e){return 0<=e.bottom&&0<=e.right&&e.top<=(window.innerHeight||document.documentElement.clientHeight)&&e.left<=(window.innerWidth||document.documentElement.clientWidth)}_getElementArea(e){return Math.min(e.width,(window.innerWidth||document.documentElement.clientWidth)-e.left)*Math.min(e.height,(window.innerHeight||document.documentElement.clientHeight)-e.top)}_getElementInfo(e){var t=e.nodeName.toLowerCase(),i={type:\"\",src:\"\",srcset:\"\",sizes:\"\",sources:[],bg_set:[],current_src:\"\"};if(\"img\"===t&&e.srcset)i.type=\"img-srcset\",i.src=e.src,i.srcset=e.srcset,i.sizes=e.sizes,i.current_src=e.currentSrc;else if(\"img\"===t)i.type=\"img\",i.src=e.src,i.current_src=e.currentSrc;else if(\"video\"===t){i.type=\"img\";var n=e.querySelector(\"source\");i.src=e.poster||(n?n.src:\"\"),i.current_src=i.src}else if(\"svg\"===t)(n=e.querySelector(\"image\"))&&(i.type=\"img\",i.src=n.getAttribute(\"href\")||\"\",i.current_src=i.src);else if(\"picture\"===t)i.type=\"picture\",n=e.querySelector(\"img\"),i.src=n?n.src:\"\",i.sources=Array.from(e.querySelectorAll(\"source\")).map(e=>({srcset:e.srcset||\"\",media:e.media||\"\",type:e.type||\"\",sizes:e.sizes||\"\"}));else{if(0===(t=[window.getComputedStyle(e,null).getPropertyValue(\"background-image\"),getComputedStyle(e,\":after\").getPropertyValue(\"background-image\"),getComputedStyle(e,\":before\").getPropertyValue(\"background-image\")].filter(e=>\"none\"!==e)).length)return null;if(n=t[0],i.type=\"bg-img\",n.includes(\"image-set(\")&&(i.type=\"bg-img-set\"),!n||\"\"===n||n.includes(\"data:image\"))return null;e=[...n.matchAll(/url\\(\\s*?['\"]?\\s*?(.+?)\\s*?[\"']?\\s*?\\)/gi)],i.bg_set=e.map(e=>e[1]?{src:e[1].trim()+(e[2]?\" \"+e[2].trim():\"\")}:{}),i.bg_set.every(e=>\"\"===e.src)&&(i.bg_set=e.map(e=>e[1]?{src:e[1].trim()}:{})),0null!==e.elementInfo))?this.performanceImages=[{...e.elementInfo,label:\"lcp\"}]:(this._logMessage(\"No LCP candidate found.\"),this.performanceImages=[])}_fillATFWithoutDuplications(e){e.forEach(e=>{var{element:e,elementInfo:t}=e;!this._isDuplicateImage(e)&&t&&this.performanceImages.push({...t,label:\"above-the-fold\"})})}_isDuplicateImage(e){const t=this._getElementInfo(e);var i;return null!==t&&(e=\"img\"===t.type||\"img-srcset\"===t.type||\"video\"===t.type,i=\"bg-img\"===t.type||\"bg-img-set\"===t.type||\"picture\"===t.type,e||i)&&this.performanceImages.some(e=>e.src===t.src)}_getFinalStatus(){return\"\"!==this.errorCode?this.errorCode:10<=(new Date-this.scriptTimer)/1e3?\"timeout\":\"success\"}_saveFinalResultIntoDB(){var e=new FormData;e.append(\"action\",\"rocket_lcp\"),e.append(\"rocket_lcp_nonce\",this.config.nonce),e.append(\"url\",this.config.url),e.append(\"is_mobile\",this.config.is_mobile),e.append(\"images\",JSON.stringify(this.performanceImages)),e.append(\"status\",this._getFinalStatus()),fetch(this.config.ajax_url,{method:\"POST\",credentials:\"same-origin\",body:e,headers:{\"wpr-saas-no-intercept\":!0}}).then(e=>e.json()).then(e=>{this._logMessage(e)}).catch(e=>{this._logMessage(e)}).finally(()=>{this._finalize()})}_handleInfiniteLoop(){this._saveFinalResultIntoDB()}_finalize(){document.querySelector('[data-name=\"wpr-lcp-beacon\"]').setAttribute(\"beacon-completed\",\"true\"),clearTimeout(this.infiniteLoopId)}_logMessage(e){this.config.debug&&console.log(e)}static run(){if(window.rocket_lcp_data){const e=new n(window.rocket_lcp_data);\"loading\"!==document.readyState?setTimeout(()=>{e.init()},window.rocket_lcp_data.delay):document.addEventListener(\"DOMContentLoaded\",()=>{setTimeout(()=>{e.init()},window.rocket_lcp_data.delay)})}}}).run()},{}]},{},[1]);"],"file":"lcp-beacon.min.js"} \ No newline at end of file diff --git a/composer.json b/composer.json index a8df0ada84..ae50c7ae2b 100644 --- a/composer.json +++ b/composer.json @@ -54,9 +54,10 @@ "mikey179/vfsstream": "1.6.11", "mnsami/composer-custom-directory-installer": "^2.0", "mobiledetect/mobiledetectlib": "^2.8", + "php-stubs/wordpress-tests-stubs": "^6.5", "phpcompatibility/phpcompatibility-wp": "^2.0", "phpstan/extension-installer": "^1.3", - "phpstan/phpstan": "^1.8", + "phpstan/phpstan-phpunit": "^1.4", "phpunit/phpunit": "^7.5 || ^8 || ^9", "psr/container": "1.1.1", "roave/security-advisories": "dev-master", @@ -74,6 +75,7 @@ "wpackagist-plugin/pdf-embedder": "4.6.*", "wpackagist-plugin/simple-custom-css": "^4.0.3", "wpackagist-plugin/spinupwp": "^1.1", + "wpackagist-plugin/the-events-calendar": "6.5.0.1", "wpackagist-plugin/woocommerce": "^8", "wpackagist-plugin/wp-smushit": "^3" }, diff --git a/inc/Engine/Admin/Settings/Page.php b/inc/Engine/Admin/Settings/Page.php index a8dd03a273..d0c85d6577 100644 --- a/inc/Engine/Admin/Settings/Page.php +++ b/inc/Engine/Admin/Settings/Page.php @@ -284,9 +284,17 @@ public function customer_data() { $data['license_type'] = rocket_get_license_type( $user ); - $data['license_class'] = time() < $user->licence_expiration ? 'wpr-isValid' : 'wpr-isInvalid'; - $data['license_expiration'] = date_i18n( get_option( 'date_format' ), (int) $user->licence_expiration ); - $data['is_from_one_dot_com'] = (bool) $user->{'has_one-com_account'}; + if ( ! empty( $user->licence_expiration ) ) { + $data['license_class'] = time() < $user->licence_expiration ? 'wpr-isValid' : 'wpr-isInvalid'; + } + + if ( ! empty( $user->licence_expiration ) ) { + $data['license_expiration'] = date_i18n( get_option( 'date_format' ), (int) $user->licence_expiration ); + } + + if ( isset( $user->{'has_one-com_account'} ) ) { + $data['is_from_one_dot_com'] = (bool) $user->{'has_one-com_account'}; + } return $data; } diff --git a/inc/Engine/Admin/Settings/Subscriber.php b/inc/Engine/Admin/Settings/Subscriber.php index 0f6206b41a..0b649596e5 100644 --- a/inc/Engine/Admin/Settings/Subscriber.php +++ b/inc/Engine/Admin/Settings/Subscriber.php @@ -144,6 +144,8 @@ public function refresh_customer_data() { } delete_transient( 'wp_rocket_customer_data' ); + delete_transient( 'wpr_user_information_timeout_active' ); + delete_transient( 'wpr_user_information_timeout' ); return wp_send_json_success( $this->page->customer_data() ); } diff --git a/inc/Engine/Common/JobManager/APIHandler/AbstractSafeAPIClient.php b/inc/Engine/Common/JobManager/APIHandler/AbstractSafeAPIClient.php new file mode 100644 index 0000000000..2e4d0acb48 --- /dev/null +++ b/inc/Engine/Common/JobManager/APIHandler/AbstractSafeAPIClient.php @@ -0,0 +1,153 @@ +send_request( 'GET', $params, $safe ); + } + + /** + * Send a POST request. + * + * @param array $params The request parameters. + * @param bool $safe Send safe request WP functions or not, default to not. + * + * @return mixed The response from the API. + */ + public function send_post_request( $params = [], $safe = false ) { + return $this->send_request( 'POST', $params, $safe ); + } + + /** + * Send a request to the API. + * + * @param string $method The HTTP method (GET or POST). + * @param array $params The request parameters. + * @param bool $safe Send safe request WP functions or not, default to not. + * @return mixed The response from the API, or WP_Error if a timeout is active. + */ + private function send_request( $method, $params = [], $safe = false ) { + $api_url = $this->get_api_url(); + + $transient_key = $this->get_transient_key(); + if ( get_transient( $transient_key . '_timeout_active' ) ) { + return new WP_Error( 429, __( 'Too many requests.', 'rocket' ) ); + } + // Get previous_expiration early to avoid multiple parallel requests increasing the expiration multiple times. + $previous_expiration = (int) get_transient( $transient_key . '_timeout' ); + + $params['method'] = strtoupper( $method ); + + $response = $this->send_remote_request( $api_url, $method, $params, $safe ); + + if ( is_wp_error( $response ) ) { + $this->set_timeout_transients( $previous_expiration ); + return $response; + } + + $body = wp_remote_retrieve_body( $response ); + if ( empty( $body ) || ( is_array( $response ) && ! empty( $response['response']['code'] ) && 200 !== $response['response']['code'] ) ) { + $this->set_timeout_transients( $previous_expiration ); + return new WP_Error( 500, __( 'Not valid response.', 'rocket' ) ); + } + + $this->delete_timeout_transients(); + + return $response; + } + + /** + * Set the timeout transients. + * + * @param string $previous_expiration The previous value of _timeout_active transient. + */ + private function set_timeout_transients( $previous_expiration ) { + $transient_key = $this->get_transient_key(); + + $expiration = ( 0 === $previous_expiration ) + ? 300 + : ( 2 * $previous_expiration <= DAY_IN_SECONDS + ? 2 * $previous_expiration + : DAY_IN_SECONDS + ); + + set_transient( $transient_key . '_timeout', $expiration, WEEK_IN_SECONDS ); + set_transient( $transient_key . '_timeout_active', true, $expiration ); + } + + /** + * Delete the timeout transients. + * + * This method deletes the timeout transients for the API requests. It uses the transient key obtained from the `get_transient_key` method. + * The transients deleted are: + * - `{transient_key}_timeout_active`: This transient indicates if a timeout is currently active. + * - `{transient_key}_timeout`: This transient stores the timeout duration. + * + * @return void + */ + private function delete_timeout_transients() { + $transient_key = $this->get_transient_key(); + delete_transient( $transient_key . '_timeout_active' ); + delete_transient( $transient_key . '_timeout' ); + } + + /** + * Decide which WP core function will be used to send the request based on the params. + * + * @param string $api_url API Url. + * @param string $method Request method (GET or POST). + * @param array $params Parameters being sent with the request. + * @param bool $safe Send safe request WP functions or not, default to not. + * @return array|WP_Error + */ + private function send_remote_request( $api_url, $method, $params, $safe ) { + if ( ! $safe ) { + return wp_remote_request( $api_url, $params ); + } + + unset( $params['method'] ); + + switch ( $method ) { + case 'GET': + return wp_safe_remote_get( $api_url, $params ); + case 'POST': + return wp_safe_remote_post( $api_url, $params ); + } + + return new WP_Error( 400, __( 'Not valid request type.', 'rocket' ) ); + } +} diff --git a/inc/Engine/Common/JobManager/ServiceProvider.php b/inc/Engine/Common/JobManager/ServiceProvider.php index e12ff10ba9..d404ef36ff 100644 --- a/inc/Engine/Common/JobManager/ServiceProvider.php +++ b/inc/Engine/Common/JobManager/ServiceProvider.php @@ -4,16 +4,12 @@ namespace WP_Rocket\Engine\Common\JobManager; use WP_Rocket\Dependencies\League\Container\ServiceProvider\AbstractServiceProvider; -use WP_Rocket\Engine\Common\JobManager\Strategy\Context\RetryContext; -use WP_Rocket\Engine\Common\JobManager\Strategy\Factory\StrategyFactory; -use WP_Rocket\Engine\Common\JobManager\Strategy\Strategies\DefaultProcess; -use WP_Rocket\Engine\Common\JobManager\Strategy\Strategies\JobSetFail; -use WP_Rocket\Engine\Common\JobManager\Strategy\Strategies\ResetRetryProcess; use WP_Rocket\Engine\Common\Clock\WPRClock; -use WP_Rocket\Engine\Common\JobManager\Queue\Queue; use WP_Rocket\Engine\Common\JobManager\APIHandler\APIClient; use WP_Rocket\Engine\Common\JobManager\Cron\Subscriber as CronSubscriber; - +use WP_Rocket\Engine\Common\JobManager\Queue\Queue; +use WP_Rocket\Engine\Common\JobManager\Strategy\Context\RetryContext; +use WP_Rocket\Engine\Common\JobManager\Strategy\Factory\StrategyFactory; class ServiceProvider extends AbstractServiceProvider { /** diff --git a/inc/Engine/License/API/PricingClient.php b/inc/Engine/License/API/PricingClient.php index 045482293d..6d29d47023 100644 --- a/inc/Engine/License/API/PricingClient.php +++ b/inc/Engine/License/API/PricingClient.php @@ -2,9 +2,33 @@ namespace WP_Rocket\Engine\License\API; -class PricingClient { +use WP_Rocket\Engine\Common\JobManager\APIHandler\AbstractSafeAPIClient; + +class PricingClient extends AbstractSafeAPIClient { const PRICING_ENDPOINT = 'https://wp-rocket.me/stat/1.0/wp-rocket/pricing-2023.php'; + /** + * Get the transient key for plugin updates. + * + * This method returns the transient key used for caching plugin updates. + * + * @return string The transient key for plugin updates. + */ + protected function get_transient_key() { + return 'wp_rocket_pricing'; + } + + /** + * Get the API URL for plugin updates. + * + * This method returns the API URL used for fetching plugin updates. + * + * @return string The API URL for plugin updates. + */ + protected function get_api_url() { + return self::PRICING_ENDPOINT; + } + /** * Gets pricing data from cache if it exists, else gets it from the pricing endpoint * @@ -40,51 +64,12 @@ public function get_pricing_data() { * @return bool|object */ private function get_raw_pricing_data() { - if ( (bool) get_transient( 'wp_rocket_pricing_timeout_active' ) ) { - return false; - } - - $response = wp_safe_remote_get( - self::PRICING_ENDPOINT - ); - - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { - $this->set_timeout_transients(); - - return false; - } - - $body = wp_remote_retrieve_body( $response ); - - if ( empty( $body ) ) { - $this->set_timeout_transients(); + $response = $this->send_get_request( [], true ); + if ( is_wp_error( $response ) || ( is_array( $response ) && 200 !== $response['response']['code'] ) ) { return false; } - delete_transient( 'wp_rocket_pricing_timeout' ); - delete_transient( 'wp_rocket_pricing_timeout_active' ); - - return json_decode( $body ); - } - - /** - * Set pricing timeout transients. - * - * @since 3.8.4 - * - * @return void - */ - private function set_timeout_transients() { - $timeout = (int) get_transient( 'wp_rocket_pricing_timeout' ); - $timeout = ( 0 === $timeout ) - ? 300 - : ( 2 * $timeout <= DAY_IN_SECONDS - ? 2 * $timeout : - DAY_IN_SECONDS - ); - - set_transient( 'wp_rocket_pricing_timeout', $timeout, WEEK_IN_SECONDS ); - set_transient( 'wp_rocket_pricing_timeout_active', true, $timeout ); + return json_decode( wp_remote_retrieve_body( $response ) ); } } diff --git a/inc/Engine/License/API/UserClient.php b/inc/Engine/License/API/UserClient.php index 00d6f15faa..62ab12f0f4 100644 --- a/inc/Engine/License/API/UserClient.php +++ b/inc/Engine/License/API/UserClient.php @@ -3,8 +3,9 @@ namespace WP_Rocket\Engine\License\API; use WP_Rocket\Admin\Options_Data; +use WP_Rocket\Engine\Common\JobManager\APIHandler\AbstractSafeAPIClient; -class UserClient { +class UserClient extends AbstractSafeAPIClient { const USER_ENDPOINT = 'https://wp-rocket.me/stat/1.0/wp-rocket/user.php'; /** @@ -14,6 +15,28 @@ class UserClient { */ private $options; + /** + * Get the transient key for plugin updates. + * + * This method returns the transient key used for caching plugin updates. + * + * @return string The transient key for plugin updates. + */ + protected function get_transient_key() { + return 'wpr_user_information'; + } + + /** + * Get the API URL for plugin updates. + * + * This method returns the API URL used for fetching plugin updates. + * + * @return string The API URL for plugin updates. + */ + protected function get_api_url() { + return self::USER_ENDPOINT; + } + /** * Instantiate the class * @@ -65,14 +88,14 @@ private function get_raw_user_data() { ? $this->options->get( 'consumer_email', '' ) : rocket_get_constant( 'WP_ROCKET_EMAIL', '' ); - $response = wp_safe_remote_post( - self::USER_ENDPOINT, + $response = $this->send_post_request( [ 'body' => 'user_id=' . rawurlencode( $customer_email ) . '&consumer_key=' . sanitize_key( $customer_key ), - ] + ], + true ); - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { + if ( is_wp_error( $response ) ) { return false; } diff --git a/inc/Engine/Media/AboveTheFold/AJAX/Controller.php b/inc/Engine/Media/AboveTheFold/AJAX/Controller.php index 7213182d86..ed5d60526c 100644 --- a/inc/Engine/Media/AboveTheFold/AJAX/Controller.php +++ b/inc/Engine/Media/AboveTheFold/AJAX/Controller.php @@ -24,6 +24,15 @@ class Controller { */ protected $context; + /** + * An array of unsupported atf schemes. + * + * @var array + */ + private $invalid_schemes = [ + 'chrome-[^:]+://', + ]; + /** * Constructor * @@ -69,20 +78,25 @@ public function add_lcp_data() { $keys = [ 'bg_set', 'src' ]; foreach ( (array) $images as $image ) { - if ( isset( $image->type ) ) { - $image_object = $this->create_object( $image, $keys ); - - if ( 'lcp' === $image->label && null !== $image_object ) { - $lcp = $image_object; - } elseif ( 'above-the-fold' === $image->label && null !== $image_object ) { - if ( 0 === $max_atf_images_number ) { - continue; - } + if ( empty( $image->type ) ) { + continue; + } - $viewport[] = $image_object; + $image_object = $this->create_object( $image, $keys ); - --$max_atf_images_number; - } + if ( ! $image_object || ! $this->validate_image( $image_object ) ) { + continue; + } + + if ( 'lcp' === $image->label ) { + $lcp = $image_object; + continue; + } + + if ( 'above-the-fold' === $image->label && 0 < $max_atf_images_number ) { + $viewport[] = $image_object; + + --$max_atf_images_number; } } @@ -254,4 +268,65 @@ public function check_lcp_data() { wp_send_json_error( 'data does not exist' ); } + + /** + * Validate image object. + * + * @param object $image_object Image full object. + * @return bool + */ + private function validate_image( $image_object ) { + $valid_image = ! empty( $image_object->src ) ? $this->validate_image_src( $image_object->src ?? '' ) : true; + + /** + * Filters If the image src is a valid image or not. + * + * @param bool $valid_image Valid image or not. + * @param string $image_src_url Image src url. + * @param object $image_object Image object with full details. + */ + return (bool) apply_filters( 'rocket_atf_valid_image', $valid_image, $image_object->src, $image_object ); + } + + /** + * Make sure that this url is valid image without loading the image itself. + * + * @param string $image_src Image src url. + * @return bool + */ + private function validate_image_src( $image_src ) { + if ( empty( $image_src ) ) { + return false; + } + + /** + * Filters the supported schemes of LCP/ATF images. + * + * @param array $invalid_schemes Array of invalid schemes. + */ + $invalid_schemes = apply_filters( 'rocket_atf_invalid_schemes', $this->invalid_schemes ); + + if ( ! is_array( $invalid_schemes ) ) { + $invalid_schemes = $this->invalid_schemes; + } + + $invalid_schemes = implode( '|', $invalid_schemes ); + + if ( preg_match( '#^' . $invalid_schemes . '#', $image_src ) ) { + return false; + } + + // Here we get the url PATH part only to strip all query strings. + $image_src_path = wp_parse_url( $image_src, PHP_URL_PATH ); + if ( empty( $image_src_path ) ) { + return false; + } + + // Add svg to allowed mime types. + $allowed_mime_types = get_allowed_mime_types(); + $allowed_mime_types['svg'] = 'image/svg+xml'; + $image_src_filetype_array = wp_check_filetype( $image_src_path, $allowed_mime_types ); + + return ! empty( $image_src_filetype_array['type'] ) && str_starts_with( $image_src_filetype_array['type'], 'image/' ); + } } diff --git a/inc/Engine/Plugin/InformationSubscriber.php b/inc/Engine/Plugin/InformationSubscriber.php index 93f11c3e78..f0398ef45b 100644 --- a/inc/Engine/Plugin/InformationSubscriber.php +++ b/inc/Engine/Plugin/InformationSubscriber.php @@ -2,6 +2,7 @@ namespace WP_Rocket\Engine\Plugin; use WP_Rocket\Event_Management\Subscriber_Interface; +use WP_Error; /** * Manages the plugin information. @@ -33,9 +34,7 @@ class InformationSubscriber implements Subscriber_Interface { /** * Constructor * - * @param array $args { - * Required arguments to populate the class properties. - * + * @param array $args { Required arguments to populate the class properties. * @type string $plugin_file Full path to the plugin. * @type string $api_url URL to contact to get update info. * } @@ -79,12 +78,12 @@ public function exclude_rocket_from_wp_info( $bool, $action, $args ) { // phpcs: } /** - * Insert WP Rocket plugin info. + * Insert WP Rocket plugin info. * - * @param object|\WP_Error $res Response object or WP_Error. - * @param string $action The type of information being requested from the Plugin Install API. - * @param object $args Plugin API arguments. - * @return object|\WP_Error Updated response object or WP_Error. + * @param object|WP_Error $res Response object or WP_Error. + * @param string $action The type of information being requested from the Plugin Install API. + * @param object $args Plugin API arguments. + * @return object|WP_Error Updated response object or WP_Error. */ public function add_rocket_info( $res, $action, $args ) { if ( ! $this->is_requesting_rocket_info( $action, $args ) || empty( $res->external ) ) { @@ -112,7 +111,7 @@ public function add_wp_tested_version( $wp_tested_version ): string { } /** - * Tell if requesting WP Rocket plugin info. + * Tell if requesting WP Rocket plugin info. * * @param string $action The type of information being requested from the Plugin Install API. * @param object $args Plugin API arguments. @@ -125,7 +124,7 @@ private function is_requesting_rocket_info( $action, $args ) { /** * Gets the plugin information data * - * @return object|\WP_Error + * @return object|WP_Error */ private function get_plugin_information() { $response = wp_remote_get( $this->api_url ); diff --git a/inc/Engine/Plugin/ServiceProvider.php b/inc/Engine/Plugin/ServiceProvider.php index 398e79ec43..809bcad86a 100644 --- a/inc/Engine/Plugin/ServiceProvider.php +++ b/inc/Engine/Plugin/ServiceProvider.php @@ -55,6 +55,7 @@ public function register(): void { ] ) ->addTag( 'common_subscriber' ); + $this->getContainer()->addShared( 'plugin_information_subscriber', InformationSubscriber::class ) ->addArgument( [ @@ -63,6 +64,7 @@ public function register(): void { ] ) ->addTag( 'common_subscriber' ); + $this->getContainer()->addShared( 'plugin_updater_subscriber', UpdaterSubscriber::class ) ->addArgument( $this->getContainer()->get( 'plugin_renewal_notice' ) ) ->addArgument( diff --git a/inc/Engine/Plugin/UpdaterSubscriber.php b/inc/Engine/Plugin/UpdaterSubscriber.php index 5224b7aa8c..c5f847daa5 100644 --- a/inc/Engine/Plugin/UpdaterSubscriber.php +++ b/inc/Engine/Plugin/UpdaterSubscriber.php @@ -84,9 +84,8 @@ class UpdaterSubscriber implements Event_Manager_Aware_Subscriber_Interface { * Constructor * * @param RenewalNotice $renewal_notice RenewalNotice instance. - * @param array $args { - * Required arguments to populate the class properties. * + * @param array $args { Required arguments to populate the class properties. * @type string $plugin_file Full path to the plugin. * @type string $plugin_version Current version of the plugin. * @type string $vendor_url URL to the plugin provider. diff --git a/inc/Engine/WPRocketUninstall.php b/inc/Engine/WPRocketUninstall.php index d2999c6204..87af2ea745 100644 --- a/inc/Engine/WPRocketUninstall.php +++ b/inc/Engine/WPRocketUninstall.php @@ -82,6 +82,8 @@ class WPRocketUninstall { 'rocket_get_refreshed_fragments_cache', 'rocket_preload_previous_requests_durations', 'rocket_preload_check_duration', + 'wpr_user_information_timeout_active', + 'wpr_user_information_timeout', ]; /** diff --git a/inc/ThirdParty/Hostings/Godaddy.php b/inc/ThirdParty/Hostings/Godaddy.php index 0876e85b09..e4601b57b3 100644 --- a/inc/ThirdParty/Hostings/Godaddy.php +++ b/inc/ThirdParty/Hostings/Godaddy.php @@ -22,7 +22,6 @@ class Godaddy implements Subscriber_Interface { * @param string $vip_url Godaddy vip url. */ public function __construct( $vip_url = '' ) { - // @phpstan-ignore-next-line $this->vip_url = method_exists( '\WPaas\Plugin', 'vip' ) ? \WPaas\Plugin::vip() : $vip_url; } diff --git a/inc/ThirdParty/Hostings/Pressidium.php b/inc/ThirdParty/Hostings/Pressidium.php index 5fd03ad8f2..a248b9e0ed 100644 --- a/inc/ThirdParty/Hostings/Pressidium.php +++ b/inc/ThirdParty/Hostings/Pressidium.php @@ -73,7 +73,6 @@ public function clear_cache_after_pressidium() { * @return void */ public function clean_pressidium() { - // @phpstan-ignore-next-line $plugin = NinukisCaching::get_instance(); $plugin->purgeAllCaches(); } @@ -107,7 +106,6 @@ private function get_paths( $urls ) { * @return void */ private function purge_cache( $paths ) { - // @phpstan-ignore-next-line NinukisCaching::get_instance()->purge_cache( $paths ); } diff --git a/inc/ThirdParty/Hostings/Savvii.php b/inc/ThirdParty/Hostings/Savvii.php index a6f7417546..ead1090b18 100644 --- a/inc/ThirdParty/Hostings/Savvii.php +++ b/inc/ThirdParty/Hostings/Savvii.php @@ -63,18 +63,14 @@ public function varnish_addon_title( $settings ) { public function clear_cache_after_savvii() { if ( ! ( - // @phpstan-ignore-next-line isset( $_REQUEST[ CacheFlusherPlugin::NAME_FLUSH_NOW ] ) && - // @phpstan-ignore-next-line check_admin_referer( CacheFlusherPlugin::NAME_FLUSH_NOW ) ) && ! ( - // @phpstan-ignore-next-line isset( $_REQUEST[ CacheFlusherPlugin::NAME_DOMAINFLUSH_NOW ] ) && - // @phpstan-ignore-next-line check_admin_referer( CacheFlusherPlugin::NAME_DOMAINFLUSH_NOW ) ) ) { diff --git a/inc/ThirdParty/Hostings/WPEngine.php b/inc/ThirdParty/Hostings/WPEngine.php index 216c01fad3..fd195f46f5 100644 --- a/inc/ThirdParty/Hostings/WPEngine.php +++ b/inc/ThirdParty/Hostings/WPEngine.php @@ -57,12 +57,10 @@ public function varnish_addon_title( $settings ) { */ public function clean_wpengine() { if ( method_exists( 'WpeCommon', 'purge_memcached' ) ) { - // @phpstan-ignore-next-line WpeCommon::purge_memcached(); } if ( method_exists( 'WpeCommon', 'purge_varnish_cache' ) ) { - // @phpstan-ignore-next-line WpeCommon::purge_varnish_cache(); } } diff --git a/inc/ThirdParty/Plugins/Ecommerce/WooCommerceSubscriber.php b/inc/ThirdParty/Plugins/Ecommerce/WooCommerceSubscriber.php index 06197b41cf..1e4cdcca3e 100644 --- a/inc/ThirdParty/Plugins/Ecommerce/WooCommerceSubscriber.php +++ b/inc/ThirdParty/Plugins/Ecommerce/WooCommerceSubscriber.php @@ -512,7 +512,6 @@ public function exclude_product_shipping_taxonomy( $excluded_taxonomies ) { * @return bool */ private function product_has_gallery_images() { - // @phpstan-ignore-next-line $product = wc_get_product( get_the_ID() ); if ( empty( $product ) ) { return false; @@ -530,7 +529,6 @@ public function show_empty_product_gallery_with_delayJS() { return; } - // @phpstan-ignore-next-line if ( ! is_product() ) { return; } @@ -562,7 +560,6 @@ public function show_notempty_product_gallery_with_delayJS( $exclusions = [] ): return $exclusions; } - // @phpstan-ignore-next-line if ( ! is_product() ) { return $exclusions; } @@ -616,14 +613,13 @@ public function disallow_rocket_clean_post(): void { */ public function allow_rocket_clean_post( int $product_id ): void { $urls = []; - // @phpstan-ignore-next-line + $category_list = wc_get_product_category_list( $product_id ); if ( preg_match_all( '/]*?\s+)?href=(["\'])(?.*?)\1/i', $category_list, $matches ) ) { $urls = $matches['urls']; } - // @phpstan-ignore-next-line $shop_page = get_permalink( wc_get_page_id( 'shop' ) ); if ( empty( $shop_page ) ) { diff --git a/inc/ThirdParty/Plugins/I18n/TranslatePress.php b/inc/ThirdParty/Plugins/I18n/TranslatePress.php index 9220150fcf..e55cc3b52a 100644 --- a/inc/ThirdParty/Plugins/I18n/TranslatePress.php +++ b/inc/ThirdParty/Plugins/I18n/TranslatePress.php @@ -41,7 +41,7 @@ public static function get_subscribed_events() { * @return string */ public function detect_homepage( $home_url, $url ) { - // @phpstan-ignore-next-line + $translatepress = TRP_Translate_Press::get_trp_instance(); $converter = $translatepress->get_component( 'url_converter' ); @@ -78,7 +78,6 @@ function_exists( 'trp_get_languages' ) * @return array */ public function add_langs_to_admin_bar( $langlinks ) { - // @phpstan-ignore-next-line $translatepress = TRP_Translate_Press::get_trp_instance(); $language_switcher = $translatepress->get_component( 'language_switcher' ); @@ -129,7 +128,6 @@ public function get_active_languages_uri( $urls ) { $home_url = home_url(); - // @phpstan-ignore-next-line $translatepress = TRP_Translate_Press::get_trp_instance(); $settings = $translatepress->get_component( 'settings' ); @@ -159,7 +157,6 @@ public function get_active_languages_codes( $codes ) { $codes = (array) $codes; } - // @phpstan-ignore-next-line $translatepress = TRP_Translate_Press::get_trp_instance(); $settings = $translatepress->get_component( 'settings' ); @@ -189,7 +186,6 @@ public function get_home_url_for_lang( $home_url, $lang ) { return $home_url; } - // @phpstan-ignore-next-line $translatepress = TRP_Translate_Press::get_trp_instance(); $converter = $translatepress->get_component( 'url_converter' ); $settings = $translatepress->get_component( 'settings' ); @@ -228,7 +224,6 @@ public function get_translated_post_urls( $urls, $url, $post_type, $regex ) { $urls = (array) $urls; } - // @phpstan-ignore-next-line $translatepress = TRP_Translate_Press::get_trp_instance(); $settings = $translatepress->get_component( 'settings' ); @@ -254,7 +249,6 @@ public function get_translated_post_urls( $urls, $url, $post_type, $regex ) { * @return void */ public function clear_post_languages( $post_id ) { - // @phpstan-ignore-next-line $translatepress = TRP_Translate_Press::get_trp_instance(); $converter = $translatepress->get_component( 'url_converter' ); @@ -293,7 +287,6 @@ public function clear_post_languages( $post_id ) { * @return void */ public function clear_post_after_updating_translation( $update_strings, $settings ) { - // @phpstan-ignore-next-line $translatepress = TRP_Translate_Press::get_trp_instance(); $converter = $translatepress->get_component( 'url_converter' ); diff --git a/inc/ThirdParty/Plugins/SEO/SEOPress.php b/inc/ThirdParty/Plugins/SEO/SEOPress.php index 8c8c3bb9ca..23e896bebc 100644 --- a/inc/ThirdParty/Plugins/SEO/SEOPress.php +++ b/inc/ThirdParty/Plugins/SEO/SEOPress.php @@ -31,7 +31,6 @@ public static function get_subscribed_events() { return []; } - // @phpstan-ignore-next-line if ( ! method_exists( seopress_get_service( 'SitemapOption' ), 'isEnabled' ) || 1 !== (int) seopress_get_service( 'SitemapOption' )->isEnabled() ) { return []; } diff --git a/inc/ThirdParty/Plugins/SEO/TheSEOFramework.php b/inc/ThirdParty/Plugins/SEO/TheSEOFramework.php index a83539313d..9eeba9f29c 100644 --- a/inc/ThirdParty/Plugins/SEO/TheSEOFramework.php +++ b/inc/ThirdParty/Plugins/SEO/TheSEOFramework.php @@ -66,8 +66,6 @@ public function add_tsf_sitemap_to_preload( $sitemaps ) { // The autoloader in TSF doesn't check for file_exists(). So, use version compare instead to prevent fatal errors. if ( version_compare( rocket_get_constant( 'THE_SEO_FRAMEWORK_VERSION', false ), '4.0', '>=' ) ) { // TSF 4.0+. Expect the class to exist indefinitely. - - // @phpstan-ignore-next-line $sitemap_bridge = Sitemap::get_instance(); foreach ( $sitemap_bridge->get_sitemap_endpoint_list() as $id => $data ) { @@ -80,8 +78,6 @@ public function add_tsf_sitemap_to_preload( $sitemaps ) { } } else { // Deprecated. TSF <4.0. - - // @phpstan-ignore-next-line $sitemaps[] = the_seo_framework()->get_sitemap_xml_url(); } diff --git a/inc/ThirdParty/Plugins/Security/WordFenceCompatibility.php b/inc/ThirdParty/Plugins/Security/WordFenceCompatibility.php index 099dfa3116..fef1762302 100644 --- a/inc/ThirdParty/Plugins/Security/WordFenceCompatibility.php +++ b/inc/ThirdParty/Plugins/Security/WordFenceCompatibility.php @@ -57,8 +57,6 @@ public function pop_old_ip( string $old_rucss_ip ) { } // Update whitelist. - - // @phpstan-ignore-next-line wfConfig::set( 'whitelisted', implode( ',', $whitelist ) ); } @@ -76,8 +74,6 @@ public function pop_ip_from_whitelist() { } // Update whitelist. - - // @phpstan-ignore-next-line wfConfig::set( 'whitelisted', implode( ',', $whitelist ) ); } @@ -89,8 +85,6 @@ public function pop_ip_from_whitelist() { */ private function can_pop_ip( string $ip ) { // Get all whitelists. - - // @phpstan-ignore-next-line $whitelists = wfConfig::get( 'whitelisted', '' ); // Convert to array. @@ -134,7 +128,6 @@ public function whitelist_wordfence_firewall_ips() { } foreach ( $ips as $ip ) { - // @phpstan-ignore-next-line wordfence::whitelistIP( $ip ); } } diff --git a/phpstan.neon.dist b/phpstan.neon.dist index b045c24a64..71ae4fda0b 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -1,37 +1,48 @@ includes: - - phar://phpstan.phar/conf/bleedingEdge.neon + - phar://phpstan.phar/conf/bleedingEdge.neon parameters: - level: 0 - checkMissingIterableValueType: false - inferPrivatePropertyTypeFromConstructor: true - paths: - # Test only the new architecture for now. - - %currentWorkingDirectory%/inc/Engine/ - - %currentWorkingDirectory%/inc/Addon/ - - %currentWorkingDirectory%/inc/ThirdParty/ - bootstrapFiles: - # Must be first - - %currentWorkingDirectory%/inc/functions/options.php - # Procedural code - - %currentWorkingDirectory%/inc/constants.php - - %currentWorkingDirectory%/inc/common/purge.php - - %currentWorkingDirectory%/inc/API/bypass.php - - %currentWorkingDirectory%/inc/3rd-party/plugins/autoptimize.php - - %currentWorkingDirectory%/inc/admin/ui/notices.php - - %currentWorkingDirectory%/inc/functions/admin.php - - %currentWorkingDirectory%/inc/functions/api.php - - %currentWorkingDirectory%/inc/functions/files.php - - %currentWorkingDirectory%/inc/functions/formatting.php - - %currentWorkingDirectory%/inc/functions/htaccess.php - - %currentWorkingDirectory%/inc/functions/i18n.php - - %currentWorkingDirectory%/inc/functions/posts.php - # Composer autoloader "exclude-from-classmap" - - %currentWorkingDirectory%/inc/classes/class-wp-rocket-requirements-check.php - - %currentWorkingDirectory%/inc/vendors/classes/class-rocket-mobile-detect.php - scanDirectories: - - %currentWorkingDirectory%/inc/Dependencies/ActionScheduler - excludePaths: - - %currentWorkingDirectory%/inc/vendors/ - # These need plugin stubs! - - %currentWorkingDirectory%/inc/classes/subscriber/third-party/ - - %currentWorkingDirectory%/inc/3rd-party/ + level: 0 + inferPrivatePropertyTypeFromConstructor: true + paths: + # Test only the new architecture for now. + - %currentWorkingDirectory%/inc/Engine/ + - %currentWorkingDirectory%/inc/Addon/ + - %currentWorkingDirectory%/inc/ThirdParty/ + - %currentWorkingDirectory%/tests/Integration/ + - %currentWorkingDirectory%/tests/Unit/ + bootstrapFiles: + # Must be first + - %currentWorkingDirectory%/inc/functions/options.php + # Procedural code + - %currentWorkingDirectory%/inc/constants.php + - %currentWorkingDirectory%/inc/common/purge.php + - %currentWorkingDirectory%/inc/API/bypass.php + - %currentWorkingDirectory%/inc/3rd-party/plugins/autoptimize.php + - %currentWorkingDirectory%/inc/admin/ui/notices.php + - %currentWorkingDirectory%/inc/functions/admin.php + - %currentWorkingDirectory%/inc/functions/api.php + - %currentWorkingDirectory%/inc/functions/files.php + - %currentWorkingDirectory%/inc/functions/formatting.php + - %currentWorkingDirectory%/inc/functions/htaccess.php + - %currentWorkingDirectory%/inc/functions/i18n.php + - %currentWorkingDirectory%/inc/functions/posts.php + # Composer autoloader "exclude-from-classmap" + - %currentWorkingDirectory%/inc/classes/class-wp-rocket-requirements-check.php + - %currentWorkingDirectory%/inc/vendors/classes/class-rocket-mobile-detect.php + scanDirectories: + - %currentWorkingDirectory%/inc/Dependencies/ActionScheduler + - %currentWorkingDirectory%/tests/Fixtures/ + - %currentWorkingDirectory%/vendor/antecedent/patchwork/ + - %currentWorkingDirectory%/vendor/wpackagist-plugin/amp/ + - %currentWorkingDirectory%/vendor/wpackagist-plugin/the-events-calendar/ + - %currentWorkingDirectory%/vendor/wpackagist-plugin/woocommerce/ + scanFiles: + - %currentWorkingDirectory%/inc/admin/upgrader.php + - %currentWorkingDirectory%/inc/admin/options.php + - %currentWorkingDirectory%/vendor/php-stubs/wordpress-stubs/wordpress-stubs.php + - %currentWorkingDirectory%/vendor/php-stubs/wordpress-tests-stubs/wordpress-tests-stubs.php + excludePaths: + - %currentWorkingDirectory%/inc/vendors/ + # These need plugin stubs! + - %currentWorkingDirectory%/inc/classes/subscriber/third-party/ + - %currentWorkingDirectory%/inc/3rd-party/ diff --git a/tests/Fixtures/inc/Engine/Media/AboveTheFold/AJAX/Controller/addLcpData.php b/tests/Fixtures/inc/Engine/Media/AboveTheFold/AJAX/Controller/addLcpData.php index 2266c2c9c2..b3d0eaf2dc 100644 --- a/tests/Fixtures/inc/Engine/Media/AboveTheFold/AJAX/Controller/addLcpData.php +++ b/tests/Fixtures/inc/Engine/Media/AboveTheFold/AJAX/Controller/addLcpData.php @@ -66,6 +66,21 @@ ], ] ), + 'filetype' => [ + 'ext' => 'jpg', + 'type' => 'image/jpeg', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], ], 'expected' => [ 'images_valid_sources' => [], @@ -111,6 +126,21 @@ ], ] ), + 'filetype' => [ + 'ext' => 'jpg', + 'type' => 'image/jpeg', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], ], 'expected' => [ 'images_valid_sources' => [], @@ -174,6 +204,21 @@ ], ] ), + 'filetype' => [ + 'ext' => 'jpg', + 'type' => 'image/jpeg', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], ], 'expected' => [ 'images_valid_sources' => [], @@ -239,6 +284,21 @@ ], ] ), + 'filetype' => [ + 'ext' => 'jpg', + 'type' => 'image/jpeg', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], ], 'expected' => [ 'images_valid_sources' => [ @@ -296,7 +356,7 @@ (object) [ 'label' => 'lcp', 'type' => 'bg-img', - 'src' => 'http://example.org/lcp.jpg', + 'src' => '', 'bg_set' => [ [ 'src' => 'http://example.org/anotherlcp.jpg' @@ -313,6 +373,21 @@ ], ] ), + 'filetype' => [ + 'ext' => 'jpg', + 'type' => 'image/jpeg', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], ], 'expected' => [ 'images_valid_sources' => [ @@ -408,6 +483,21 @@ ], ] ), + 'filetype' => [ + 'ext' => 'jpg', + 'type' => 'image/jpeg', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], ], 'expected' => [ 'images_valid_sources' => [], @@ -476,6 +566,21 @@ 'images' => json_encode( $long_array ), + 'filetype' => [ + 'ext' => 'jpg', + 'type' => 'image/jpeg', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], ], 'expected' => [ 'images_valid_sources' => [], @@ -637,4 +742,328 @@ ], ], ], + + 'testShouldBailoutWithNotValidImages1' => [ + 'config' => [ + 'filter' => true, + 'url' => 'http://example.org', + 'is_mobile' => false, + 'images' => json_encode( + [ + (object) [ + 'label' => 'lcp', + 'type' => 'img', + 'src' => 'http://example.org/file.php?url=img.jpg', + ], + ] + ), + 'filetype' => [ + 'ext' => 'php', + 'type' => false, + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], + ], + 'expected' => [ + 'item' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + 'result' => true, + 'message' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + ], + ], + 'testShouldBailoutWithNotValidImages2' => [ + 'config' => [ + 'filter' => true, + 'url' => 'http://example.org', + 'is_mobile' => false, + 'images' => json_encode( + [ + (object) [ + 'label' => 'lcp', + 'type' => 'img', + 'src' => 'http://example.org/file.js?url=img.jpg', + ], + ] + ), + 'filetype' => [ + 'ext' => 'js', + 'type' => 'application/javascript', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], + ], + 'expected' => [ + 'item' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + 'result' => true, + 'message' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + ], + ], + 'testShouldBailoutWithNotValidImages3' => [ + 'config' => [ + 'filter' => true, + 'url' => 'http://example.org', + 'is_mobile' => false, + 'images' => json_encode( + [ + (object) [ + 'label' => 'lcp', + 'type' => 'img', + 'src' => 'http://example.org/file.php#url=img.jpg', + ], + ] + ), + 'filetype' => [ + 'ext' => 'php', + 'type' => 'application/php', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], + ], + 'expected' => [ + 'item' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + 'result' => true, + 'message' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + ], + ], + 'testShouldBailoutWithNotValidImages4' => [ + 'config' => [ + 'filter' => true, + 'url' => 'http://example.org', + 'is_mobile' => false, + 'images' => json_encode( + [ + (object) [ + 'label' => 'lcp', + 'type' => 'img', + 'src' => 'chrome-extension://extension-hash/path/to/image/x.svg', + ], + ] + ), + 'filetype' => [ + 'ext' => 'svg', + 'type' => 'image/svg+xml', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], + ], + 'expected' => [ + 'item' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + 'result' => true, + 'message' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + ], + ], + 'testShouldBailoutWithNotValidImages5' => [ + 'config' => [ + 'filter' => true, + 'url' => 'http://example.org', + 'is_mobile' => false, + 'images' => json_encode( + [ + (object) [ + 'label' => 'lcp', + 'type' => 'bg-img', + 'src' => 'linear-gradient(160deg, rgb(255, 255, 255) 0%, rgb(248, 246, 243) 100%)', + ], + ] + ), + 'filetype' => [ + 'ext' => false, + 'type' => false, + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], + ], + 'expected' => [ + 'item' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + 'result' => true, + 'message' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => 'not found', + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + ], + ], + 'testShouldAddItemToDBWhenSvgWithHttpProtocol' => [ + 'config' => [ + 'filter' => true, + 'url' => 'http://example.org', + 'is_mobile' => false, + 'images' => json_encode( + [ + (object) [ + 'label' => 'lcp', + 'type' => 'img', + 'src' => 'http://example.org/path/to/images/image.svg', + ], + ] + ), + 'filetype' => [ + 'ext' => 'svg', + 'type' => 'image/svg+xml', + ], + 'allowed_mime_types' => [ + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tiff|tif' => 'image/tiff', + 'webp' => 'image/webp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'heic' => 'image/heic', + ], + ], + 'expected' => [ + 'images_valid_sources' => [], + 'item' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => json_encode( + (object) [ + 'type' => 'img', + 'src' => 'http://example.org/path/to/images/image.svg', + ], + ), + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + 'result' => true, + 'message' => [ + 'url' => 'http://example.org', + 'is_mobile' => false, + 'status' => 'completed', + 'lcp' => json_encode( + (object) [ + 'type' => 'img', + 'src' => 'http://example.org/path/to/images/image.svg', + ], + ), + 'viewport' => '[]', + 'last_accessed' => '2024-01-01 00:00:00', + 'error_message' => '', + ], + ], + ], ]; diff --git a/tests/Integration/inc/Engine/License/API/UserClient/getUserData.php b/tests/Integration/inc/Engine/License/API/UserClient/getUserData.php index 8fc3eea35c..9346c5c88b 100644 --- a/tests/Integration/inc/Engine/License/API/UserClient/getUserData.php +++ b/tests/Integration/inc/Engine/License/API/UserClient/getUserData.php @@ -30,13 +30,17 @@ public static function set_up_before_class() { public function set_up() { parent::set_up(); - + delete_transient( 'wp_rocket_customer_data' ); + delete_transient( 'wpr_user_information_timeout_active' ); + delete_transient( 'wpr_user_information_timeout' ); add_filter( 'pre_get_rocket_option_consumer_email', [ $this, 'set_consumer_email' ] ); add_filter( 'pre_get_rocket_option_consumer_key', [ $this, 'set_consumer_key' ] ); } public function tear_down() { delete_transient( 'wp_rocket_customer_data' ); + delete_transient( 'wpr_user_information_timeout_active' ); + delete_transient( 'wpr_user_information_timeout' ); remove_filter( 'pre_get_rocket_option_consumer_email', [ $this, 'set_consumer_email' ] ); remove_filter( 'pre_get_rocket_option_consumer_key', [ $this, 'set_consumer_key' ] ); remove_filter( 'pre_http_request', [ $this, 'set_response' ] ); diff --git a/tests/Integration/inc/Engine/Optimization/Minify/CSS/AdminSubscriber/onUpdate.php b/tests/Integration/inc/Engine/Optimization/Minify/CSS/AdminSubscriber/onUpdate.php index 1a41de6768..45f8c507f5 100644 --- a/tests/Integration/inc/Engine/Optimization/Minify/CSS/AdminSubscriber/onUpdate.php +++ b/tests/Integration/inc/Engine/Optimization/Minify/CSS/AdminSubscriber/onUpdate.php @@ -2,8 +2,8 @@ namespace WP_Rocket\Tests\Integration\inc\Engine\Optimization\Minify\CSS\AdminSubscriber; -use WP_Rocket\Tests\Integration\TestCase; use Brain\Monkey\Functions; +use WP_Rocket\Tests\Integration\TestCase; /** * Test class covering \WP_Rocket\Engine\Optimization\Minify\CSS\AdminSubscriber::on_update @@ -11,7 +11,7 @@ * @group AdminOnly * @group MinifyAdmin */ -class Test_OnUpdate extends TestCase { +class TestOnUpdate extends TestCase { public function set_up() { parent::set_up(); @@ -19,7 +19,7 @@ public function set_up() { } public function tear_down() { - add_filter( 'wp_rocket_upgrade', 'rocket_new_upgrade' ); + add_filter( 'wp_rocket_upgrade', 'rocket_new_upgrade', 10, 2 ); parent::tear_down(); } diff --git a/tests/Integration/inc/Engine/WPRocketUninstall/uninstall.php b/tests/Integration/inc/Engine/WPRocketUninstall/uninstall.php index f237f5c252..1e88e42d13 100644 --- a/tests/Integration/inc/Engine/WPRocketUninstall/uninstall.php +++ b/tests/Integration/inc/Engine/WPRocketUninstall/uninstall.php @@ -64,6 +64,8 @@ class Test_Uninstall extends FilesystemTestCase { 'wp_rocket_pricing_timeout' => null, 'wp_rocket_pricing_timeout_active' => null, 'rocket_get_refreshed_fragments_cache' => null, + 'wpr_user_information_timeout_active' => null, + 'wpr_user_information_timeout' => null, ]; private $events = [ diff --git a/tests/Integration/inc/ThirdParty/Hostings/Godaddy/GodaddyTestCase.php b/tests/Integration/inc/ThirdParty/Hostings/Godaddy/GodaddyTestCase.php index 525fb1455b..9054c91b08 100644 --- a/tests/Integration/inc/ThirdParty/Hostings/Godaddy/GodaddyTestCase.php +++ b/tests/Integration/inc/ThirdParty/Hostings/Godaddy/GodaddyTestCase.php @@ -1,5 +1,5 @@ options = $container->get('options'); - $this->options_api = $container->get('options_api'); + + $container = apply_filters( 'rocket_container', null ); + $this->options = $container->get( 'options' ); + $this->options_api = $container->get( 'options_api' ); } /** - * @dataProvider configTestData - */ - public function testShouldDoAsExpected( $config ) - { - Functions\expect('is_plugin_active')->with('')->andReturn($config['plugin_active']); - do_action('enable_cloudflare/cloudflare.php'); - $settings = $this->options_api->get('settings'); - $this->options->set_values($settings); - $this->assertSame(false, $this->options->get('do_cloudflare', false)); - } + * @dataProvider configTestData + */ + public function testShouldDoAsExpected( $config ) { + Functions\expect( 'is_plugin_active' )->andReturn( $config['plugin_active'] ); + + do_action( 'enable_cloudflare/cloudflare.php' ); + + $settings = $this->options_api->get( 'settings' ); + + $this->options->set_values( $settings ); + + $this->assertFalse( $this->options->get( 'do_cloudflare', false ) ); + } } diff --git a/tests/Integration/inc/ThirdParty/Themes/Divi/removeAssetsGenerated.php b/tests/Integration/inc/ThirdParty/Themes/Divi/removeAssetsGenerated.php index 39e23eff0a..60b931bea5 100644 --- a/tests/Integration/inc/ThirdParty/Themes/Divi/removeAssetsGenerated.php +++ b/tests/Integration/inc/ThirdParty/Themes/Divi/removeAssetsGenerated.php @@ -10,7 +10,7 @@ * * @group Themes */ -class Test_RemoveAssetsGenerated extends WPThemeTestcase { +class TestRemoveAssetsGenerated extends WPThemeTestcase { private $container; private $event; private $subscriber; @@ -49,8 +49,9 @@ public function testShouldRemoveCallback( $config, $expected ) { $this->event->add_subscriber( $this->subscriber ); - add_action( 'et_dynamic_late_assets_generated', '__return_true' ); - $this->assertTrue( has_action( 'et_dynamic_late_assets_generated' ) ); + add_filter( 'et_dynamic_late_assets_generated', '__return_true' ); + + $this->assertTrue( has_filter( 'et_dynamic_late_assets_generated' ) ); switch_theme( $config['stylesheet'] ); diff --git a/tests/Integration/inc/ThirdParty/Themes/Shoptimizer/excludeJqueryDeferjsWithCartDrawer.php b/tests/Integration/inc/ThirdParty/Themes/Shoptimizer/excludeJqueryDeferjsWithCartDrawer.php index 5a20ca42a2..36fa562b22 100644 --- a/tests/Integration/inc/ThirdParty/Themes/Shoptimizer/excludeJqueryDeferjsWithCartDrawer.php +++ b/tests/Integration/inc/ThirdParty/Themes/Shoptimizer/excludeJqueryDeferjsWithCartDrawer.php @@ -11,7 +11,7 @@ * * @group Themes */ -class Test_excludeJqueryDeferjsWithCartDrawer extends TestCase { +class TestExcludeJqueryDeferjsWithCartDrawer extends TestCase { private $container; private $event; private $subscriber; @@ -20,7 +20,7 @@ public function set_up() { parent::set_up(); $this->container = apply_filters( 'rocket_container', '' ); - $this->event = $this->container->get( 'event_manager' ); + $this->event = $this->container->get( 'event_manager' ); } public function tear_down() { @@ -33,7 +33,8 @@ public function tear_down() { * @dataProvider configTestData */ public function testShouldReturnAsExpected( $config, $expected ) { - $this->subscriber = new Shoptimizer( $this->container->get( 'options' ) ); + $this->subscriber = new Shoptimizer(); + $this->event->add_subscriber( $this->subscriber ); Functions\when( 'shoptimizer_get_option' )->justReturn( $config['option'] ); diff --git a/tests/Integration/inc/admin/rocketAfterSaveOptions.php b/tests/Integration/inc/admin/rocketAfterSaveOptions.php index 2acedd07f8..a937a50e3f 100644 --- a/tests/Integration/inc/admin/rocketAfterSaveOptions.php +++ b/tests/Integration/inc/admin/rocketAfterSaveOptions.php @@ -227,30 +227,4 @@ private function set_transient() { Functions\expect( 'set_transient' )->with( 'rocket_analytics_optin', 1 )->never(); } } - - private function silently_update_option( $new_value ) { - global $wp_filter; - - $hooks = [ - 'pre_update_option_wp_rocket_settings', - 'pre_update_option', - 'default_option_wp_rocket_settings', - 'update_option', - 'update_option_wp_rocket_settings', - 'updated_option', - ]; - - foreach ( $hooks as $hook ) { - if ( ! empty( $wp_filter[ $hook ] ) ) { - $this->hooks[ $hook ] = $wp_filter[ $hook ]; - unset( $wp_filter[ $hook ] ); - } - } - - update_option( $this->option_name, $new_value ); - - if ( $this->hooks ) { - $wp_filter = array_merge( $wp_filter, $this->hooks ); - } - } } diff --git a/tests/Integration/inc/admin/rocketFirstInstall.php b/tests/Integration/inc/admin/rocketFirstInstall.php index 8d2ae0b785..890be4e426 100644 --- a/tests/Integration/inc/admin/rocketFirstInstall.php +++ b/tests/Integration/inc/admin/rocketFirstInstall.php @@ -6,6 +6,7 @@ /** * Test class covering ::rocket_first_install + * * @group admin * @group upgrade * @group AdminOnly @@ -111,8 +112,4 @@ public function testShouldAddOption( $expected ) { $this->assertContains( $this->box_name, $user_boxes ); $this->assertNotSame( 'foobar', get_transient( $this->box_name ) ); } - - public function addProvider() { - return $this->getTestData( __DIR__, 'rocketFirstInstall' ); - } } diff --git a/tests/Unit/inc/Engine/Cache/Config/ConfigSubscriber/changeCacheRejectUriWithPermalink.php b/tests/Unit/inc/Engine/Cache/Config/ConfigSubscriber/changeCacheRejectUriWithPermalink.php index 8e0a2ea54b..ec74cf76d2 100644 --- a/tests/Unit/inc/Engine/Cache/Config/ConfigSubscriber/changeCacheRejectUriWithPermalink.php +++ b/tests/Unit/inc/Engine/Cache/Config/ConfigSubscriber/changeCacheRejectUriWithPermalink.php @@ -2,22 +2,24 @@ namespace WP_Rocket\Tests\Unit\inc\Engine\Cache\Config\ConfigSubscriber; -use Mockery; -use WP_Rocket\Tests\Unit\TestCase; use Brain\Monkey\Functions; +use Mockery; use WP_Rocket\Admin\Options_Data; use WP_Rocket\Admin\Options; use WP_Rocket\Engine\Cache\Config\ConfigSubscriber; +use WP_Rocket\Tests\Unit\TestCase; /** * Test class covering \WP_Rocket\Engine\Cache\Config\ConfigSubscriber::change_cache_reject_uri_with_permalink + * + * @group Config */ class Test_ChangeCacheRejectUriWithPermalink extends TestCase { - private $config_subscriber; + private $config_subscriber; - public function setUp() : void { + public function setUp(): void { parent::setUp(); - + $options_data = Mockery::mock( Options_Data::class ); $options = Mockery::mock( Options::class ); $this->config_subscriber = new ConfigSubscriber( $options_data, $options ); @@ -31,26 +33,25 @@ public function testShouldReturnExpected( $config, $expected ) { if ( isset( $config['permalink'] ) ) { $times = 2; + $maybe_trailing_slash = $config['permalink']['trailing_slash'] ? '/' : ''; $return_values[] = $config['value']['cache_reject_uri'][0] . $maybe_trailing_slash; if ( false !== strpos( $config['value']['cache_reject_uri'][1], 'index.php' ) || '/' === $config['value']['cache_reject_uri'][1] ) { - unset( $return_values[1] ); $times = 1; - } - else{ + } else { $return_values[] = $config['value']['cache_reject_uri'][1] . $maybe_trailing_slash; } - Functions\expect('user_trailingslashit') - ->times($times) + Functions\expect( 'user_trailingslashit' ) + ->times( $times ) ->andReturnValues( $return_values ); } - $this->assertSame( + $this->assertSame( $expected, - $this->config_subscriber->change_cache_reject_uri_with_permalink( $config['value'], $config['old_value'] ) + $this->config_subscriber->change_cache_reject_uri_with_permalink( $config['value'], $config['old_value'] ) ); } } diff --git a/tests/Unit/inc/Engine/Cache/Purge/purgeDatesArchives.php b/tests/Unit/inc/Engine/Cache/Purge/purgeDatesArchives.php index f9634c7e03..3c37ff60f8 100644 --- a/tests/Unit/inc/Engine/Cache/Purge/purgeDatesArchives.php +++ b/tests/Unit/inc/Engine/Cache/Purge/purgeDatesArchives.php @@ -2,23 +2,24 @@ namespace WP_Rocket\Tests\Unit\inc\Engine\Cache\Purge; -use Mockery; use Brain\Monkey\Functions; use WP_Rocket\Engine\Cache\Purge; -use WP_Rocket\Tests\Unit\FilesystemTestCase; use WP_Rocket\Engine\Preload\Database\Queries\Cache; +use WP_Rocket\Tests\Unit\FilesystemTestCase; /** * Test class covering \WP_Rocket\Engine\Cache\Purge::purge_dates_archives - * @group purge_actions + * + * @group purge_actions */ -class Test_PurgeDatesArchives extends FilesystemTestCase { +class TestPurgeDatesArchives extends FilesystemTestCase { + private $purge; protected $path_to_test_data = '/inc/Engine/Cache/Purge/purgeDatesArchives.php'; protected function setUp(): void { parent::setUp(); - - $query = $this->createPartialMock(Cache::class, ['query']); + + $query = $this->createPartialMock( Cache::class, [ 'query' ] ); $this->purge = new Purge( $this->filesystem, $query ); } @@ -56,13 +57,11 @@ public function testShouldCleanCache( $post, $cleaned ) { ->with( $date[0], $date[1], $date[2] ) ->andReturn( "http://example.org/{$date[0]}/{$date[1]}/{$date[2]}/" ); - Functions\when( 'wp_parse_url' )->alias( function( $url, $component = -1 ) { - return parse_url( $url, $component ); - } ); + $this->stubWpParseUrl(); $this->purge->purge_dates_archives( $post ); $this->checkEntriesDeleted( $cleaned ); $this->checkShouldNotDeleteEntries(); - } + } } diff --git a/tests/Unit/inc/Engine/Cache/Purge/purgePostTermsUrls.php b/tests/Unit/inc/Engine/Cache/Purge/purgePostTermsUrls.php index 708d21bceb..b95b242715 100644 --- a/tests/Unit/inc/Engine/Cache/Purge/purgePostTermsUrls.php +++ b/tests/Unit/inc/Engine/Cache/Purge/purgePostTermsUrls.php @@ -2,27 +2,29 @@ namespace WP_Rocket\Tests\Unit\inc\Engine\Cache\Purge; -use Brain\Monkey\Filters; -use Brain\Monkey\Functions; +use Brain\Monkey\{Filters, Functions}; use Mockery; +use WP_Post; use WP_Rocket\Engine\Cache\Purge; use WP_Rocket\Engine\Preload\Database\Queries\Cache; -use WP_Post; use WP_Rocket\Tests\Unit\FilesystemTestCase; use WP_Term; /** * Test class covering \WP_Rocket\Engine\Cache\Purge::purge_post_terms_urls - * @group Purge - * @group purge_actions + * + * @group Purge + * @group purge_actions */ class Test_PurgePostTermsUrls extends FilesystemTestCase { + private $purge; + protected $path_to_test_data = '/inc/Engine/Cache/Purge/purgePostTermsUrls.php'; public function setUp(): void { parent::setUp(); - $query = $this->createPartialMock(Cache::class, ['query']); + $query = $this->createPartialMock( Cache::class, [ 'query' ] ); $this->purge = new Purge( $this->filesystem, $query ); } @@ -53,7 +55,8 @@ public function testShouldReturnExpectedUrls( $post_data, $terms, $expected ) { ->andReturn( $taxonomies ); Filters\expectApplied( 'rocket_exclude_post_taxonomy' ) ->once(); - $urls = []; + + $urls = []; $index = 0; foreach ( $taxonomies as $type => $taxonomy ) { if ( ! $taxonomy->public ) { @@ -119,9 +122,7 @@ public function testShouldReturnExpectedUrls( $post_data, $terms, $expected ) { } Filters\expectApplied( 'rocket_post_terms_urls', $expected )->once(); - Functions\when( 'wp_parse_url' )->alias( function( $url, $component = -1 ) { - return parse_url( $url, $component ); - } ); + $this->stubWpParseUrl(); $GLOBALS['wp_rewrite'] = (object) [ 'pagination_base' => 'page' ]; @@ -158,7 +159,7 @@ private function getTerms( $type, $config ) { } foreach ( $config as $term ) { - $terms[] = (object) [ 'term_id' => rand(1, 100), 'slug' => isset( $term['name'] ) ? $term['name'] : $term['slug'], 'parent' => isset( $term['parent']) ? $term['parent'] : null ]; + $terms[] = (object) [ 'term_id' => rand( 1, 100 ), 'slug' => isset( $term['name'] ) ? $term['name'] : $term['slug'], 'parent' => isset( $term['parent']) ? $term['parent'] : null ]; } return $terms; diff --git a/tests/Unit/inc/Engine/Common/JobManager/Strategy/Strategies/ResetRetryProcess/execute.php b/tests/Unit/inc/Engine/Common/JobManager/Strategy/Strategies/ResetRetryProcess/execute.php index 24b1a36f7a..33246382ca 100644 --- a/tests/Unit/inc/Engine/Common/JobManager/Strategy/Strategies/ResetRetryProcess/execute.php +++ b/tests/Unit/inc/Engine/Common/JobManager/Strategy/Strategies/ResetRetryProcess/execute.php @@ -1,38 +1,38 @@ manager = Mockery::mock( Manager::class ); - $this->strategy = new ResetRetryProcess($this->manager); - } - - public function tearDown(): void { - parent::tearDown(); + $this->manager = Mockery::mock( Manager::class ); + $this->strategy = new ResetRetryProcess( $this->manager ); } /** * @dataProvider configTestData */ - public function testShouldBehaveAsExpected( $config, $expected ) - { + public function testShouldBehaveAsExpected( $config, $expected ) { $this->manager->shouldReceive( 'add_url_to_the_queue' ) ->once() - ->withArgs([$config['row_details']->url,$config['row_details']->is_mobile]); - - $this->strategy->execute($config['row_details'], $config['job_details']); + ->withArgs( + [ + $config['row_details']->url, + $config['row_details']->is_mobile, + ] + ); + + $this->strategy->execute( $config['row_details'], $config['job_details'] ); } } diff --git a/tests/Unit/inc/Engine/CriticalPath/Admin/Admin/enqueueAdminCpcssHeartbeatScript.php b/tests/Unit/inc/Engine/CriticalPath/Admin/Admin/enqueueAdminCpcssHeartbeatScript.php index 1872e70a61..781ddd90f0 100644 --- a/tests/Unit/inc/Engine/CriticalPath/Admin/Admin/enqueueAdminCpcssHeartbeatScript.php +++ b/tests/Unit/inc/Engine/CriticalPath/Admin/Admin/enqueueAdminCpcssHeartbeatScript.php @@ -4,22 +4,25 @@ use Brain\Monkey\Functions; use Mockery; -use WP_Rocket\Engine\CriticalPath\ProcessorService; use WP_Rocket\Engine\CriticalPath\Admin\Admin; -use WP_Rocket\Tests\Unit\TestCase; +use WP_Rocket\Engine\CriticalPath\ProcessorService; use WP_Rocket\Tests\Unit\inc\Engine\CriticalPath\Admin\AdminTrait; +use WP_Rocket\Tests\Unit\TestCase; /** * Test class covering \WP_Rocket\Engine\CriticalPath\Admin\Admin::enqueue_admin_cpcss_heartbeat_script - * @uses ::rocket_get_constant * - * @group CriticalPath - * @group CriticalPathAdmin + * @uses :rocket_get_constant + * + * @group CriticalPath + * @group CriticalPathAdmin */ -class Test_EnqueueAdminCpcssHeartbeatScript extends TestCase { +class TestEnqueueAdminCpcssHeartbeatScript extends TestCase { use AdminTrait; - public function setUp() : void { + private $admin; + + public function setUp(): void { parent::setUp(); $this->setUpMocks(); diff --git a/tests/Unit/inc/Engine/CriticalPath/CriticalCSS/processHandler.php b/tests/Unit/inc/Engine/CriticalPath/CriticalCSS/processHandler.php index b35c353271..71c548dbf9 100644 --- a/tests/Unit/inc/Engine/CriticalPath/CriticalCSS/processHandler.php +++ b/tests/Unit/inc/Engine/CriticalPath/CriticalCSS/processHandler.php @@ -14,10 +14,10 @@ /** * Test class covering \WP_Rocket\Engine\CriticalPath\CriticalCSS::process_handler * - * @group CriticalCss - * @group CriticalPath + * @group CriticalCss + * @group CriticalPath */ -class Test_ProcessHandler extends FilesystemTestCase { +class TestProcessHandler extends FilesystemTestCase { protected $path_to_test_data = '/inc/Engine/CriticalPath/CriticalCSS/processHandler.php'; private $critical_css; @@ -45,7 +45,9 @@ protected function setUp(): void { Functions\when( 'home_url' )->justReturn( 'http://example.org/' ); Functions\when( 'get_current_blog_id' )->justReturn( 1 ); - $GLOBALS['wpdb'] = $this->wpdb = new wpdb(); + $this->wpdb = new wpdb( 'dbuser', 'dbpassword', 'dbname', 'dbhost' ); + + $GLOBALS['wpdb'] = $this->wpdb; } protected function tearDown(): void { diff --git a/tests/Unit/inc/Engine/CriticalPath/DataManager/getCacheJobId.php b/tests/Unit/inc/Engine/CriticalPath/DataManager/getCacheJobId.php index 4cfeb3cbe2..cb7df674c6 100644 --- a/tests/Unit/inc/Engine/CriticalPath/DataManager/getCacheJobId.php +++ b/tests/Unit/inc/Engine/CriticalPath/DataManager/getCacheJobId.php @@ -9,11 +9,11 @@ /** * Test class covering \WP_Rocket\Engine\CriticalPath\DataManager::get_cache_job_id * - * @group CriticalPath + * @group CriticalPath */ -class Test_GetCacheJobId extends TestCase { +class TestGetCacheJobId extends TestCase { - protected function setUp() : void { + protected function setUp(): void { parent::setUp(); Functions\when( 'get_current_blog_id' )->justReturn( 1 ); @@ -32,15 +32,5 @@ public function testShouldDoExpected( $item_url, $expected, $is_mobile = false ) $actual = $data_manager->get_cache_job_id( $item_url, $is_mobile ); $this->assertSame( $expected, $actual ); - } - - public function nonMultisiteTestData() { - if ( empty( $this->config ) ) { - $this->loadConfig(); - } - - return $this->config['test_data']['non_multisite']; - } - } diff --git a/tests/Unit/inc/Engine/HealthCheck/ActionSchedulerCheck/checkOnUpdateOptions.php b/tests/Unit/inc/Engine/HealthCheck/ActionSchedulerCheck/checkOnUpdateOptions.php index 2e6850f258..c48e4939c0 100644 --- a/tests/Unit/inc/Engine/HealthCheck/ActionSchedulerCheck/checkOnUpdateOptions.php +++ b/tests/Unit/inc/Engine/HealthCheck/ActionSchedulerCheck/checkOnUpdateOptions.php @@ -30,7 +30,7 @@ protected function setUp(): void { $this->as_check = new ActionSchedulerCheck(); - $GLOBALS['wpdb'] = $this->wpdb = new wpdb(); + $GLOBALS['wpdb'] = $this->wpdb = new wpdb( 'dbuser', 'dbpassword', 'dbname', 'dbhost' ); } protected function tearDown(): void { diff --git a/tests/Unit/inc/Engine/HealthCheck/ActionSchedulerCheck/maybeRecreateAsTables.php b/tests/Unit/inc/Engine/HealthCheck/ActionSchedulerCheck/maybeRecreateAsTables.php index 55e0a57db4..6364e9b564 100644 --- a/tests/Unit/inc/Engine/HealthCheck/ActionSchedulerCheck/maybeRecreateAsTables.php +++ b/tests/Unit/inc/Engine/HealthCheck/ActionSchedulerCheck/maybeRecreateAsTables.php @@ -28,7 +28,7 @@ protected function setUp(): void { $this->as_check = new ActionSchedulerCheck(); - $GLOBALS['wpdb'] = $this->wpdb = new wpdb(); + $GLOBALS['wpdb'] = $this->wpdb = new wpdb( 'dbuser', 'dbpassword', 'dbname', 'dbhost' ); } protected function tearDown(): void { diff --git a/tests/Unit/inc/Engine/License/API/PricingClient/getPricingData.php b/tests/Unit/inc/Engine/License/API/PricingClient/getPricingData.php index 72595b52de..50c9defa49 100644 --- a/tests/Unit/inc/Engine/License/API/PricingClient/getPricingData.php +++ b/tests/Unit/inc/Engine/License/API/PricingClient/getPricingData.php @@ -17,6 +17,7 @@ class GetPricingData extends TestCase { * @dataProvider configTestData */ public function testShouldReturnExpected( $config, $expected ) { + $this->stubTranslationFunctions(); $client = new PricingClient(); Functions\expect( 'get_transient' ) @@ -48,7 +49,7 @@ public function testShouldReturnExpected( $config, $expected ) { if ( false !== $config['response'] ) { Functions\expect( 'wp_safe_remote_get' ) ->once() - ->with( PricingClient::PRICING_ENDPOINT ) + ->with( PricingClient::PRICING_ENDPOINT, [] ) ->andReturn( $config['response'] ); if ( diff --git a/tests/Unit/inc/Engine/License/API/UserClient/getUserData.php b/tests/Unit/inc/Engine/License/API/UserClient/getUserData.php index d9e471aae5..ce85508c20 100644 --- a/tests/Unit/inc/Engine/License/API/UserClient/getUserData.php +++ b/tests/Unit/inc/Engine/License/API/UserClient/getUserData.php @@ -14,7 +14,7 @@ * * @group License */ -class GetPricingData extends TestCase { +class GetUserData extends TestCase { use ApiTrait; protected static $api_credentials_config_file = 'license.php'; @@ -22,13 +22,15 @@ class GetPricingData extends TestCase { private $client; private $options; - public static function setUpBeforeClass() : void { + public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); self::pathToApiCredentialsConfigFile( WP_ROCKET_TESTS_DIR . '/../env/local/' ); } public function setUp(): void { + parent::setUp(); + $this->options = Mockery::mock( Options_Data::class ); $this->client = new UserClient( $this->options ); } @@ -37,6 +39,8 @@ public function setUp(): void { * @dataProvider configTestData */ public function testShouldReturnExpected( $config, $expected ) { + $this->stubTranslationFunctions(); + Functions\expect( 'get_transient' ) ->atLeast()->once() ->with( 'wp_rocket_customer_data' ) @@ -94,6 +98,14 @@ public function testShouldReturnExpected( $config, $expected ) { Functions\expect( 'set_transient' )->never(); } + if ( ! $expected ) { + Functions\expect( 'set_transient' )->with( 'wpr_user_information_timeout' )->andReturn(null); + Functions\expect( 'set_transient' )->with( 'wpr_user_information_timeout_active' )->andReturn(null); + } else { + Functions\expect( 'delete_transient' )->with( 'wpr_user_information_timeout' )->andReturn(null); + Functions\expect( 'delete_transient' )->with( 'wpr_user_information_timeout_active' )->andReturn(null); + } + $this->assertEquals( $expected, $this->client->get_user_data() diff --git a/tests/Unit/inc/Engine/Media/AboveTheFold/AJAX/Controller/addLcpData.php b/tests/Unit/inc/Engine/Media/AboveTheFold/AJAX/Controller/addLcpData.php index a2d4ec4166..e02cfea9de 100644 --- a/tests/Unit/inc/Engine/Media/AboveTheFold/AJAX/Controller/addLcpData.php +++ b/tests/Unit/inc/Engine/Media/AboveTheFold/AJAX/Controller/addLcpData.php @@ -8,6 +8,7 @@ use WP_Rocket\Engine\Media\AboveTheFold\Database\Queries\AboveTheFold; use WP_Rocket\Engine\Media\AboveTheFold\AJAX\Controller; use WP_Rocket\Tests\Unit\TestCase; +use Brain\Monkey\Filters; /** * Test class covering WP_Rocket\Engine\Media\AboveTheFold\AJAX\Controller::add_lcp_data @@ -77,7 +78,7 @@ function ( $value ) { } ); - $images_valid_sources = $expected['images_valid_sources']; + $images_valid_sources = $expected['images_valid_sources'] ?? []; Functions\when( 'sanitize_url' )->alias( function( $url ) use ( $images_valid_sources ) { @@ -108,6 +109,15 @@ function( $url ) use ( $images_valid_sources ) { ->with( $expected['message'] ); } + $this->stubWpParseUrl(); + + Filters\expectApplied('rocket_atf_invalid_schemes')->with([ 'chrome-[^:]+://' ])->andReturn([ 'chrome-[^:]+://' ]); + + if ( ! empty( $config['filetype'] ) ) { + Functions\when('get_allowed_mime_types')->justReturn( $config['allowed_mime_types'] ); + Functions\when('wp_check_filetype')->justReturn( $config['filetype'] ); + } + $this->controller->add_lcp_data(); } } diff --git a/tests/Unit/inc/Engine/Optimization/GoogleFonts/Subscriber/preconnect.php b/tests/Unit/inc/Engine/Optimization/GoogleFonts/Subscriber/preconnect.php index c4ea54015b..5cf9476e1e 100644 --- a/tests/Unit/inc/Engine/Optimization/GoogleFonts/Subscriber/preconnect.php +++ b/tests/Unit/inc/Engine/Optimization/GoogleFonts/Subscriber/preconnect.php @@ -4,27 +4,30 @@ use Mockery; use Brain\Monkey\Functions; -use WPMedia\PHPUnit\Unit\TestCase; use WP_Rocket\Admin\Options_Data; use WP_Rocket\Engine\Optimization\GoogleFonts\Combine; use WP_Rocket\Engine\Optimization\GoogleFonts\CombineV2; use WP_Rocket\Engine\Optimization\GoogleFonts\Subscriber; +use WP_Rocket\Tests\Unit\TestCase; /** * Test class covering \WP_Rocket\Engine\Optimization\GoogleFonts\Subscriber::preconnect + * * @group GoogleFonts */ class Test_Preconnect extends TestCase { private $options; private $subscriber; - public function setUp() : void { + public function setUp(): void { + parent::setUp(); + $this->options = Mockery::mock( Options_Data::class ); $this->subscriber = new Subscriber( Mockery::mock( Combine::class ), Mockery::mock( CombineV2::class ), $this->options ); } /** - * @dataProvider providerTestData + * @dataProvider configTestData */ public function testShouldReturnExpectedArray( $bypass, $option_value, $urls, $relation_type, $user_logged_in, $cache_logged_user, $expected ) { Functions\when( 'rocket_bypass' )->justReturn( $bypass ); @@ -35,12 +38,12 @@ public function testShouldReturnExpectedArray( $bypass, $option_value, $urls, $r ->once() ->andReturn( $option_value ); - if ( $user_logged_in ) { - $this->options->shouldReceive( 'get' ) - ->once() - ->with( 'cache_logged_user', 0 ) - ->andReturn( $cache_logged_user ); - } + if ( $user_logged_in ) { + $this->options->shouldReceive( 'get' ) + ->once() + ->with( 'cache_logged_user', 0 ) + ->andReturn( $cache_logged_user ); + } Functions\when( 'is_user_logged_in' )->justReturn( $user_logged_in ); } else { @@ -48,14 +51,9 @@ public function testShouldReturnExpectedArray( $bypass, $option_value, $urls, $r ->never(); } - $this->assertSame( $expected, $this->subscriber->preconnect( $urls, $relation_type ) ); } - - public function providerTestData() { - return $this->getTestData( __DIR__, 'preconnect' ); - } } diff --git a/tests/Unit/inc/Engine/Optimization/Minify/CSS/AdminSubscriber/onUpdate.php b/tests/Unit/inc/Engine/Optimization/Minify/CSS/AdminSubscriber/onUpdate.php index a9cf7679ec..75c772c49c 100644 --- a/tests/Unit/inc/Engine/Optimization/Minify/CSS/AdminSubscriber/onUpdate.php +++ b/tests/Unit/inc/Engine/Optimization/Minify/CSS/AdminSubscriber/onUpdate.php @@ -3,40 +3,37 @@ namespace WP_Rocket\Tests\Unit\inc\Engine\Optimization\Minify\CSS\AdminSubscriber; use Brain\Monkey\Functions; -use Mockery; -use WP_Filesystem_Direct; -use WP_Rocket\Admin\Options_Data; use WP_Rocket\Engine\Optimization\Minify\CSS\AdminSubscriber; -use WP_Rocket\Engine\Optimization\Minify\ProcessorInterface; use WP_Rocket\Tests\Unit\TestCase; -use function Brain\Monkey\Functions; - /** * Test class covering \WP_Rocket\Engine\Optimization\Minify\CSS\AdminSubscriber::on_update + * + * @group AdminOnly + * @group Minify */ -class Test_onUpdate extends TestCase { +class TestOnUpdate extends TestCase { + /** + * @var AdminSubscriber + */ + protected $subscriber; - /** - * @var AdminSubscriber - */ - protected $subscriber; + public function setUp(): void { + parent::setUp(); - public function set_up() { - parent::set_up(); - $this->subscriber = new AdminSubscriber(); - } + $this->subscriber = new AdminSubscriber(); + } - /** - * @dataProvider configTestData - */ - public function testShouldDoAsExpected( $config, $expected ) - { - if($expected) { - Functions\expect('rocket_clean_domain'); - }else { - Functions\expect('rocket_clean_domain')->never(); + /** + * @dataProvider configTestData + */ + public function testShouldDoAsExpected( $config, $expected ) { + if ( $expected ) { + Functions\expect( 'rocket_clean_domain' ); + } else { + Functions\expect( 'rocket_clean_domain' )->never(); } - $this->subscriber->on_update('3.15', $config['old_version']); - } + + $this->subscriber->on_update( '3.15', $config['old_version'] ); + } } diff --git a/tests/Unit/inc/Engine/Optimization/RUCSS/Admin/Database/dropResourcesTable.php b/tests/Unit/inc/Engine/Optimization/RUCSS/Admin/Database/dropResourcesTable.php index 549c3cc052..3e82c62031 100644 --- a/tests/Unit/inc/Engine/Optimization/RUCSS/Admin/Database/dropResourcesTable.php +++ b/tests/Unit/inc/Engine/Optimization/RUCSS/Admin/Database/dropResourcesTable.php @@ -31,7 +31,7 @@ protected function setUp(): void { return; } - $GLOBALS['wpdb'] = new wpdb(); + $GLOBALS['wpdb'] = new wpdb( 'dbuser', 'dbpassword', 'dbname', 'dbhost' ); $this->usedCSS = $this->getMockBuilder( UsedCSS::class ) ->disableOriginalConstructor() diff --git a/tests/Unit/inc/Engine/Optimization/RUCSS/Controller/UsedCSS/UsedCSSTrait.php b/tests/Unit/inc/Engine/Optimization/RUCSS/Controller/UsedCSS/UsedCSSTrait.php deleted file mode 100644 index a0bf9b4c59..0000000000 --- a/tests/Unit/inc/Engine/Optimization/RUCSS/Controller/UsedCSS/UsedCSSTrait.php +++ /dev/null @@ -1,88 +0,0 @@ -options = Mockery::mock(Options_Data::class); - $this->used_css_query = $this->createMock(UsedCSS_Query::class); - $this->api = Mockery::mock(APIClient::class); - $this->queue = Mockery::mock(QueueInterface::class); - $this->data_manager = Mockery::mock(DataManager::class); - $this->filesystem = Mockery::mock(Filesystem::class); - $this->database = Mockery::mock(Database::class); - $this->context = Mockery::mock(ContextInterface::class); - $this->optimisedContext = Mockery::mock(ContextInterface::class); - $this->strategy_factory = Mockery::mock(StrategyFactory::class); - $this->clock = Mockery::mock(WPRClock::class); - - $this->usedcss = new UsedCSS($this->options, $this->used_css_query, $this->api, $this->queue, $this->data_manager, $this->filesystem, $this->context, $this->optimisedContext, $this->strategy_factory, $this->clock); - $this->set_logger($this->usedcss); - } -} diff --git a/tests/Unit/inc/Engine/Plugin/InformationSubscriber/addPluginsToResult.php b/tests/Unit/inc/Engine/Plugin/InformationSubscriber/addPluginsToResult.php index 24eb36b5fe..217a58bb8c 100644 --- a/tests/Unit/inc/Engine/Plugin/InformationSubscriber/addPluginsToResult.php +++ b/tests/Unit/inc/Engine/Plugin/InformationSubscriber/addPluginsToResult.php @@ -15,6 +15,8 @@ class TestAddPluginsToResult extends TestCase { private $subscriber; protected function setUp(): void { + parent::setUp(); + $this->subscriber = new InformationSubscriber( [ 'plugin_file' => 'wp-rocket/wp-rocket.php', diff --git a/tests/Unit/inc/Engine/Preload/Cron/Subscriber/addInterval.php b/tests/Unit/inc/Engine/Preload/Cron/Subscriber/addInterval.php index f522b207bf..9725e829a1 100644 --- a/tests/Unit/inc/Engine/Preload/Cron/Subscriber/addInterval.php +++ b/tests/Unit/inc/Engine/Preload/Cron/Subscriber/addInterval.php @@ -2,14 +2,13 @@ namespace WP_Rocket\Tests\Unit\inc\Engine\Preload\Cron\Subscriber; +use Brain\Monkey\Filters; use Mockery; -use WP_Rocket\Engine\Common\Queue\PreloadQueueRunner; use WP_Rocket\Engine\Preload\Admin\Settings; use WP_Rocket\Engine\Preload\Controller\PreloadUrl; use WP_Rocket\Engine\Preload\Cron\Subscriber; use WP_Rocket\Engine\Preload\Database\Queries\Cache; use WP_Rocket\Tests\Unit\TestCase; -use Brain\Monkey\Filters; /** * Test class covering \WP_Rocket\Engine\Preload\Cron\Subscriber::add_interval @@ -17,39 +16,41 @@ * @group Cron * @group Preload */ -class Test_AddInterval extends TestCase -{ - protected $subscriber; - protected $query; - protected $settings; - protected $controller; - protected $queue_runner; - - protected function setUp(): void - { +class TestAddInterval extends TestCase { + private $subscriber; + private $query; + private $settings; + private $controller; + + protected function setUp(): void { parent::setUp(); - $this->query = $this->createMock(Cache::class); - $this->settings = Mockery::mock(Settings::class); - $this->controller = Mockery::mock(PreloadUrl::class); - $this->queue_runner = Mockery::mock(PreloadQueueRunner::class); - $this->subscriber = new Subscriber($this->settings, $this->query, $this->controller, $this->queue_runner); + $this->query = $this->createMock( Cache::class ); + $this->settings = Mockery::mock( Settings::class ); + $this->controller = Mockery::mock( PreloadUrl::class ); + $this->subscriber = new Subscriber( $this->settings, $this->query, $this->controller ); } /** * @dataProvider configTestData */ - public function testShouldDoAsExpected($config, $expected) { + public function testShouldDoAsExpected( $config, $expected ) { $this->stubTranslationFunctions(); - $this->settings->expects()->is_enabled()->andReturn($config['is_enabled']); - $this->assertSame($expected, $this->subscriber->add_interval($config['schedules'])); + $this->settings->expects()->is_enabled()->andReturn( $config['is_enabled'] ); + + $this->assertSame( + $expected, + $this->subscriber->add_interval( $config['schedules'] ) + ); } - public function configureInterval($config) { - if(! $config['is_enabled'] ) { + public function configureInterval( $config ) { + if( ! $config['is_enabled'] ) { return; } - Filters\expectApplied('rocket_preload_pending_jobs_cron_interval')->with()->andReturn($config['filtered_interval']); + + Filters\expectApplied( 'rocket_preload_pending_jobs_cron_interval' ) + ->andReturn( $config['filtered_interval'] ); } } diff --git a/tests/Unit/inc/Engine/Preload/Cron/Subscriber/scheduleCleanNotCommonlyUsedRows.php b/tests/Unit/inc/Engine/Preload/Cron/Subscriber/scheduleCleanNotCommonlyUsedRows.php index 571d0af111..3ea3e2c751 100644 --- a/tests/Unit/inc/Engine/Preload/Cron/Subscriber/scheduleCleanNotCommonlyUsedRows.php +++ b/tests/Unit/inc/Engine/Preload/Cron/Subscriber/scheduleCleanNotCommonlyUsedRows.php @@ -4,7 +4,6 @@ use Brain\Monkey\Functions; use Mockery; -use WP_Rocket\Engine\Common\Queue\PreloadQueueRunner; use WP_Rocket\Engine\Preload\Admin\Settings; use WP_Rocket\Engine\Preload\Controller\PreloadUrl; use WP_Rocket\Engine\Preload\Cron\Subscriber; @@ -17,28 +16,25 @@ * @group Cron * @group Preload */ -class Test_ScheduleCleanNotCommonlyUsedRows extends TestCase { +class TestScheduleCleanNotCommonlyUsedRows extends TestCase { protected $subscriber; protected $query; protected $settings; protected $controller; - protected $queue_runner; - protected function setUp(): void - { + protected function setUp(): void { parent::setUp(); - $this->query = $this->createMock(Cache::class); - $this->settings = Mockery::mock(Settings::class); - $this->controller = Mockery::mock(PreloadUrl::class); - $this->queue_runner = Mockery::mock(PreloadQueueRunner::class); - $this->subscriber = new Subscriber($this->settings, $this->query, $this->controller, $this->queue_runner); + $this->query = $this->createMock( Cache::class ); + $this->settings = Mockery::mock( Settings::class ); + $this->controller = Mockery::mock( PreloadUrl::class ); + $this->subscriber = new Subscriber( $this->settings, $this->query, $this->controller ); } /** * @dataProvider configTestData */ - public function testShouldDoAsExpected($config) { + public function testShouldDoAsExpected( $config ) { Functions\expect( 'wp_next_scheduled' ) ->once() ->with( 'rocket_preload_clean_rows_time_event' ) @@ -47,17 +43,17 @@ public function testShouldDoAsExpected($config) { $old_time = time() + 10 * MINUTE_IN_SECONDS; if ( ! $config['has_next_schedule'] ) { - Functions\expect('wp_schedule_event') + Functions\expect( 'wp_schedule_event' ) ->once() ->with( Mockery::on(function ($date) use ($old_time) { - return $date >= $old_time && $date <= time() + 10 * MINUTE_IN_SECONDS; - }), + return $date >= $old_time && $date <= time() + 10 * MINUTE_IN_SECONDS; + } ), 'weekly', 'rocket_preload_clean_rows_time_event' ); } else { - Functions\expect('wp_schedule_event')->never(); + Functions\expect( 'wp_schedule_event' )->never(); } $this->subscriber->schedule_clean_not_commonly_used_rows(); diff --git a/tests/Unit/inc/Engine/Preload/Cron/Subscriber/schedulePendingJobs.php b/tests/Unit/inc/Engine/Preload/Cron/Subscriber/schedulePendingJobs.php index cd2ab626f8..634555552d 100644 --- a/tests/Unit/inc/Engine/Preload/Cron/Subscriber/schedulePendingJobs.php +++ b/tests/Unit/inc/Engine/Preload/Cron/Subscriber/schedulePendingJobs.php @@ -2,14 +2,13 @@ namespace WP_Rocket\Tests\Unit\inc\Engine\Preload\Cron\Subscriber; +use Brain\Monkey\Functions; use Mockery; -use WP_Rocket\Engine\Common\Queue\PreloadQueueRunner; use WP_Rocket\Engine\Preload\Admin\Settings; use WP_Rocket\Engine\Preload\Controller\PreloadUrl; use WP_Rocket\Engine\Preload\Cron\Subscriber; use WP_Rocket\Engine\Preload\Database\Queries\Cache; use WP_Rocket\Tests\Unit\TestCase; -use Brain\Monkey\Functions; /** * Test class covering \WP_Rocket\Engine\Preload\Cron\Subscriber::schedule_pending_jobs @@ -17,29 +16,25 @@ * @group Cron * @group Preload */ -class Test_SchedulePendingJobs extends TestCase -{ +class TestSchedulePendingJobs extends TestCase { protected $subscriber; protected $query; protected $settings; protected $controller; - protected $queue_runner; - protected function setUp(): void - { + protected function setUp(): void { parent::setUp(); - $this->query = $this->createMock(Cache::class); - $this->settings = Mockery::mock(Settings::class); - $this->controller = Mockery::mock(PreloadUrl::class); - $this->queue_runner = Mockery::mock(PreloadQueueRunner::class); - $this->subscriber = new Subscriber($this->settings, $this->query, $this->controller, $this->queue_runner); + $this->query = $this->createMock( Cache::class ); + $this->settings = Mockery::mock( Settings::class ); + $this->controller = Mockery::mock( PreloadUrl::class ); + $this->subscriber = new Subscriber( $this->settings, $this->query, $this->controller ); } /** * @dataProvider configTestData */ - public function testShouldDoAsExpected($config) { + public function testShouldDoAsExpected( $config ) { $this->settings->shouldReceive('is_enabled')->andReturn($config['is_enabled'])->atLeast()->once(); $this->configureCheckNextSchedule($config); diff --git a/tests/Unit/inc/Engine/Preload/Cron/Subscriber/scheduleRevertOldFailedRows.php b/tests/Unit/inc/Engine/Preload/Cron/Subscriber/scheduleRevertOldFailedRows.php index 6aa240013c..3128e503ea 100644 --- a/tests/Unit/inc/Engine/Preload/Cron/Subscriber/scheduleRevertOldFailedRows.php +++ b/tests/Unit/inc/Engine/Preload/Cron/Subscriber/scheduleRevertOldFailedRows.php @@ -2,7 +2,6 @@ namespace WP_Rocket\Tests\Unit\inc\Engine\Preload\Cron\Subscriber; -use WP_Rocket\Engine\Common\Queue\PreloadQueueRunner; use WP_Rocket\Engine\Preload\Admin\Settings; use WP_Rocket\Engine\Preload\Controller\PreloadUrl; use WP_Rocket\Engine\Preload\Cron\Subscriber; diff --git a/tests/Unit/inc/ThirdParty/Hostings/HostSubscriberFactory/getSubscriber.php b/tests/Unit/inc/ThirdParty/Hostings/HostSubscriberFactory/getSubscriber.php index 06b9b82df1..b7d9389632 100644 --- a/tests/Unit/inc/ThirdParty/Hostings/HostSubscriberFactory/getSubscriber.php +++ b/tests/Unit/inc/ThirdParty/Hostings/HostSubscriberFactory/getSubscriber.php @@ -2,28 +2,22 @@ namespace WP_Rocket\Tests\Unit\inc\ThirdParty\Hostings\HostSubscriberFactory; -use Mockery; -use WP_Rocket\Engine\Cache\AdminSubscriber; -use WP_Rocket\Event_Management\Event_Manager; use WP_Rocket\ThirdParty\Hostings\HostSubscriberFactory; use WP_Rocket\Tests\Unit\TestCase; /** * Test class covering \WP_Rocket\ThirdParty\Hostings\HostSubscriberFactory::get_subscriber * - * @group Hostings - * @group ThirdParty + * @group Hostings + * @group ThirdParty */ -class Test_GetSubscriber extends TestCase { +class TestGetSubscriber extends TestCase { private $factory; protected function setUp(): void { parent::setUp(); - $this->factory = new HostSubscriberFactory( - Mockery::mock( AdminSubscriber::class ), - Mockery::mock( Event_Manager::class ) - ); + $this->factory = new HostSubscriberFactory(); } protected function tearDown(): void { @@ -55,6 +49,9 @@ public function testShouldReturnSubscriber( $host, $expected ) { break; } - $this->assertInstanceOf( $expected, $this->factory->get_subscriber()); + $this->assertInstanceOf( + $expected, + $this->factory->get_subscriber() + ); } } diff --git a/tests/Unit/inc/ThirdParty/Themes/Divi/handleSaveTemplate.php b/tests/Unit/inc/ThirdParty/Themes/Divi/handleSaveTemplate.php index 87ecc8ea6d..966f16e9a0 100644 --- a/tests/Unit/inc/ThirdParty/Themes/Divi/handleSaveTemplate.php +++ b/tests/Unit/inc/ThirdParty/Themes/Divi/handleSaveTemplate.php @@ -28,7 +28,7 @@ public static function setUpBeforeClass(): void { protected function setUp(): void { parent::setUp(); - $GLOBALS['wpdb'] = $this->wpdb = new wpdb(); + $GLOBALS['wpdb'] = $this->wpdb = new wpdb( 'dbuser', 'dbpassword', 'dbname', 'dbhost' ); } protected function tearDown(): void {