From a53ae5c0a038f71c19ad8f1bddb9cfbdfe8ffcd7 Mon Sep 17 00:00:00 2001 From: glo5363 Date: Thu, 12 Jan 2023 19:02:34 +0530 Subject: [PATCH 01/27] #AC-7583::Stores->Configuration page errors when enabled Fastly- updated zend_http with laminas_http --- Controller/Adminhtml/FastlyCdn/Purge/All.php | 3 +- .../Adminhtml/FastlyCdn/Purge/Quick.php | 15 +- Model/Api.php | 216 +++++++++++------- Model/Config/ConfigRewrite.php | 3 +- Model/Layout/LayoutPlugin.php | 2 +- Model/Notification.php | 28 ++- Model/PurgeCache.php | 4 +- Model/Statistic.php | 58 +++-- Observer/FlushAllCacheObserver.php | 3 +- Observer/InvalidateVarnishObserver.php | 3 +- 10 files changed, 212 insertions(+), 123 deletions(-) diff --git a/Controller/Adminhtml/FastlyCdn/Purge/All.php b/Controller/Adminhtml/FastlyCdn/Purge/All.php index 343134b0..506ed064 100644 --- a/Controller/Adminhtml/FastlyCdn/Purge/All.php +++ b/Controller/Adminhtml/FastlyCdn/Purge/All.php @@ -21,6 +21,7 @@ namespace Fastly\Cdn\Controller\Adminhtml\FastlyCdn\Purge; use Fastly\Cdn\Model\Api; +use Laminas\Uri\Exception\ExceptionInterface as UriException; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\App\Cache\Manager; @@ -64,7 +65,7 @@ public function __construct( * Should be used when "Preserve static assets on purge" is enabled. * * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface - * @throws \Zend_Uri_Exception + * @throws UriException */ public function execute() { diff --git a/Controller/Adminhtml/FastlyCdn/Purge/Quick.php b/Controller/Adminhtml/FastlyCdn/Purge/Quick.php index de47aabb..8507c938 100644 --- a/Controller/Adminhtml/FastlyCdn/Purge/Quick.php +++ b/Controller/Adminhtml/FastlyCdn/Purge/Quick.php @@ -22,6 +22,9 @@ use Fastly\Cdn\Model\Config; use Fastly\Cdn\Model\PurgeCache; +use Laminas\Uri\Exception\ExceptionInterface as UriException; +use Laminas\Uri\UriFactory; +use Laminas\Uri\Uri; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\Exception\LocalizedException; @@ -82,10 +85,10 @@ public function execute() // check if url is given $url = $this->getRequest()->getParam('quick_purge_url', false); - $zendUri = \Zend_Uri::factory($url); - $host = $zendUri->getHost(); - $scheme = $zendUri->getScheme(); - $path = $zendUri->getPath(); + $laminasUri = UriFactory::factory($url); + $host = $laminasUri->getHost(); + $scheme = $laminasUri->getScheme(); + $path = $laminasUri->getPath(); // check if host is one of magento's if (!$this->isHostInDomainList($host)) { @@ -122,7 +125,7 @@ public function execute() * * @param $host * @return bool - * @throws \Zend_Uri_Exception + * @throws UriException */ private function isHostInDomainList($host) { @@ -139,7 +142,7 @@ private function isHostInDomainList($host) /** @var \Magento\Store\Model\Store $store */ foreach ($urlTypes as $urlType) { foreach ($secureScheme as $scheme) { - $shopHost = \Zend_Uri::factory($store->getBaseUrl($urlType, $scheme))->getHost(); + $shopHost = UriFactory::factory($store->getBaseUrl($urlType, $scheme))->getHost(); if ($host === $shopHost) { return true; } diff --git a/Model/Api.php b/Model/Api.php index 5d34c3c5..cb538255 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -20,6 +20,11 @@ */ namespace Fastly\Cdn\Model; +use Laminas\Http\Request; +use Laminas\Http\Response; +use Laminas\Uri\Exception\ExceptionInterface as UriException; +use Laminas\Uri\UriFactory; +use Laminas\Uri\Uri; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\HTTP\Adapter\CurlFactory; use Magento\Framework\Cache\InvalidateLogger; @@ -36,12 +41,12 @@ */ class Api { - const FASTLY_HEADER_AUTH = 'Fastly-Key'; - const FASTLY_HEADER_TOKEN = 'X-Purge-Token'; - const FASTLY_HEADER_SOFT_PURGE = 'Fastly-Soft-Purge'; - const PURGE_TIMEOUT = 10; - const PURGE_TOKEN_LIFETIME = 30; - const FASTLY_MAX_HEADER_KEY_SIZE = 256; + public const FASTLY_HEADER_AUTH = 'Fastly-Key'; + public const FASTLY_HEADER_TOKEN = 'X-Purge-Token'; + public const FASTLY_HEADER_SOFT_PURGE = 'Fastly-Soft-Purge'; + public const PURGE_TIMEOUT = 10; + public const PURGE_TOKEN_LIFETIME = 30; + public const FASTLY_MAX_HEADER_KEY_SIZE = 256; /** * @var Config @@ -153,7 +158,7 @@ private function _getWafEndpoint() * * @param $url * @return \Magento\Framework\Controller\Result\Json - * @throws \Zend_Uri_Exception + * @throws UriException */ public function cleanUrl($url) { @@ -175,7 +180,7 @@ public function cleanUrl($url) * * @param $keys * @return bool|\Magento\Framework\Controller\Result\Json - * @throws \Zend_Uri_Exception + * @throws UriException */ public function cleanBySurrogateKey($keys) { @@ -200,7 +205,7 @@ public function cleanBySurrogateKey($keys) foreach ($collection as $keys) { $payload = json_encode(['surrogate_keys' => $keys]); - $result = $this->_purge($uri, null, \Zend_Http_Client::POST, $payload); + $result = $this->_purge($uri, null, Request::METHOD_POST, $payload); if ($result['status']) { foreach ($keys as $key) { $this->logger->execute('surrogate key: ' . $key); @@ -232,7 +237,7 @@ public function cleanBySurrogateKey($keys) * Purge all of Fastly's CDN content. Can be called only once per request * * @return bool|\Magento\Framework\Controller\Result\Json - * @throws \Zend_Uri_Exception + * @throws UriException */ public function cleanAll() { @@ -276,17 +281,17 @@ public function cleanAll() * @param string $method * @param null $payload * @return \Magento\Framework\Controller\Result\Json - * @throws \Zend_Uri_Exception + * @throws UriException */ - private function _purge($uri, $type, $method = \Zend_Http_Client::POST, $payload = null) + private function _purge($uri, $type, $method = Request::METHOD_POST, $payload = null) { if ($method == 'PURGE') { // create purge token $expiration = time() + self::PURGE_TOKEN_LIFETIME; - $zendUri = \Zend_Uri::factory($uri); - $path = $zendUri->getPath(); + $laminasUri = UriFactory::factory($uri); + $path = $laminasUri->getPath(); $stringToSign = $path . $expiration; $signature = hash_hmac('sha1', $stringToSign, $this->config->getServiceId()); $token = $expiration . '_' . urlencode($signature); @@ -316,8 +321,8 @@ private function _purge($uri, $type, $method = \Zend_Http_Client::POST, $payload } $client->write($method, $uri, '1.1', $headers, $payload); $responseBody = $client->read(); - $responseCode = \Zend_Http_Response::extractCode($responseBody); - $responseMessage = \Zend_Http_Response::extractMessage($responseBody); + $responseCode = $this->extractCodeFromResponse($responseBody); + $responseMessage = $this->extractMessageFromResponse($responseBody); $client->close(); // check response @@ -379,7 +384,7 @@ public function checkServiceDetails($test = false, $serviceId = null, $apiKey = $result = $this->_fetch($uri); } else { $uri = $this->config->getApiEndpoint() . 'service/' . rawurlencode($serviceId); - $result = $this->_fetch($uri, \Zend_Http_Client::GET, null, true, $apiKey); + $result = $this->_fetch($uri, Request::METHOD_GET, null, true, $apiKey); } if (!$result) { @@ -399,7 +404,7 @@ public function checkServiceDetails($test = false, $serviceId = null, $apiKey = public function cloneVersion($curVersion) { $url = $this->_getApiServiceUri() . 'version/'.rawurlencode($curVersion).'/clone'; - $result = $this->_fetch($url, \Zend_Http_Client::PUT); + $result = $this->_fetch($url, Request::METHOD_PUT); if (!$result) { throw new LocalizedException(__('Failed to clone active version.')); @@ -419,7 +424,7 @@ public function cloneVersion($curVersion) public function addComment($version, $comment) { $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version); - $result = $this->_fetch($url, \Zend_Http_Client::PUT, $comment); + $result = $this->_fetch($url, Request::METHOD_PUT, $comment); return $result; } @@ -535,9 +540,9 @@ public function uploadSnippet($version, array $snippet) $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/snippet'; if (!$checkIfExists) { - $verb = \Zend_Http_Client::POST; + $verb = Request::METHOD_POST; } else { - $verb = \Zend_Http_Client::PUT; + $verb = Request::METHOD_PUT; if (!isset($snippet['dynamic']) || $snippet['dynamic'] != 1) { $url .= '/'.rawurlencode($snippetName); unset($snippet['name'], $snippet['type'], $snippet['dynamic']); @@ -565,7 +570,7 @@ public function uploadSnippet($version, array $snippet) public function getSnippet($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/snippet/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -580,7 +585,7 @@ public function getSnippet($version, $name) public function updateSnippet(array $snippet) { $url = $this->_getApiServiceUri(). 'snippet' . '/'.rawurlencode($snippet['name']); - $result = $this->_fetch($url, \Zend_Http_Client::PUT, $snippet); + $result = $this->_fetch($url, Request::METHOD_PUT, $snippet); if (!$result) { throw new LocalizedException(__($this->errorMessage)); @@ -601,7 +606,7 @@ public function updateSnippet(array $snippet) public function hasSnippet($version, $name) { $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/snippet/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::GET, '', false, null, false); + $result = $this->_fetch($url, Request::METHOD_GET, '', false, null, false); if ($result == false) { return false; @@ -620,7 +625,7 @@ public function hasSnippet($version, $name) public function removeSnippet($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/snippet/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::DELETE); + $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; } @@ -637,9 +642,9 @@ public function createCondition($version, array $condition) $checkIfExists = $this->getCondition($version, $condition['name']); $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/condition'; if (!$checkIfExists) { - $verb = \Zend_Http_Client::POST; + $verb = Request::METHOD_POST; } else { - $verb = \Zend_Http_Client::PUT; + $verb = Request::METHOD_PUT; $url .= '/'.rawurlencode($condition['name']); } @@ -663,7 +668,7 @@ public function removeCondition($version, string $conditionName) { $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/condition/' . $conditionName; - return $this->_fetch($url, \Zend_Http_Client::DELETE); + return $this->_fetch($url, Request::METHOD_DELETE); } /** @@ -677,7 +682,7 @@ public function removeCondition($version, string $conditionName) public function getCondition($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/condition/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -696,9 +701,9 @@ public function createHeader($version, array $condition) $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/header'; if ($checkIfExists === false) { - $verb = \Zend_Http_Client::POST; + $verb = Request::METHOD_POST; } else { - $verb = \Zend_Http_Client::PUT; + $verb = Request::METHOD_PUT; $url .= '/'.rawurlencode($condition['name']); } @@ -718,7 +723,7 @@ public function createHeader($version, array $condition) public function getHeader($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/header/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -736,9 +741,9 @@ public function createResponse($version, array $response) $checkIfExists = $this->getResponse($version, $response['name']); $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/response_object'; if (!$checkIfExists) { - $verb = \Zend_Http_Client::POST; + $verb = Request::METHOD_POST; } else { - $verb = \Zend_Http_Client::PUT; + $verb = Request::METHOD_PUT; $url .= '/'.rawurlencode($response['name']); } @@ -759,7 +764,7 @@ public function removeResponse($version, string $responseName) { $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/response_object/' . $responseName; - return $this->_fetch($url, \Zend_Http_Client::DELETE); + return $this->_fetch($url, Request::METHOD_DELETE); } /** @@ -773,7 +778,7 @@ public function removeResponse($version, string $responseName) public function getResponse($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/response_object/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -789,9 +794,9 @@ public function createRequest($version, $request) $checkIfExists = $this->getRequest($version, $request['name']); $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/request_settings'; if (!$checkIfExists) { - $verb = \Zend_Http_Client::POST; + $verb = Request::METHOD_POST; } else { - $verb = \Zend_Http_Client::PUT; + $verb = Request::METHOD_PUT; $url .= '/'.rawurlencode($request['name']); } @@ -814,7 +819,7 @@ public function createRequest($version, $request) public function getRequest($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/request_settings/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::GET, '', false, null, false); + $result = $this->_fetch($url, Request::METHOD_GET, '', false, null, false); return $result; } @@ -827,7 +832,7 @@ public function getRequest($version, $name) public function getAllConditions($version) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/condition'; - $result = $this->_fetch($url, \Zend_Http_Client::GET, '', false, null, false); + $result = $this->_fetch($url, Request::METHOD_GET, '', false, null, false); return $result; } @@ -840,7 +845,7 @@ public function getAllConditions($version) public function getAllDomains($version) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/domain'; - $result = $this->_fetch($url, \Zend_Http_Client::GET, '', false, null, false); + $result = $this->_fetch($url, Request::METHOD_GET, '', false, null, false); return $result; } @@ -854,7 +859,7 @@ public function getAllDomains($version) public function deleteDomain($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/domain/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::DELETE); + $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; } @@ -868,7 +873,7 @@ public function deleteDomain($version, $name) public function createDomain($version, $data) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/domain'; - $result = $this->_fetch($url, \Zend_Http_Client::POST, $data); + $result = $this->_fetch($url, Request::METHOD_POST, $data); return $result; } @@ -882,7 +887,7 @@ public function createDomain($version, $data) public function deleteRequest($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/request_settings/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::DELETE); + $result = $this->_fetch($url, Request::METHOD_DELETE); if (!$result) { throw new LocalizedException(__('Failed to delete the REQUEST object.')); @@ -899,7 +904,7 @@ public function deleteRequest($version, $name) public function getBackends($version) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/backend'; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -916,7 +921,7 @@ public function getBackends($version) public function configureBackend($params, $version, $old_name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/backend/' . rawurlencode($old_name); - $result = $this->_fetch($url, \Zend_Http_Client::PUT, $params); + $result = $this->_fetch($url, Request::METHOD_PUT, $params); return $result; } @@ -930,7 +935,7 @@ public function configureBackend($params, $version, $old_name) public function createBackend($params, $version) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/backend'; - $result = $this->_fetch($url, \Zend_Http_Client::POST, $params); + $result = $this->_fetch($url, Request::METHOD_POST, $params); return $result; } @@ -944,7 +949,7 @@ public function createBackend($params, $version) public function deleteBackend($name, $version) { $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/backend/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::DELETE); + $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; } @@ -960,7 +965,7 @@ public function getAllLogEndpoints($version) $results = []; foreach ($providers as $type => $providerName) { $url = $this->_getApiServiceUri(). 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type); - $endpoints = $this->_fetch($url, \Zend_Http_Client::GET); + $endpoints = $this->_fetch($url, Request::METHOD_GET); foreach ($endpoints as $endpoint) { $results[] = [ 'label' => "{$endpoint->name} [{$providerName}]", @@ -983,7 +988,7 @@ public function getLogEndpoints($version, $type) $results = []; $providers = $this->helper->getAvailableLogEndpointProviders(); $url = $this->_getApiServiceUri(). 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type); - $endpoints = $this->_fetch($url, \Zend_Http_Client::GET); + $endpoints = $this->_fetch($url, Request::METHOD_GET); foreach ($endpoints as $endpoint) { $results[] = [ 'label' => "{$endpoint->name} [{$providers[$type]}]", @@ -1004,7 +1009,7 @@ public function getLogEndpoints($version, $type) public function getLogEndpoint($version, $type, $name) { $url = $this->_getApiServiceUri(). 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type) . '/' . rawurlencode($name); - return $this->_fetch($url, \Zend_Http_Client::GET); + return $this->_fetch($url, Request::METHOD_GET); } /** @@ -1017,7 +1022,7 @@ public function getLogEndpoint($version, $type, $name) public function createLogEndpoint($version, $type, $params) { $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type); - return $this->_fetch($url, \Zend_Http_Client::POST, $params); + return $this->_fetch($url, Request::METHOD_POST, $params); } /** @@ -1031,7 +1036,7 @@ public function createLogEndpoint($version, $type, $params) public function updateLogEndpoint($version, $type, $params, $oldName) { $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type) . '/' . rawurlencode($oldName); - return $this->_fetch($url, \Zend_Http_Client::PUT, $params); + return $this->_fetch($url, Request::METHOD_PUT, $params); } /** @@ -1073,9 +1078,9 @@ public function sendWebHook($message) $client = $this->curlFactory->create(); $client->addOption(CURLOPT_CONNECTTIMEOUT, 2); $client->addOption(CURLOPT_TIMEOUT, 3); - $client->write(\Zend_Http_Client::POST, $url, '1.1', $headers, $body); + $client->write(Request::METHOD_POST, $url, '1.1', $headers, $body); $response = $client->read(); - $responseCode = \Zend_Http_Response::extractCode($response); + $responseCode = $this->extractCodeFromResponse($response); if ($responseCode != 200) { $this->log->log(100, 'Failed to send message to the following Webhook: '.$url); @@ -1095,7 +1100,7 @@ public function sendWebHook($message) public function createDictionary($version, $params) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/dictionary'; - $result = $this->_fetch($url, \Zend_Http_Client::POST, $params); + $result = $this->_fetch($url, Request::METHOD_POST, $params); return $result; } @@ -1111,7 +1116,7 @@ public function createDictionary($version, $params) public function deleteDictionary($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/dictionary/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::DELETE); + $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; } @@ -1126,7 +1131,7 @@ public function deleteDictionary($version, $name) public function dictionaryItemsList($dictionaryId) { $url = $this->_getApiServiceUri(). 'dictionary/'.rawurlencode($dictionaryId).'/items'; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1142,7 +1147,7 @@ public function dictionaryItemsList($dictionaryId) public function getSingleDictionary($version, $dictionaryName) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/dictionary/' . rawurlencode($dictionaryName); - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1194,7 +1199,7 @@ public function checkAuthDictionaryPopulation($version) public function createDictionaryItems($dictionaryId, $params) { $url = $this->_getApiServiceUri().'dictionary/'.rawurlencode($dictionaryId).'/items'; - $result = $this->_fetch($url, \Zend_Http_Client::PATCH, $params); + $result = $this->_fetch($url, Request::METHOD_PATCH, $params); return $result; } @@ -1209,7 +1214,7 @@ public function createDictionaryItems($dictionaryId, $params) public function getDictionaries($version) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/dictionary'; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1225,7 +1230,7 @@ public function getDictionaries($version) public function deleteDictionaryItem($dictionaryId, $itemKey) { $url = $this->_getApiServiceUri(). 'dictionary/'. rawurlencode($dictionaryId) . '/item/' . rawurlencode($itemKey); - $result = $this->_fetch($url, \Zend_Http_Client::DELETE); + $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; } @@ -1242,7 +1247,7 @@ public function upsertDictionaryItem($dictionaryId, $itemKey, $itemValue) { $body = ['item_value' => $itemValue]; $url = $this->_getApiServiceUri(). 'dictionary/'. rawurlencode($dictionaryId) . '/item/' . rawurlencode($itemKey); - $result = $this->_fetch($url, \Zend_Http_Client::PUT, $body); + $result = $this->_fetch($url, Request::METHOD_PUT, $body); if (!$result) { throw new LocalizedException(__('Failed to create Dictionary item.')); @@ -1259,7 +1264,7 @@ public function upsertDictionaryItem($dictionaryId, $itemKey, $itemValue) public function getSingleAcl($version, $acl) { $url = $this->_getApiServiceUri(). 'version/'. $version . '/acl/' . $acl; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1275,7 +1280,7 @@ public function getSingleAcl($version, $acl) public function createAcl($version, $params) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/acl'; - $result = $this->_fetch($url, \Zend_Http_Client::POST, $params); + $result = $this->_fetch($url, Request::METHOD_POST, $params); return $result; } @@ -1290,7 +1295,7 @@ public function createAcl($version, $params) public function getAcls($version) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/acl'; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1306,7 +1311,7 @@ public function getAcls($version) public function deleteAcl($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/acl/' . rawurlencode($name); - $result = $this->_fetch($url, \Zend_Http_Client::DELETE); + $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; } @@ -1321,7 +1326,7 @@ public function deleteAcl($version, $name) public function aclItemsList($aclId) { $url = $this->_getApiServiceUri() . 'acl/'. rawurlencode($aclId) . '/entries'; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1350,7 +1355,7 @@ public function upsertAclItem($aclId, $itemValue, $negated, $comment = 'Added by } $url = $this->_getApiServiceUri(). 'acl/'. rawurlencode($aclId) . '/entry'; - $result = $this->_fetch($url, \Zend_Http_Client::POST, $body); + $result = $this->_fetch($url, Request::METHOD_POST, $body); return $result; } @@ -1366,7 +1371,7 @@ public function upsertAclItem($aclId, $itemValue, $negated, $comment = 'Added by public function deleteAclItem($aclId, $aclItemId) { $url = $this->_getApiServiceUri(). 'acl/'. rawurlencode($aclId) . '/entry/' . rawurlencode($aclItemId); - $result = $this->_fetch($url, \Zend_Http_Client::DELETE); + $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; } @@ -1396,7 +1401,7 @@ public function updateAclItem($aclId, $aclItemId, $itemValue, $negated, $comment } $url = $this->_getApiServiceUri(). 'acl/'. rawurlencode($aclId) . '/entry/' . rawurlencode($aclItemId); - $result = $this->_fetch($url, \Zend_Http_Client::PATCH, json_encode($body)); + $result = $this->_fetch($url, Request::METHOD_PATCH, json_encode($body)); return $result; } @@ -1431,7 +1436,7 @@ public function queryHistoricStats(array $parameters) public function getGeneratedVcl($version) { $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/generated_vcl'; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1439,7 +1444,7 @@ public function getGeneratedVcl($version) public function getParticularVersion($version) { $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version); - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1453,7 +1458,7 @@ public function getParticularVersion($version) public function checkImageOptimizationStatus() { $url = $this->_getApiServiceUri(). 'dynamic_io_settings'; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1468,7 +1473,7 @@ public function checkImageOptimizationStatus() public function getImageOptimizationDefaultConfigOptions($version) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/io_settings'; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1484,7 +1489,7 @@ public function getImageOptimizationDefaultConfigOptions($version) public function configureImageOptimizationDefaultConfigOptions($params, $version) { $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/io_settings'; - $result = $this->_fetch($url, \Zend_Http_Client::PATCH, $params); + $result = $this->_fetch($url, Request::METHOD_PATCH, $params); return $result; } @@ -1498,7 +1503,7 @@ public function configureImageOptimizationDefaultConfigOptions($params, $version public function getServiceDetails() { $url = $this->_getApiServiceUri() . 'details'; - $result = $this->_fetch($url, \Zend_Http_Client::GET); + $result = $this->_fetch($url, Request::METHOD_GET); return $result; } @@ -1518,7 +1523,7 @@ public function getWafSettings(string $id, bool $includeWafFirewallVersions = fa $url .= '?include=waf_firewall_versions'; } - return $this->_fetch($url, \Zend_Http_Client::GET); + return $this->_fetch($url, Request::METHOD_GET); } public function getLastErrorMessage() @@ -1541,7 +1546,7 @@ public function getLastErrorMessage() */ private function _fetch( $uri, - $method = \Zend_Http_Client::GET, + $method = Request::METHOD_GET, $body = '', $test = false, $testApiKey = null, @@ -1565,20 +1570,20 @@ private function _fetch( // Request method specific header & option changes switch ($method) { - case \Zend_Http_Client::DELETE: - $options[CURLOPT_CUSTOMREQUEST] = \Zend_Http_Client::DELETE; + case Request::METHOD_DELETE: + $options[CURLOPT_CUSTOMREQUEST] = Request::METHOD_DELETE; break; - case \Zend_Http_Client::PUT: + case Request::METHOD_PUT: $headers[] = 'Content-Type: application/x-www-form-urlencoded'; - $options[CURLOPT_CUSTOMREQUEST] = \Zend_Http_Client::PUT; + $options[CURLOPT_CUSTOMREQUEST] = Request::METHOD_PUT; if ($body != '') { $options[CURLOPT_POSTFIELDS] = $body; } break; - case \Zend_Http_Client::PATCH: - $options[CURLOPT_CUSTOMREQUEST] = \Zend_Http_Client::PATCH; + case Request::METHOD_PATCH: + $options[CURLOPT_CUSTOMREQUEST] = Request::METHOD_PATCH; $headers[] = 'Content-Type: text/json'; if ($body != '') { @@ -1598,9 +1603,9 @@ private function _fetch( $client->close(); // Parse response - $responseBody = \Zend_Http_Response::extractBody($response); - $responseCode = \Zend_Http_Response::extractCode($response); - $responseMessage = \Zend_Http_Response::extractMessage($response); + $responseBody = Response::getBody($response); + $responseCode = $this->extractCodeFromResponse($response); + $responseMessage = $this->extractMessageFromResponse($response); // Return error based on response code if ($responseCode == '429') { @@ -1647,4 +1652,39 @@ private function extractErrorDetails($responseBody, $responseMessage) } return $responseMessage; } + + /** + * Extract the response code from a response string + * + * @param string $responseString + * + * @return false|int + */ + private function extractCodeFromResponse(string $responseString) + { + try { + $responseCode = Response::fromString($responseString)->getStatusCode(); + } catch (Throwable $e) { + $responseCode = false; + } + + return $responseCode; + } + + /** + * Extract the response message from a response string + * + * @param string $responseString + * + * @return false|int + */ + private function extractMessageFromResponse(string $responseString) + { + preg_match("|^HTTP/[\d\.x]+ \d+ ([^\r\n]+)|", $responseString, $matches); + if (isset($matches[1])) { + return $matches[1]; + } + + return false; + } } diff --git a/Model/Config/ConfigRewrite.php b/Model/Config/ConfigRewrite.php index 0a4e2238..e278060d 100644 --- a/Model/Config/ConfigRewrite.php +++ b/Model/Config/ConfigRewrite.php @@ -21,6 +21,7 @@ namespace Fastly\Cdn\Model\Config; use Fastly\Cdn\Model\Api; +use Laminas\Uri\Exception\ExceptionInterface as UriException; use Magento\Framework\App\Config\ScopeConfigInterface; /** @@ -58,7 +59,7 @@ public function __construct( * Trigger purge if set * * @param \Magento\Config\Model\Config $subject - * @throws \Zend_Uri_Exception + * @throws UriException */ public function afterSave(\Magento\Config\Model\Config $subject) // @codingStandardsIgnoreLine - unused parameter { diff --git a/Model/Layout/LayoutPlugin.php b/Model/Layout/LayoutPlugin.php index 9a382d98..4b328696 100644 --- a/Model/Layout/LayoutPlugin.php +++ b/Model/Layout/LayoutPlugin.php @@ -73,7 +73,7 @@ public function afterGenerateElements(\Magento\Framework\View\Layout $subject) && $this->config->getType() === Config::FASTLY && $this->config->getTtl()) { // get cache control header $header = $this->response->getHeader('cache-control'); - if (($header instanceof \Zend\Http\Header\HeaderInterface) && ($value = $header->getFieldValue())) { + if (($header instanceof \Laminas\Http\Header\HeaderInterface) && ($value = $header->getFieldValue())) { // append stale values if ($ttl = $this->config->getStaleTtl()) { $value .= ', stale-while-revalidate=' . $ttl; diff --git a/Model/Notification.php b/Model/Notification.php index 6a8958d9..cfa16417 100644 --- a/Model/Notification.php +++ b/Model/Notification.php @@ -20,6 +20,8 @@ */ namespace Fastly\Cdn\Model; +use Laminas\Http\Request; +use Laminas\Http\Response; use Magento\AdminNotification\Model\Feed; use Magento\AdminNotification\Model\InboxFactory; use Magento\Backend\App\ConfigInterface; @@ -46,7 +48,7 @@ class Notification extends Feed /** * Github latest composer data url */ - const CHECK_VERSION_URL = 'https://raw.githubusercontent.com/fastly/fastly-magento2/master/composer.json'; + public const CHECK_VERSION_URL = 'https://raw.githubusercontent.com/fastly/fastly-magento2/master/composer.json'; /** * @var ScopeConfigInterface */ @@ -156,15 +158,15 @@ public function getLastVersion() $url = self::CHECK_VERSION_URL; $client = $this->curlFactory->create(); - $client->write(\Zend_Http_Client::GET, $url, '1.1'); + $client->write(Request::METHOD_GET, $url, '1.1'); $responseBody = $client->read(); $client->close(); - $responseCode = \Zend_Http_Response::extractCode($responseBody); + $responseCode = $this->extractCodeFromResponse($responseBody); if ($responseCode !== 200) { return false; } - $body = \Zend_Http_Response::extractBody($responseBody); + $body = Response::getBody($responseBody); $json = json_decode($body); $version = !empty($json->version) ? $json->version : false; @@ -174,4 +176,22 @@ public function getLastVersion() return false; } } + + /** + * Extract the response code from a response string + * + * @param string $responseString + * + * @return false|int + */ + private function extractCodeFromResponse(string $responseString) + { + try { + $responseCode = Response::fromString($responseString)->getStatusCode(); + } catch (Throwable $e) { + $responseCode = false; + } + + return $responseCode; + } } diff --git a/Model/PurgeCache.php b/Model/PurgeCache.php index 651192c0..64201428 100644 --- a/Model/PurgeCache.php +++ b/Model/PurgeCache.php @@ -20,6 +20,8 @@ */ namespace Fastly\Cdn\Model; +use Laminas\Uri\Exception\ExceptionInterface as UriException; + /** * Class PurgeCache * @@ -53,7 +55,7 @@ public function __construct(Api $api, Config $config) * * @param string $pattern * @return bool - * @throws \Zend_Uri_Exception + * @throws UriException */ public function sendPurgeRequest($pattern = '') { diff --git a/Model/Statistic.php b/Model/Statistic.php index 72c28021..a1b1408c 100644 --- a/Model/Statistic.php +++ b/Model/Statistic.php @@ -21,6 +21,8 @@ namespace Fastly\Cdn\Model; use Fastly\Cdn\Helper\Data; +use Laminas\Http\Request; +use Laminas\Http\Response; use Magento\Directory\Api\CountryInformationAcquirerInterface; use Magento\Directory\Model\CountryFactory; use Magento\Directory\Model\RegionFactory; @@ -48,35 +50,35 @@ class Statistic extends AbstractModel implements IdentityInterface /** * Fastly INSTALLED Flag */ - const FASTLY_INSTALLED_FLAG = 'installed'; + public const FASTLY_INSTALLED_FLAG = 'installed'; /** * Fastly CONFIGURED Flag */ - const FASTLY_CONFIGURED_FLAG = 'configured'; + public const FASTLY_CONFIGURED_FLAG = 'configured'; /** * Fastly NOT_CONFIGURED Flag */ - const FASTLY_NOT_CONFIGURED_FLAG = 'not_configured'; - const FASTLY_VALIDATED_FLAG = 'validated'; - const FASTLY_NON_VALIDATED_FLAG = 'non_validated'; + public const FASTLY_NOT_CONFIGURED_FLAG = 'not_configured'; + public const FASTLY_VALIDATED_FLAG = 'validated'; + public const FASTLY_NON_VALIDATED_FLAG = 'non_validated'; - const FASTLY_CONFIGURATION_FLAG = 'configuration'; - const FASTLY_VALIDATION_FLAG = 'validation'; + public const FASTLY_CONFIGURATION_FLAG = 'configuration'; + public const FASTLY_VALIDATION_FLAG = 'validation'; /** * Fastly upgrade flag */ - const FASTLY_UPGRADE_FLAG = 'upgrade'; - const FASTLY_UPGRADED_FLAG = 'upgraded'; + public const FASTLY_UPGRADE_FLAG = 'upgrade'; + public const FASTLY_UPGRADED_FLAG = 'upgraded'; - const FASTLY_MODULE_NAME = 'Fastly_Cdn'; - const CACHE_TAG = 'fastly_cdn_statistic'; - const FASTLY_GA_TRACKING_ID = 'UA-89025888-1'; - const GA_API_ENDPOINT = 'https://www.google-analytics.com/collect'; - const GA_HITTYPE_PAGEVIEW = 'pageview'; - const GA_HITTYPE_EVENT = 'event'; - const GA_PAGEVIEW_URL = 'http://fastly.com/'; - const GA_FASTLY_SETUP = 'Fastly Setup'; + public const FASTLY_MODULE_NAME = 'Fastly_Cdn'; + public const CACHE_TAG = 'fastly_cdn_statistic'; + public const FASTLY_GA_TRACKING_ID = 'UA-89025888-1'; + public const GA_API_ENDPOINT = 'https://www.google-analytics.com/collect'; + public const GA_HITTYPE_PAGEVIEW = 'pageview'; + public const GA_HITTYPE_EVENT = 'event'; + public const GA_PAGEVIEW_URL = 'http://fastly.com/'; + public const GA_FASTLY_SETUP = 'Fastly Setup'; /** * @var array */ @@ -580,7 +582,7 @@ public function daysFromInstallation() * @param string $uri * @return bool */ - private function sendReqToGA($body = '', $method = \Zend_Http_Client::POST, $uri = self::GA_API_ENDPOINT) + private function sendReqToGA($body = '', $method = Request::METHOD_POST, $uri = self::GA_API_ENDPOINT) { $reqGAData = (array)$this->getGAReqData(); @@ -593,7 +595,7 @@ private function sendReqToGA($body = '', $method = \Zend_Http_Client::POST, $uri $client->addOption(CURLOPT_TIMEOUT, 10); $client->write($method, $uri, '1.1', null, http_build_query($body)); $response = $client->read(); - $responseCode = \Zend_Http_Response::extractCode($response); + $responseCode = $this->extractCodeFromResponse($response); $client->close(); if ($responseCode != '200') { @@ -605,4 +607,22 @@ private function sendReqToGA($body = '', $method = \Zend_Http_Client::POST, $uri return false; } } + + /** + * Extract the response code from a response string + * + * @param string $responseString + * + * @return false|int + */ + private function extractCodeFromResponse(string $responseString) + { + try { + $responseCode = Response::fromString($responseString)->getStatusCode(); + } catch (Throwable $e) { + $responseCode = false; + } + + return $responseCode; + } } diff --git a/Observer/FlushAllCacheObserver.php b/Observer/FlushAllCacheObserver.php index e8800456..7c55c904 100644 --- a/Observer/FlushAllCacheObserver.php +++ b/Observer/FlushAllCacheObserver.php @@ -22,6 +22,7 @@ use Fastly\Cdn\Model\Config; use Fastly\Cdn\Model\PurgeCache; +use Laminas\Uri\Exception\ExceptionInterface as UriException; use Magento\Framework\Event\ObserverInterface; /** @@ -54,7 +55,7 @@ public function __construct(Config $config, PurgeCache $purgeCache) * Flush Fastly CDN cache * * @param \Magento\Framework\Event\Observer $observer - * @throws \Zend_Uri_Exception + * @throws UriException */ public function execute(\Magento\Framework\Event\Observer $observer) // @codingStandardsIgnoreLine - unused parameter { diff --git a/Observer/InvalidateVarnishObserver.php b/Observer/InvalidateVarnishObserver.php index 23c7edd0..a429623d 100644 --- a/Observer/InvalidateVarnishObserver.php +++ b/Observer/InvalidateVarnishObserver.php @@ -23,6 +23,7 @@ use Fastly\Cdn\Helper\CacheTags; use Fastly\Cdn\Model\Config; use Fastly\Cdn\Model\PurgeCache; +use Laminas\Uri\Exception\ExceptionInterface as UriException; use Magento\Framework\Event\ObserverInterface; /** @@ -68,7 +69,7 @@ public function __construct( * If Fastly CDN is enabled it sends one purge request per tag * * @param \Magento\Framework\Event\Observer $observer - * @throws \Zend_Uri_Exception + * @throws UriException */ public function execute(\Magento\Framework\Event\Observer $observer) { From 8e0e9cf19ec0e616dab45c2d77a5693ff0d997ad Mon Sep 17 00:00:00 2001 From: glo5363 Date: Fri, 13 Jan 2023 19:13:39 +0530 Subject: [PATCH 02/27] #AC-7583::Stores->Configuration page errors when enabled Fastly- fixed static call to non-static method --- Model/Notification.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Model/Notification.php b/Model/Notification.php index cfa16417..92bace97 100644 --- a/Model/Notification.php +++ b/Model/Notification.php @@ -166,7 +166,7 @@ public function getLastVersion() if ($responseCode !== 200) { return false; } - $body = Response::getBody($responseBody); + $body = $this->extractBodyFromResponse($responseBody); $json = json_decode($body); $version = !empty($json->version) ? $json->version : false; @@ -194,4 +194,19 @@ private function extractCodeFromResponse(string $responseString) return $responseCode; } + + /** + * Extract the body from a response string + * + * @param string $response_str + * @return string + */ + private function extractBodyFromResponse($response_str) + { + $parts = preg_split('|(?:\r\n){2}|m', $response_str, 2); + if (isset($parts[1])) { + return $parts[1]; + } + return ''; + } } From 8d88f6f4f584e027e03711cd26cdebb21ec19821 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Mon, 16 Jan 2023 11:52:46 +0100 Subject: [PATCH 03/27] Notification class refactored --- Model/Notification.php | 145 +++++++++++++++----------------------- Observer/CheckVersion.php | 2 +- 2 files changed, 56 insertions(+), 91 deletions(-) diff --git a/Model/Notification.php b/Model/Notification.php index 92bace97..0a33d070 100644 --- a/Model/Notification.php +++ b/Model/Notification.php @@ -18,11 +18,12 @@ * @copyright Copyright (c) 2016 Fastly, Inc. (http://www.fastly.com) * @license BSD, see LICENSE_FASTLY_CDN.txt */ + namespace Fastly\Cdn\Model; +use Laminas\Http\ClientFactory; use Laminas\Http\Request; -use Laminas\Http\Response; -use Magento\AdminNotification\Model\Feed; +use Laminas\Http\RequestFactory; use Magento\AdminNotification\Model\InboxFactory; use Magento\Backend\App\ConfigInterface; use Magento\Framework\App\Cache\Manager; @@ -31,7 +32,7 @@ use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\ProductMetadataInterface; use Magento\Framework\Data\Collection\AbstractDb; -use Magento\Framework\HTTP\Adapter\CurlFactory; +use Magento\Framework\Model\AbstractModel; use Magento\Framework\Model\Context; use Magento\Framework\Model\ResourceModel\AbstractResource; use Magento\Framework\Registry; @@ -41,9 +42,8 @@ * Class Notification * * Fastly CDN admin notification for latest version - * @package Fastly\Cdn\Model */ -class Notification extends Feed +class Notification extends AbstractModel { /** * Github latest composer data url @@ -61,55 +61,57 @@ class Notification extends Feed * @var Manager */ private $cacheManager; + /** + * @var ClientFactory + */ + private $clientFactory; + + /** + * @var RequestFactory + */ + private $requestFactory; + + /** + * @var InboxFactory + */ + private $inboxFactory; /** - * Notification constructor. - * * @param Context $context * @param Registry $registry - * @param ConfigInterface $backendConfig - * @param InboxFactory $inboxFactory - * @param CurlFactory $curlFactory - * @param DeploymentConfig $deploymentConfig - * @param ProductMetadataInterface $productMetadata - * @param UrlInterface $urlBuilder * @param ScopeConfigInterface $scopeConfig * @param WriterInterface $configWriter * @param Manager $cacheManager + * @param ClientFactory $clientFactory + * @param RequestFactory $requestFactory + * @param InboxFactory $inboxFactory * @param AbstractResource|null $resource * @param AbstractDb|null $resourceCollection * @param array $data */ public function __construct( - Context $context, - Registry $registry, - ConfigInterface $backendConfig, - InboxFactory $inboxFactory, - CurlFactory $curlFactory, - DeploymentConfig $deploymentConfig, - ProductMetadataInterface $productMetadata, - UrlInterface $urlBuilder, + Context $context, + Registry $registry, ScopeConfigInterface $scopeConfig, - WriterInterface $configWriter, - Manager $cacheManager, - AbstractResource $resource = null, - AbstractDb $resourceCollection = null, - array $data = [] + WriterInterface $configWriter, + Manager $cacheManager, + ClientFactory $clientFactory, + RequestFactory $requestFactory, + InboxFactory $inboxFactory, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, + array $data = [] ) { $this->scopeConfig = $scopeConfig; $this->configWriter = $configWriter; $this->cacheManager = $cacheManager; $this->_logger = $context->getLogger(); - + $this->clientFactory = $clientFactory; + $this->requestFactory = $requestFactory; + $this->inboxFactory = $inboxFactory; parent::__construct( $context, $registry, - $backendConfig, - $inboxFactory, - $curlFactory, - $deploymentConfig, - $productMetadata, - $urlBuilder, $resource, $resourceCollection, $data @@ -117,13 +119,14 @@ public function __construct( } /** - * Check feed for modification + * Check latest version and set inbox notice * - * @param null $currentVersion + * @param string $currentVersion + * @return void */ - public function checkUpdate($currentVersion = null) + public function checkUpdate(string $currentVersion): void { - $lastVersion = (string)$this->getLastVersion(); + $lastVersion = $this->getLastVersion(); if (!$lastVersion || version_compare($lastVersion, $currentVersion, '<=')) { return; @@ -134,14 +137,11 @@ public function checkUpdate($currentVersion = null) if (version_compare($oldValue, $lastVersion, '<')) { $this->configWriter->save($versionPath, $lastVersion); - - // save last version in db, and notify only if newly fetched last version is greater than stored version - $inboxFactory = $this->_inboxFactory; - $inbox = $inboxFactory->create(); + $inbox = $this->inboxFactory->create(); $inbox->addNotice( 'Fastly CDN', "Version $lastVersion is available. You are currently running $currentVersion." - . ' Please consider upgrading at your earliest convenience.' + . ' Please consider upgrading at your earliest convenience.' ); $this->cacheManager->clean([\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER]); } @@ -150,63 +150,28 @@ public function checkUpdate($currentVersion = null) /** * Fetches last github version * - * @return bool|float + * @return string */ - public function getLastVersion() + public function getLastVersion(): string { try { $url = self::CHECK_VERSION_URL; - $client = $this->curlFactory->create(); - - $client->write(Request::METHOD_GET, $url, '1.1'); - $responseBody = $client->read(); - $client->close(); + $client = $this->clientFactory->create(); + $request = $this->requestFactory->create(); + $request->setMethod(Request::METHOD_GET); + $request->setUri($url); + $response = $client->send($request); - $responseCode = $this->extractCodeFromResponse($responseBody); + $responseCode = $response->getStatusCode(); if ($responseCode !== 200) { - return false; + return ''; } - $body = $this->extractBodyFromResponse($responseBody); + $body = $response->getBody(); $json = json_decode($body); - $version = !empty($json->version) ? $json->version : false; - - return $version; + return !empty($json->version) ? $json->version : ''; } catch (\Exception $e) { - $this->_logger->log(100, $e->getMessage().$url); - return false; - } - } - - /** - * Extract the response code from a response string - * - * @param string $responseString - * - * @return false|int - */ - private function extractCodeFromResponse(string $responseString) - { - try { - $responseCode = Response::fromString($responseString)->getStatusCode(); - } catch (Throwable $e) { - $responseCode = false; - } - - return $responseCode; - } - - /** - * Extract the body from a response string - * - * @param string $response_str - * @return string - */ - private function extractBodyFromResponse($response_str) - { - $parts = preg_split('|(?:\r\n){2}|m', $response_str, 2); - if (isset($parts[1])) { - return $parts[1]; + $this->_logger->log(100, $e->getMessage() . $url); + return ''; } - return ''; } } diff --git a/Observer/CheckVersion.php b/Observer/CheckVersion.php index dcacf4e8..789fc5ac 100644 --- a/Observer/CheckVersion.php +++ b/Observer/CheckVersion.php @@ -93,7 +93,7 @@ public function execute(Observer $observer) // @codingStandardsIgnoreLine - unus $modulePath = $this->moduleRegistry->getPath(ComponentRegistrar::MODULE, 'Fastly_Cdn'); $filePath = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, "$modulePath/composer.json"); $composerData = json_decode(file_get_contents($filePath)); // @codingStandardsIgnoreLine - not user controlled - $currentVersion = !empty($composerData->version) ? $composerData->version : false; + $currentVersion = !empty($composerData->version) ? $composerData->version : ''; if ($currentVersion) { $this->feedFactory->checkUpdate($currentVersion); From 879e451e054aeb476bec744ba3ff97ae1b28fd2d Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Mon, 16 Jan 2023 13:47:59 +0100 Subject: [PATCH 04/27] Api.php laminas --- Model/Api.php | 120 +++++++++++++++++++++++++++----------------------- 1 file changed, 65 insertions(+), 55 deletions(-) diff --git a/Model/Api.php b/Model/Api.php index cb538255..760e4905 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -20,11 +20,13 @@ */ namespace Fastly\Cdn\Model; +use Laminas\Http\ClientFactory; use Laminas\Http\Request; use Laminas\Http\Response; +use Laminas\Http\HeadersFactory; +use Laminas\Http\RequestFactory; use Laminas\Uri\Exception\ExceptionInterface as UriException; use Laminas\Uri\UriFactory; -use Laminas\Uri\Uri; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\HTTP\Adapter\CurlFactory; use Magento\Framework\Cache\InvalidateLogger; @@ -84,12 +86,24 @@ class Api * @var State */ private $state; - + /** + * @var + */ private $errorMessage; + /** + * @var ClientFactory + */ + private $clientFactory; + /** + * @var RequestFactory + */ + private $requestFactory; + /** + * @var HeadersFactory + */ + private $headersFactory; /** - * Api constructor. - * * @param Config $config * @param CurlFactory $curlFactory * @param InvalidateLogger $logger @@ -98,6 +112,9 @@ class Api * @param Vcl $vcl * @param Session $authSession * @param State $state + * @param ClientFactory $clientFactory + * @param RequestFactory $requestFactory + * @param HeadersFactory $headersFactory */ public function __construct( Config $config, @@ -107,7 +124,10 @@ public function __construct( LoggerInterface $log, Vcl $vcl, Session $authSession, - State $state + State $state, + ClientFactory $clientFactory, + RequestFactory $requestFactory, + HeadersFactory $headersFactory ) { $this->config = $config; $this->curlFactory = $curlFactory; @@ -117,6 +137,9 @@ public function __construct( $this->vcl = $vcl; $this->authSession = $authSession; $this->state = $state; + $this->clientFactory = $clientFactory; + $this->requestFactory = $requestFactory; + $this->headersFactory = $headersFactory; } /** @@ -285,7 +308,8 @@ public function cleanAll() */ private function _purge($uri, $type, $method = Request::METHOD_POST, $payload = null) { - + $request = $this->requestFactory->create(); + $headers = $this->headersFactory->create(); if ($method == 'PURGE') { // create purge token $expiration = time() + self::PURGE_TOKEN_LIFETIME; @@ -295,35 +319,30 @@ private function _purge($uri, $type, $method = Request::METHOD_POST, $payload = $stringToSign = $path . $expiration; $signature = hash_hmac('sha1', $stringToSign, $this->config->getServiceId()); $token = $expiration . '_' . urlencode($signature); - $headers = [ - self::FASTLY_HEADER_TOKEN . ': ' . $token - ]; + $headers->addHeaderLine(self::FASTLY_HEADER_TOKEN . ': ' . $token); } else { // set headers - $headers = [ - self::FASTLY_HEADER_AUTH . ': ' . $this->config->getApiKey() - ]; + $headers->addHeaderLine(self::FASTLY_HEADER_AUTH . ': ' . $this->config->getApiKey()); } // soft purge if needed if ($this->config->canUseSoftPurge()) { - array_push( - $headers, - self::FASTLY_HEADER_SOFT_PURGE . ': 1' - ); + $headers->addHeaderLine(self::FASTLY_HEADER_SOFT_PURGE . ': 1'); } $result['status'] = true; try { - $client = $this->curlFactory->create(); - $client->setConfig(['timeout' => self::PURGE_TIMEOUT]); - if ($method == 'PURGE') { - $client->addOption(CURLOPT_CUSTOMREQUEST, 'PURGE'); - } - $client->write($method, $uri, '1.1', $headers, $payload); - $responseBody = $client->read(); - $responseCode = $this->extractCodeFromResponse($responseBody); - $responseMessage = $this->extractMessageFromResponse($responseBody); - $client->close(); + $client = $this->clientFactory->create(); + + $client->setOptions([ + 'timeout' => self::PURGE_TIMEOUT, + ]); + + $request->setUri($uri); + $request->setMethod($method); + $request->setHeaders($headers); + $response = $client->send($request); + $responseCode = $response->getStatusCode(); + $responseMessage = $response->getReasonPhrase(); // check response if ($responseCode == '429') { @@ -1554,58 +1573,49 @@ private function _fetch( ) { $apiKey = ($test == true) ? $testApiKey : $this->config->getApiKey(); + $headers = $this->headersFactory->create(); + $request = $this->requestFactory->create(); + // Correctly format $body string if (is_array($body) == true) { $body = http_build_query($body); } // Client headers - $headers = [ - self::FASTLY_HEADER_AUTH . ': ' . $apiKey, - 'Accept: application/json' - ]; + $headers->addHeaderLine(self::FASTLY_HEADER_AUTH . ': ' . $apiKey); + $headers->addHeaderLine('Accept: application/json'); // Client options - $options = []; + //$options = []; // Request method specific header & option changes switch ($method) { - case Request::METHOD_DELETE: - $options[CURLOPT_CUSTOMREQUEST] = Request::METHOD_DELETE; - break; case Request::METHOD_PUT: - $headers[] = 'Content-Type: application/x-www-form-urlencoded'; - $options[CURLOPT_CUSTOMREQUEST] = Request::METHOD_PUT; + $headers->addHeaderLine('Content-Type: application/x-www-form-urlencoded'); if ($body != '') { - $options[CURLOPT_POSTFIELDS] = $body; + //$options[CURLOPT_POSTFIELDS] = $body; + $request->getPost()->fromString($body); } - break; case Request::METHOD_PATCH: - $options[CURLOPT_CUSTOMREQUEST] = Request::METHOD_PATCH; - $headers[] = 'Content-Type: text/json'; - + $headers->addHeaderLine('Content-Type: text/json'); if ($body != '') { - $options[CURLOPT_POSTFIELDS] = $body; + $request->getPost()->fromString($body); } - break; } - /** @var \Magento\Framework\HTTP\Adapter\Curl $client */ - $client = $this->curlFactory->create(); - - // Execute request - $client->setOptions($options); - $client->write($method, $uri, '1.1', $headers, $body); - $response = $client->read(); - $client->close(); - + /** @var \Laminas\Http\Client $client */ + $client = $this->clientFactory->create(); + $request->setMethod($method); + $request->setUri($uri); + $request->setHeaders($headers); + $response = $client->send($request); // Parse response - $responseBody = Response::getBody($response); - $responseCode = $this->extractCodeFromResponse($response); - $responseMessage = $this->extractMessageFromResponse($response); + $responseBody = $response->getBody(); + $responseCode = $response->getStatusCode(); + $responseMessage = $response->getReasonPhrase(); // Return error based on response code if ($responseCode == '429') { From 77b2ee90ee77baa223c4fe08c55b3940052cb689 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Mon, 16 Jan 2023 13:53:31 +0100 Subject: [PATCH 05/27] wp --- Model/Api.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Model/Api.php b/Model/Api.php index 760e4905..89971004 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -339,6 +339,9 @@ private function _purge($uri, $type, $method = Request::METHOD_POST, $payload = $request->setUri($uri); $request->setMethod($method); + if($payload){ + $request->setContent($payload); + } $request->setHeaders($headers); $response = $client->send($request); $responseCode = $response->getStatusCode(); From 6c43e1080d160699b4c0f15364e73d5c259420f6 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Mon, 16 Jan 2023 14:08:33 +0100 Subject: [PATCH 06/27] wp --- Model/Api.php | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/Model/Api.php b/Model/Api.php index 89971004..3dc29107 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -1683,21 +1683,4 @@ private function extractCodeFromResponse(string $responseString) return $responseCode; } - - /** - * Extract the response message from a response string - * - * @param string $responseString - * - * @return false|int - */ - private function extractMessageFromResponse(string $responseString) - { - preg_match("|^HTTP/[\d\.x]+ \d+ ([^\r\n]+)|", $responseString, $matches); - if (isset($matches[1])) { - return $matches[1]; - } - - return false; - } } From 68dd0f2276207cf87bc839e34396eec440807b31 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Mon, 16 Jan 2023 14:21:55 +0100 Subject: [PATCH 07/27] wp --- Model/Api.php | 46 +++++++++++++++------------------------------- 1 file changed, 15 insertions(+), 31 deletions(-) diff --git a/Model/Api.php b/Model/Api.php index 3dc29107..df464e55 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -335,6 +335,7 @@ private function _purge($uri, $type, $method = Request::METHOD_POST, $payload = $client->setOptions([ 'timeout' => self::PURGE_TIMEOUT, + 'httpversion' => '1.1' ]); $request->setUri($uri); @@ -1087,9 +1088,8 @@ public function sendWebHook($message) $text = $messagePrefix.' user='.$currentUsername.' '.$message.' on <'.$storeUrl.'|Store> | '.$storeName; - $headers = [ - 'Content-type: application/json' - ]; + $headers = $this->headersFactory->create(); + $headers->addHeaderLine('Content-type: application/json'); $body = json_encode([ "text" => $text, @@ -1097,18 +1097,20 @@ public function sendWebHook($message) "icon_emoji"=> ":airplane:" ]); - $client = $this->curlFactory->create(); - $client->addOption(CURLOPT_CONNECTTIMEOUT, 2); - $client->addOption(CURLOPT_TIMEOUT, 3); - $client->write(Request::METHOD_POST, $url, '1.1', $headers, $body); - $response = $client->read(); - $responseCode = $this->extractCodeFromResponse($response); - - if ($responseCode != 200) { + $client = $this->clientFactory->create(); + $request = $this->requestFactory->create(); + $client->setOptions([ + 'timeout' => 2, + 'httpversion' => '1.1' + ]); + $request->setUri($url); + $request->setMethod(Request::METHOD_POST); + $request->setHeaders($headers); + $request->setContent($body); + $response = $client->send($request); + if ($response->getStatusCode() != 200) { $this->log->log(100, 'Failed to send message to the following Webhook: '.$url); } - - $client->close(); } /** @@ -1665,22 +1667,4 @@ private function extractErrorDetails($responseBody, $responseMessage) } return $responseMessage; } - - /** - * Extract the response code from a response string - * - * @param string $responseString - * - * @return false|int - */ - private function extractCodeFromResponse(string $responseString) - { - try { - $responseCode = Response::fromString($responseString)->getStatusCode(); - } catch (Throwable $e) { - $responseCode = false; - } - - return $responseCode; - } } From 63360b5ea73eee4b9754d3bb5909aa1387faebaa Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Mon, 16 Jan 2023 14:27:05 +0100 Subject: [PATCH 08/27] wp --- Model/Api.php | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Model/Api.php b/Model/Api.php index df464e55..ecddb6b4 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -22,7 +22,6 @@ use Laminas\Http\ClientFactory; use Laminas\Http\Request; -use Laminas\Http\Response; use Laminas\Http\HeadersFactory; use Laminas\Http\RequestFactory; use Laminas\Uri\Exception\ExceptionInterface as UriException; @@ -1590,9 +1589,6 @@ private function _fetch( $headers->addHeaderLine(self::FASTLY_HEADER_AUTH . ': ' . $apiKey); $headers->addHeaderLine('Accept: application/json'); - // Client options - //$options = []; - // Request method specific header & option changes switch ($method) { case Request::METHOD_PUT: @@ -1600,13 +1596,13 @@ private function _fetch( $headers->addHeaderLine('Content-Type: application/x-www-form-urlencoded'); if ($body != '') { //$options[CURLOPT_POSTFIELDS] = $body; - $request->getPost()->fromString($body); + $request->setContent($body); } break; case Request::METHOD_PATCH: $headers->addHeaderLine('Content-Type: text/json'); if ($body != '') { - $request->getPost()->fromString($body); + $request->setContent($body); } break; } From 99054f202dd867205a40e220816fe5c4c045d37c Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Mon, 16 Jan 2023 14:33:45 +0100 Subject: [PATCH 09/27] wp --- Model/Api.php | 156 +++++++++++++++++++++++--------------------------- 1 file changed, 73 insertions(+), 83 deletions(-) diff --git a/Model/Api.php b/Model/Api.php index ecddb6b4..7a70caa4 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -20,25 +20,23 @@ */ namespace Fastly\Cdn\Model; +use Fastly\Cdn\Helper\Data; +use Fastly\Cdn\Helper\Vcl; use Laminas\Http\ClientFactory; -use Laminas\Http\Request; use Laminas\Http\HeadersFactory; +use Laminas\Http\Request; use Laminas\Http\RequestFactory; use Laminas\Uri\Exception\ExceptionInterface as UriException; use Laminas\Uri\UriFactory; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\HTTP\Adapter\CurlFactory; -use Magento\Framework\Cache\InvalidateLogger; -use Fastly\Cdn\Helper\Data; -use Fastly\Cdn\Helper\Vcl; -use Psr\Log\LoggerInterface; use Magento\Backend\Model\Auth\Session; use Magento\Framework\App\State; +use Magento\Framework\Cache\InvalidateLogger; +use Magento\Framework\Exception\LocalizedException; +use Psr\Log\LoggerInterface; /** * Class Api * - * @package Fastly\Cdn\Model */ class Api { @@ -53,10 +51,6 @@ class Api * @var Config */ private $config; - /** - * @var CurlFactory - */ - private $curlFactory; /** * @var InvalidateLogger */ @@ -104,7 +98,6 @@ class Api /** * @param Config $config - * @param CurlFactory $curlFactory * @param InvalidateLogger $logger * @param Data $helper * @param LoggerInterface $log @@ -117,7 +110,6 @@ class Api */ public function __construct( Config $config, - CurlFactory $curlFactory, InvalidateLogger $logger, Data $helper, LoggerInterface $log, @@ -129,7 +121,6 @@ public function __construct( HeadersFactory $headersFactory ) { $this->config = $config; - $this->curlFactory = $curlFactory; $this->logger = $logger; $this->helper = $helper; $this->log = $log; @@ -321,7 +312,7 @@ private function _purge($uri, $type, $method = Request::METHOD_POST, $payload = $headers->addHeaderLine(self::FASTLY_HEADER_TOKEN . ': ' . $token); } else { // set headers - $headers->addHeaderLine(self::FASTLY_HEADER_AUTH . ': ' . $this->config->getApiKey()); + $headers->addHeaderLine(self::FASTLY_HEADER_AUTH . ': ' . $this->config->getApiKey()); } // soft purge if needed @@ -339,7 +330,7 @@ private function _purge($uri, $type, $method = Request::METHOD_POST, $payload = $request->setUri($uri); $request->setMethod($method); - if($payload){ + if ($payload) { $request->setContent($payload); } $request->setHeaders($headers); @@ -364,7 +355,7 @@ private function _purge($uri, $type, $method = Request::METHOD_POST, $payload = } if ($this->config->areWebHooksEnabled() && $this->config->canPublishPurgeChanges()) { - $this->sendWebHook('*initiated ' . $type .'*'); + $this->sendWebHook('*initiated ' . $type . '*'); if ($this->config->canPublishPurgeDebugBacktrace() == false) { return $result; @@ -425,7 +416,7 @@ public function checkServiceDetails($test = false, $serviceId = null, $apiKey = */ public function cloneVersion($curVersion) { - $url = $this->_getApiServiceUri() . 'version/'.rawurlencode($curVersion).'/clone'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($curVersion) . '/clone'; $result = $this->_fetch($url, Request::METHOD_PUT); if (!$result) { @@ -461,7 +452,7 @@ public function addComment($version, $comment) */ public function uploadVcl($version, $vcl) { - $url = $this->_getApiServiceUri() . 'version/' .rawurlencode($version). '/vcl'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/vcl'; $result = $this->_fetch($url, 'POST', $vcl); return $result; @@ -477,7 +468,7 @@ public function uploadVcl($version, $vcl) */ public function setVclAsMain($version, $name) { - $url = $this->_getApiServiceUri() . 'version/' .rawurlencode($version). '/vcl/' .rawurlencode($name). '/main'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/vcl/' . rawurlencode($name) . '/main'; $result = $this->_fetch($url, 'PUT'); return $result; @@ -491,7 +482,7 @@ public function setVclAsMain($version, $name) */ public function validateServiceVersion($version) { - $url = $this->_getApiServiceUri() . 'version/' .rawurlencode($version). '/validate'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/validate'; $result = $this->_fetch($url, 'GET'); if ($result->status == 'error') { @@ -506,7 +497,7 @@ public function validateServiceVersion($version) */ public function containerValidateServiceVersion($version) { - $url = $this->_getApiServiceUri() . 'version/' .rawurlencode($version). '/validate'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/validate'; $result = $this->_fetch($url, 'GET'); return $result; @@ -521,7 +512,7 @@ public function containerValidateServiceVersion($version) */ public function activateVersion($version) { - $url = $this->_getApiServiceUri() . 'version/' .rawurlencode($version). '/activate'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/activate'; $result = $this->_fetch($url, 'PUT'); return $result; @@ -559,18 +550,18 @@ public function uploadSnippet($version, array $snippet) $snippetName = $snippet['name']; $checkIfExists = $this->hasSnippet($version, $snippetName); - $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/snippet'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/snippet'; if (!$checkIfExists) { $verb = Request::METHOD_POST; } else { $verb = Request::METHOD_PUT; if (!isset($snippet['dynamic']) || $snippet['dynamic'] != 1) { - $url .= '/'.rawurlencode($snippetName); + $url .= '/' . rawurlencode($snippetName); unset($snippet['name'], $snippet['type'], $snippet['dynamic']); } else { $snippet['name'] = $this->getSnippet($version, $snippetName)->id; - $url = $this->_getApiServiceUri(). 'snippet' . '/'.rawurlencode($snippet['name']); + $url = $this->_getApiServiceUri() . 'snippet' . '/' . rawurlencode($snippet['name']); } } @@ -591,7 +582,7 @@ public function uploadSnippet($version, array $snippet) */ public function getSnippet($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/snippet/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/snippet/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -606,7 +597,7 @@ public function getSnippet($version, $name) */ public function updateSnippet(array $snippet) { - $url = $this->_getApiServiceUri(). 'snippet' . '/'.rawurlencode($snippet['name']); + $url = $this->_getApiServiceUri() . 'snippet' . '/' . rawurlencode($snippet['name']); $result = $this->_fetch($url, Request::METHOD_PUT, $snippet); if (!$result) { @@ -646,7 +637,7 @@ public function hasSnippet($version, $name) */ public function removeSnippet($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/snippet/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/snippet/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; @@ -662,12 +653,12 @@ public function removeSnippet($version, $name) public function createCondition($version, array $condition) { $checkIfExists = $this->getCondition($version, $condition['name']); - $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/condition'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/condition'; if (!$checkIfExists) { $verb = Request::METHOD_POST; } else { $verb = Request::METHOD_PUT; - $url .= '/'.rawurlencode($condition['name']); + $url .= '/' . rawurlencode($condition['name']); } $result = $this->_fetch($url, $verb, $condition); @@ -688,7 +679,7 @@ public function createCondition($version, array $condition) */ public function removeCondition($version, string $conditionName) { - $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/condition/' . $conditionName; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/condition/' . $conditionName; return $this->_fetch($url, Request::METHOD_DELETE); } @@ -703,7 +694,7 @@ public function removeCondition($version, string $conditionName) */ public function getCondition($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/condition/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/condition/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -720,13 +711,13 @@ public function getCondition($version, $name) public function createHeader($version, array $condition) { $checkIfExists = $this->getHeader($version, $condition['name']); - $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/header'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/header'; if ($checkIfExists === false) { $verb = Request::METHOD_POST; } else { $verb = Request::METHOD_PUT; - $url .= '/'.rawurlencode($condition['name']); + $url .= '/' . rawurlencode($condition['name']); } $result = $this->_fetch($url, $verb, $condition); @@ -744,7 +735,7 @@ public function createHeader($version, array $condition) */ public function getHeader($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/header/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/header/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -761,12 +752,12 @@ public function getHeader($version, $name) public function createResponse($version, array $response) { $checkIfExists = $this->getResponse($version, $response['name']); - $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/response_object'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/response_object'; if (!$checkIfExists) { $verb = Request::METHOD_POST; } else { $verb = Request::METHOD_PUT; - $url .= '/'.rawurlencode($response['name']); + $url .= '/' . rawurlencode($response['name']); } $result = $this->_fetch($url, $verb, $response); @@ -784,7 +775,7 @@ public function createResponse($version, array $response) */ public function removeResponse($version, string $responseName) { - $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/response_object/' . $responseName; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/response_object/' . $responseName; return $this->_fetch($url, Request::METHOD_DELETE); } @@ -799,7 +790,7 @@ public function removeResponse($version, string $responseName) */ public function getResponse($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/response_object/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/response_object/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -814,12 +805,12 @@ public function getResponse($version, $name) public function createRequest($version, $request) { $checkIfExists = $this->getRequest($version, $request['name']); - $url = $this->_getApiServiceUri(). 'version/' .rawurlencode($version). '/request_settings'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/request_settings'; if (!$checkIfExists) { $verb = Request::METHOD_POST; } else { $verb = Request::METHOD_PUT; - $url .= '/'.rawurlencode($request['name']); + $url .= '/' . rawurlencode($request['name']); } $result = $this->_fetch($url, $verb, $request); @@ -840,7 +831,7 @@ public function createRequest($version, $request) */ public function getRequest($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/request_settings/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/request_settings/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_GET, '', false, null, false); return $result; @@ -853,7 +844,7 @@ public function getRequest($version, $name) */ public function getAllConditions($version) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/condition'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/condition'; $result = $this->_fetch($url, Request::METHOD_GET, '', false, null, false); return $result; @@ -866,7 +857,7 @@ public function getAllConditions($version) */ public function getAllDomains($version) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/domain'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/domain'; $result = $this->_fetch($url, Request::METHOD_GET, '', false, null, false); return $result; @@ -880,7 +871,7 @@ public function getAllDomains($version) */ public function deleteDomain($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/domain/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/domain/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; @@ -894,7 +885,7 @@ public function deleteDomain($version, $name) */ public function createDomain($version, $data) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/domain'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/domain'; $result = $this->_fetch($url, Request::METHOD_POST, $data); return $result; @@ -908,7 +899,7 @@ public function createDomain($version, $data) */ public function deleteRequest($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/request_settings/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/request_settings/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_DELETE); if (!$result) { @@ -925,7 +916,7 @@ public function deleteRequest($version, $name) */ public function getBackends($version) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/backend'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/backend'; $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -942,7 +933,7 @@ public function getBackends($version) */ public function configureBackend($params, $version, $old_name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/backend/' . rawurlencode($old_name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/backend/' . rawurlencode($old_name); $result = $this->_fetch($url, Request::METHOD_PUT, $params); return $result; @@ -956,7 +947,7 @@ public function configureBackend($params, $version, $old_name) */ public function createBackend($params, $version) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version). '/backend'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/backend'; $result = $this->_fetch($url, Request::METHOD_POST, $params); return $result; @@ -986,7 +977,7 @@ public function getAllLogEndpoints($version) $providers = $this->helper->getAvailableLogEndpointProviders(); $results = []; foreach ($providers as $type => $providerName) { - $url = $this->_getApiServiceUri(). 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type); $endpoints = $this->_fetch($url, Request::METHOD_GET); foreach ($endpoints as $endpoint) { $results[] = [ @@ -1009,7 +1000,7 @@ public function getLogEndpoints($version, $type) { $results = []; $providers = $this->helper->getAvailableLogEndpointProviders(); - $url = $this->_getApiServiceUri(). 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type); $endpoints = $this->_fetch($url, Request::METHOD_GET); foreach ($endpoints as $endpoint) { $results[] = [ @@ -1030,7 +1021,7 @@ public function getLogEndpoints($version, $type) */ public function getLogEndpoint($version, $type, $name) { - $url = $this->_getApiServiceUri(). 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type) . '/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/logging/' . rawurlencode($type) . '/' . rawurlencode($name); return $this->_fetch($url, Request::METHOD_GET); } @@ -1085,7 +1076,7 @@ public function sendWebHook($message) $storeName = $this->helper->getStoreName(); $storeUrl = $this->helper->getStoreUrl(); - $text = $messagePrefix.' user='.$currentUsername.' '.$message.' on <'.$storeUrl.'|Store> | '.$storeName; + $text = $messagePrefix . ' user=' . $currentUsername . ' ' . $message . ' on <' . $storeUrl . '|Store> | ' . $storeName; $headers = $this->headersFactory->create(); $headers->addHeaderLine('Content-type: application/json'); @@ -1108,7 +1099,7 @@ public function sendWebHook($message) $request->setContent($body); $response = $client->send($request); if ($response->getStatusCode() != 200) { - $this->log->log(100, 'Failed to send message to the following Webhook: '.$url); + $this->log->log(100, 'Failed to send message to the following Webhook: ' . $url); } } @@ -1122,7 +1113,7 @@ public function sendWebHook($message) */ public function createDictionary($version, $params) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/dictionary'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/dictionary'; $result = $this->_fetch($url, Request::METHOD_POST, $params); return $result; @@ -1138,7 +1129,7 @@ public function createDictionary($version, $params) */ public function deleteDictionary($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/dictionary/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/dictionary/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; @@ -1153,7 +1144,7 @@ public function deleteDictionary($version, $name) */ public function dictionaryItemsList($dictionaryId) { - $url = $this->_getApiServiceUri(). 'dictionary/'.rawurlencode($dictionaryId).'/items'; + $url = $this->_getApiServiceUri() . 'dictionary/' . rawurlencode($dictionaryId) . '/items'; $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -1169,7 +1160,7 @@ public function dictionaryItemsList($dictionaryId) */ public function getSingleDictionary($version, $dictionaryName) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/dictionary/' . rawurlencode($dictionaryName); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/dictionary/' . rawurlencode($dictionaryName); $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -1221,7 +1212,7 @@ public function checkAuthDictionaryPopulation($version) */ public function createDictionaryItems($dictionaryId, $params) { - $url = $this->_getApiServiceUri().'dictionary/'.rawurlencode($dictionaryId).'/items'; + $url = $this->_getApiServiceUri() . 'dictionary/' . rawurlencode($dictionaryId) . '/items'; $result = $this->_fetch($url, Request::METHOD_PATCH, $params); return $result; @@ -1236,7 +1227,7 @@ public function createDictionaryItems($dictionaryId, $params) */ public function getDictionaries($version) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/dictionary'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/dictionary'; $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -1252,7 +1243,7 @@ public function getDictionaries($version) */ public function deleteDictionaryItem($dictionaryId, $itemKey) { - $url = $this->_getApiServiceUri(). 'dictionary/'. rawurlencode($dictionaryId) . '/item/' . rawurlencode($itemKey); + $url = $this->_getApiServiceUri() . 'dictionary/' . rawurlencode($dictionaryId) . '/item/' . rawurlencode($itemKey); $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; @@ -1269,7 +1260,7 @@ public function deleteDictionaryItem($dictionaryId, $itemKey) public function upsertDictionaryItem($dictionaryId, $itemKey, $itemValue) { $body = ['item_value' => $itemValue]; - $url = $this->_getApiServiceUri(). 'dictionary/'. rawurlencode($dictionaryId) . '/item/' . rawurlencode($itemKey); + $url = $this->_getApiServiceUri() . 'dictionary/' . rawurlencode($dictionaryId) . '/item/' . rawurlencode($itemKey); $result = $this->_fetch($url, Request::METHOD_PUT, $body); if (!$result) { @@ -1286,7 +1277,7 @@ public function upsertDictionaryItem($dictionaryId, $itemKey, $itemValue) */ public function getSingleAcl($version, $acl) { - $url = $this->_getApiServiceUri(). 'version/'. $version . '/acl/' . $acl; + $url = $this->_getApiServiceUri() . 'version/' . $version . '/acl/' . $acl; $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -1302,7 +1293,7 @@ public function getSingleAcl($version, $acl) */ public function createAcl($version, $params) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/acl'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/acl'; $result = $this->_fetch($url, Request::METHOD_POST, $params); return $result; @@ -1317,7 +1308,7 @@ public function createAcl($version, $params) */ public function getAcls($version) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/acl'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/acl'; $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -1333,7 +1324,7 @@ public function getAcls($version) */ public function deleteAcl($version, $name) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/acl/' . rawurlencode($name); + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/acl/' . rawurlencode($name); $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; @@ -1348,7 +1339,7 @@ public function deleteAcl($version, $name) */ public function aclItemsList($aclId) { - $url = $this->_getApiServiceUri() . 'acl/'. rawurlencode($aclId) . '/entries'; + $url = $this->_getApiServiceUri() . 'acl/' . rawurlencode($aclId) . '/entries'; $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -1377,7 +1368,7 @@ public function upsertAclItem($aclId, $itemValue, $negated, $comment = 'Added by $body['subnet'] = $subnet; } - $url = $this->_getApiServiceUri(). 'acl/'. rawurlencode($aclId) . '/entry'; + $url = $this->_getApiServiceUri() . 'acl/' . rawurlencode($aclId) . '/entry'; $result = $this->_fetch($url, Request::METHOD_POST, $body); return $result; @@ -1393,7 +1384,7 @@ public function upsertAclItem($aclId, $itemValue, $negated, $comment = 'Added by */ public function deleteAclItem($aclId, $aclItemId) { - $url = $this->_getApiServiceUri(). 'acl/'. rawurlencode($aclId) . '/entry/' . rawurlencode($aclItemId); + $url = $this->_getApiServiceUri() . 'acl/' . rawurlencode($aclId) . '/entry/' . rawurlencode($aclItemId); $result = $this->_fetch($url, Request::METHOD_DELETE); return $result; @@ -1423,7 +1414,7 @@ public function updateAclItem($aclId, $aclItemId, $itemValue, $negated, $comment $body['subnet'] = $subnet; } - $url = $this->_getApiServiceUri(). 'acl/'. rawurlencode($aclId) . '/entry/' . rawurlencode($aclItemId); + $url = $this->_getApiServiceUri() . 'acl/' . rawurlencode($aclId) . '/entry/' . rawurlencode($aclItemId); $result = $this->_fetch($url, Request::METHOD_PATCH, json_encode($body)); return $result; @@ -1439,10 +1430,10 @@ public function updateAclItem($aclId, $aclItemId, $itemValue, $negated, $comment public function queryHistoricStats(array $parameters) { $uri = $this->_getHistoricalEndpoint() - . '?region='.rawurlencode($parameters['region']) - . '&from='.rawurlencode($parameters['from']) - . '&to='.rawurlencode($parameters['to']) - . '&by='.rawurlencode($parameters['sample_rate']); + . '?region=' . rawurlencode($parameters['region']) + . '&from=' . rawurlencode($parameters['from']) + . '&to=' . rawurlencode($parameters['to']) + . '&by=' . rawurlencode($parameters['sample_rate']); $result = $this->_fetch($uri); @@ -1480,7 +1471,7 @@ public function getParticularVersion($version) */ public function checkImageOptimizationStatus() { - $url = $this->_getApiServiceUri(). 'dynamic_io_settings'; + $url = $this->_getApiServiceUri() . 'dynamic_io_settings'; $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -1495,7 +1486,7 @@ public function checkImageOptimizationStatus() */ public function getImageOptimizationDefaultConfigOptions($version) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/io_settings'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/io_settings'; $result = $this->_fetch($url, Request::METHOD_GET); return $result; @@ -1511,7 +1502,7 @@ public function getImageOptimizationDefaultConfigOptions($version) */ public function configureImageOptimizationDefaultConfigOptions($params, $version) { - $url = $this->_getApiServiceUri(). 'version/'. rawurlencode($version) . '/io_settings'; + $url = $this->_getApiServiceUri() . 'version/' . rawurlencode($version) . '/io_settings'; $result = $this->_fetch($url, Request::METHOD_PATCH, $params); return $result; @@ -1586,7 +1577,7 @@ private function _fetch( } // Client headers - $headers->addHeaderLine(self::FASTLY_HEADER_AUTH . ': ' . $apiKey); + $headers->addHeaderLine(self::FASTLY_HEADER_AUTH . ': ' . $apiKey); $headers->addHeaderLine('Accept: application/json'); // Request method specific header & option changes @@ -1595,7 +1586,6 @@ private function _fetch( $headers->addHeaderLine('Content-Type: application/x-www-form-urlencoded'); if ($body != '') { - //$options[CURLOPT_POSTFIELDS] = $body; $request->setContent($body); } break; @@ -1645,7 +1635,7 @@ private function stackTrace($type) } } - $this->sendWebHook('*'. $type .' backtrace:*```' . implode("\n", $trace) . '```'); + $this->sendWebHook('*' . $type . ' backtrace:*```' . implode("\n", $trace) . '```'); } /** From 714d7101daf5abefd9db2bd021a6f30d52b57cb8 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Mon, 16 Jan 2023 14:49:27 +0100 Subject: [PATCH 10/27] wp --- Model/Api.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Model/Api.php b/Model/Api.php index 7a70caa4..a8caf5ca 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -1097,8 +1097,12 @@ public function sendWebHook($message) $request->setMethod(Request::METHOD_POST); $request->setHeaders($headers); $request->setContent($body); - $response = $client->send($request); - if ($response->getStatusCode() != 200) { + try{ + $response = $client->send($request); + if ($response->getStatusCode() != 200) { + $this->log->log(100, 'Failed to send message to the following Webhook: ' . $url); + } + }catch (\Exception $e){ $this->log->log(100, 'Failed to send message to the following Webhook: ' . $url); } } From 5dec1cd12b229d0509c04b47485d040ba8226668 Mon Sep 17 00:00:00 2001 From: Borna Butkovic Date: Mon, 16 Jan 2023 12:53:37 +0100 Subject: [PATCH 11/27] update Magento, PHP and Laminas dependencies --- composer.json | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/composer.json b/composer.json index 20a75fab..772be186 100644 --- a/composer.json +++ b/composer.json @@ -2,12 +2,13 @@ "name": "fastly/magento2", "description": "Fastly CDN Module for Magento 2.3.x | 2.4.x", "require": { - "php": "~7.1.3|~7.2.0|~7.3.0|~7.4.0|~8.0.0|~8.1.0|~8.2.0", - "magento/module-config": ">=101.1.0", - "magento/module-store": ">=101.0.0", - "magento/module-page-cache": ">=100.3.0", - "magento/module-cache-invalidate": ">=100.3.0", - "magento/framework": ">=102.0.0", + "php": "~7.3.0|~7.4.0|~8.0.0|~8.1.0|~8.2.0", + "magento/module-config": ">=101.1.6", + "magento/module-store": ">=101.0.6", + "magento/module-page-cache": ">=100.3.6", + "magento/module-cache-invalidate": ">=100.3.4", + "magento/framework": ">=102.0.6", + "laminas/laminas-http": "^2.6.0", "zordius/lightncandy": "^1.2" }, "type": "magento2-module", From 1a0975c3e1e922dd37bcf78b561d0ebd5ad76a5e Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Tue, 17 Jan 2023 09:59:40 +0100 Subject: [PATCH 12/27] Observer/InvalidateVarnishObserver.php --- Observer/InvalidateVarnishObserver.php | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Observer/InvalidateVarnishObserver.php b/Observer/InvalidateVarnishObserver.php index a429623d..927d5de8 100644 --- a/Observer/InvalidateVarnishObserver.php +++ b/Observer/InvalidateVarnishObserver.php @@ -23,13 +23,11 @@ use Fastly\Cdn\Helper\CacheTags; use Fastly\Cdn\Model\Config; use Fastly\Cdn\Model\PurgeCache; -use Laminas\Uri\Exception\ExceptionInterface as UriException; use Magento\Framework\Event\ObserverInterface; /** - * Class InvalidateVarnishObserver - * - * @package Fastly\Cdn\Observer + * Class InvalidateVarnishObserver for invalidating fastly cache + * sending purge request */ class InvalidateVarnishObserver implements ObserverInterface { @@ -69,9 +67,9 @@ public function __construct( * If Fastly CDN is enabled it sends one purge request per tag * * @param \Magento\Framework\Event\Observer $observer - * @throws UriException + * @return void */ - public function execute(\Magento\Framework\Event\Observer $observer) + public function execute(\Magento\Framework\Event\Observer $observer): void { if ($this->config->getType() === Config::FASTLY && $this->config->isEnabled()) { $object = $observer->getEvent()->getObject(); From 0a5b6925c344870cd8d8a974875ed13d90209762 Mon Sep 17 00:00:00 2001 From: Borna Butkovic Date: Tue, 17 Jan 2023 10:01:02 +0100 Subject: [PATCH 13/27] deprecate 2.3.x --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 772be186..9376cc7e 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "fastly/magento2", - "description": "Fastly CDN Module for Magento 2.3.x | 2.4.x", + "description": "Fastly CDN Module for Magento 2.4.x", "require": { "php": "~7.3.0|~7.4.0|~8.0.0|~8.1.0|~8.2.0", "magento/module-config": ">=101.1.6", From a05109b496bd221b18d9adb6c24dae7459d513b2 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Tue, 17 Jan 2023 10:04:17 +0100 Subject: [PATCH 14/27] Observer/FlushAllCacheObserver.php --- Observer/FlushAllCacheObserver.php | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Observer/FlushAllCacheObserver.php b/Observer/FlushAllCacheObserver.php index 7c55c904..06d9ac1a 100644 --- a/Observer/FlushAllCacheObserver.php +++ b/Observer/FlushAllCacheObserver.php @@ -22,13 +22,12 @@ use Fastly\Cdn\Model\Config; use Fastly\Cdn\Model\PurgeCache; -use Laminas\Uri\Exception\ExceptionInterface as UriException; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Event\Observer; /** - * Class FlushAllCacheObserver + * Class FlushAllCacheObserver - send purge request * - * @package Fastly\Cdn\Observer */ class FlushAllCacheObserver implements ObserverInterface { @@ -54,10 +53,10 @@ public function __construct(Config $config, PurgeCache $purgeCache) /** * Flush Fastly CDN cache * - * @param \Magento\Framework\Event\Observer $observer - * @throws UriException + * @param Observer $observer + * @return void */ - public function execute(\Magento\Framework\Event\Observer $observer) // @codingStandardsIgnoreLine - unused parameter + public function execute(Observer $observer): void // @codingStandardsIgnoreLine - unused parameter { if ($this->config->getType() === Config::FASTLY && $this->config->isEnabled()) { $this->purgeCache->sendPurgeRequest(); From 258f6b956dc6d3b88f8093996bf61779b47c2535 Mon Sep 17 00:00:00 2001 From: Borna Butkovic Date: Tue, 17 Jan 2023 10:12:14 +0100 Subject: [PATCH 15/27] deprecate 2.3.x --- composer.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index 9376cc7e..8bb912cd 100644 --- a/composer.json +++ b/composer.json @@ -3,11 +3,11 @@ "description": "Fastly CDN Module for Magento 2.4.x", "require": { "php": "~7.3.0|~7.4.0|~8.0.0|~8.1.0|~8.2.0", - "magento/module-config": ">=101.1.6", - "magento/module-store": ">=101.0.6", - "magento/module-page-cache": ">=100.3.6", - "magento/module-cache-invalidate": ">=100.3.4", - "magento/framework": ">=102.0.6", + "magento/module-config": ">=101.2.0", + "magento/module-store": ">=101.1.0", + "magento/module-page-cache": ">=100.4.0", + "magento/module-cache-invalidate": ">=100.4.0", + "magento/framework": ">=103.0.0", "laminas/laminas-http": "^2.6.0", "zordius/lightncandy": "^1.2" }, From 395f17a1b2b94bcc39d404d71b9029b29a842450 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Tue, 17 Jan 2023 10:38:55 +0100 Subject: [PATCH 16/27] Model/PurgeCache.php --- Model/PurgeCache.php | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Model/PurgeCache.php b/Model/PurgeCache.php index 64201428..f120a075 100644 --- a/Model/PurgeCache.php +++ b/Model/PurgeCache.php @@ -20,12 +20,9 @@ */ namespace Fastly\Cdn\Model; -use Laminas\Uri\Exception\ExceptionInterface as UriException; - /** - * Class PurgeCache + * Class PurgeCache by pattern * - * @package Fastly\Cdn\Model */ class PurgeCache { @@ -54,8 +51,7 @@ public function __construct(Api $api, Config $config) * Send API purge request to invalidate cache by pattern * * @param string $pattern - * @return bool - * @throws UriException + * @return array|bool|\Magento\Framework\Controller\Result\Json */ public function sendPurgeRequest($pattern = '') { From 9639daeeefd4e3f27fc7c8615e9d26bcec85eb5e Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Tue, 17 Jan 2023 13:06:11 +0100 Subject: [PATCH 17/27] Layout/LayoutPlugin.php --- Model/Layout/LayoutPlugin.php | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/Model/Layout/LayoutPlugin.php b/Model/Layout/LayoutPlugin.php index 4b328696..356f272d 100644 --- a/Model/Layout/LayoutPlugin.php +++ b/Model/Layout/LayoutPlugin.php @@ -20,12 +20,11 @@ */ namespace Fastly\Cdn\Model\Layout; -use \Fastly\Cdn\Model\Config; +use Fastly\Cdn\Model\Config; +use Laminas\Http\Header\HeaderInterface; /** - * Class LayoutPlugin - * - * @package Fastly\Cdn\Model\Layout + * Class LayoutPlugin for setting fastly cache-control header */ class LayoutPlugin { @@ -61,19 +60,18 @@ public function __construct( /** * Set appropriate Cache-Control headers - * Set Fastly stale headers if configured * * @param \Magento\Framework\View\Layout $subject * @return void */ - public function afterGenerateElements(\Magento\Framework\View\Layout $subject) + public function afterGenerateElements(\Magento\Framework\View\Layout $subject): void { // if subject is cacheable, FPC cache is enabled, Fastly module is chosen and general TTL is > 0 if ($subject->isCacheable() && $this->config->isEnabled() && $this->config->getType() === Config::FASTLY && $this->config->getTtl()) { // get cache control header $header = $this->response->getHeader('cache-control'); - if (($header instanceof \Laminas\Http\Header\HeaderInterface) && ($value = $header->getFieldValue())) { + if (($header instanceof HeaderInterface) && ($value = $header->getFieldValue())) { // append stale values if ($ttl = $this->config->getStaleTtl()) { $value .= ', stale-while-revalidate=' . $ttl; @@ -99,7 +97,6 @@ public function afterGenerateElements(\Magento\Framework\View\Layout $subject) /** * Add a debug header to indicate this request has passed through the Fastly Module. - * This is for ease of debugging * * @param \Magento\Framework\View\Layout $subject * @param mixed $result From 69198c27b1455f80a4d62f02a0dcd15b01c7d179 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Tue, 17 Jan 2023 14:01:11 +0100 Subject: [PATCH 18/27] Layout/LayoutPlugin.php --- Model/Layout/LayoutPlugin.php | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/Model/Layout/LayoutPlugin.php b/Model/Layout/LayoutPlugin.php index 356f272d..e6d0f779 100644 --- a/Model/Layout/LayoutPlugin.php +++ b/Model/Layout/LayoutPlugin.php @@ -36,26 +36,19 @@ class LayoutPlugin * @var \Magento\Framework\App\ResponseInterface */ private $response; - /** - * @var \Fastly\Cdn\Helper\CacheTags - */ - private $cacheTags; /** * Constructor * * @param \Magento\Framework\App\ResponseInterface $response * @param \Fastly\Cdn\Model\Config $config - * @param \Fastly\Cdn\Helper\CacheTags $cacheTags */ public function __construct( \Magento\Framework\App\ResponseInterface $response, - Config $config, - \Fastly\Cdn\Helper\CacheTags $cacheTags + Config $config ) { $this->response = $response; $this->config = $config; - $this->cacheTags = $cacheTags; } /** From f6ec19100f99e1b8ba795cbb40dd075c0014af74 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Tue, 17 Jan 2023 14:03:52 +0100 Subject: [PATCH 19/27] Model/Config/ConfigRewrite.php --- Model/Config/ConfigRewrite.php | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Model/Config/ConfigRewrite.php b/Model/Config/ConfigRewrite.php index e278060d..c9e679cf 100644 --- a/Model/Config/ConfigRewrite.php +++ b/Model/Config/ConfigRewrite.php @@ -21,16 +21,16 @@ namespace Fastly\Cdn\Model\Config; use Fastly\Cdn\Model\Api; -use Laminas\Uri\Exception\ExceptionInterface as UriException; use Magento\Framework\App\Config\ScopeConfigInterface; /** * Used for sending purge after disabling Fastly as caching service - * - * @author Inchoo */ class ConfigRewrite { + /** + * @var bool + */ private $purge = false; /** * @var ScopeConfigInterface @@ -59,9 +59,9 @@ public function __construct( * Trigger purge if set * * @param \Magento\Config\Model\Config $subject - * @throws UriException + * @return void */ - public function afterSave(\Magento\Config\Model\Config $subject) // @codingStandardsIgnoreLine - unused parameter + public function afterSave(\Magento\Config\Model\Config $subject): void // @codingStandardsIgnoreLine - unused parameter { if ($this->purge) { $this->api->cleanBySurrogateKey(['text']); @@ -70,9 +70,11 @@ public function afterSave(\Magento\Config\Model\Config $subject) // @codingStand /** * Set flag for purging if Fastly is switched off + * * @param \Magento\Config\Model\Config $subject + * @return void */ - public function beforeSave(\Magento\Config\Model\Config $subject) + public function beforeSave(\Magento\Config\Model\Config $subject): void { $data = $subject->getData(); if (!empty($data['groups']['full_page_cache']['fields']['caching_application']['value'])) { From 23467afdf470c1ee73a8fe7c15a341680a3eb9f1 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Tue, 17 Jan 2023 14:52:46 +0100 Subject: [PATCH 20/27] Controller/Adminhtml/FastlyCdn/Purge/Quick.php --- Controller/Adminhtml/FastlyCdn/Purge/Quick.php | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/Controller/Adminhtml/FastlyCdn/Purge/Quick.php b/Controller/Adminhtml/FastlyCdn/Purge/Quick.php index 8507c938..5d3f9f07 100644 --- a/Controller/Adminhtml/FastlyCdn/Purge/Quick.php +++ b/Controller/Adminhtml/FastlyCdn/Purge/Quick.php @@ -22,9 +22,7 @@ use Fastly\Cdn\Model\Config; use Fastly\Cdn\Model\PurgeCache; -use Laminas\Uri\Exception\ExceptionInterface as UriException; use Laminas\Uri\UriFactory; -use Laminas\Uri\Uri; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\Exception\LocalizedException; @@ -32,9 +30,7 @@ use Magento\Store\Model\StoreManagerInterface; /** - * Class Quick - * - * @package Fastly\Cdn\Controller\Adminhtml\FastlyCdn\Purge + * Class Quick purge */ class Quick extends Action { @@ -123,11 +119,10 @@ public function execute() /** * Checks if host is one of Magento's configured domains. * - * @param $host + * @param string $host * @return bool - * @throws UriException */ - private function isHostInDomainList($host) + private function isHostInDomainList($host): bool { $urlTypes = [ UrlInterface::URL_TYPE_LINK, From 410cd912f979334e3cd761f1cda99f1c0aa241fd Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Tue, 17 Jan 2023 15:25:58 +0100 Subject: [PATCH 21/27] Controller/Adminhtml/FastlyCdn/Purge/All.php --- Controller/Adminhtml/FastlyCdn/Purge/All.php | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Controller/Adminhtml/FastlyCdn/Purge/All.php b/Controller/Adminhtml/FastlyCdn/Purge/All.php index 506ed064..ed4a5aba 100644 --- a/Controller/Adminhtml/FastlyCdn/Purge/All.php +++ b/Controller/Adminhtml/FastlyCdn/Purge/All.php @@ -18,18 +18,16 @@ * @copyright Copyright (c) 2016 Fastly, Inc. (http://www.fastly.com) * @license BSD, see LICENSE_FASTLY_CDN.txt */ + namespace Fastly\Cdn\Controller\Adminhtml\FastlyCdn\Purge; use Fastly\Cdn\Model\Api; -use Laminas\Uri\Exception\ExceptionInterface as UriException; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\App\Cache\Manager; /** - * Class All - * - * @package Fastly\Cdn\Controller\Adminhtml\FastlyCdn\Purge + * Class Purge All objects */ class All extends Action { @@ -51,7 +49,7 @@ class All extends Action */ public function __construct( Context $context, - Api $api, + Api $api, Manager $cacheManager ) { $this->api = $api; @@ -62,10 +60,10 @@ public function __construct( /** * Performs cache cleanup and purge all on Fastly service. + * * Should be used when "Preserve static assets on purge" is enabled. * * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface - * @throws UriException */ public function execute() { From abc988a5c3534e900be852c18344118f45d5618d Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Wed, 18 Jan 2023 10:14:58 +0100 Subject: [PATCH 22/27] Api.php --- Model/Api.php | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/Model/Api.php b/Model/Api.php index a8caf5ca..ee25602f 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -26,7 +26,6 @@ use Laminas\Http\HeadersFactory; use Laminas\Http\Request; use Laminas\Http\RequestFactory; -use Laminas\Uri\Exception\ExceptionInterface as UriException; use Laminas\Uri\UriFactory; use Magento\Backend\Model\Auth\Session; use Magento\Framework\App\State; @@ -35,8 +34,7 @@ use Psr\Log\LoggerInterface; /** - * Class Api - * + * Class Api for sending request to fastly */ class Api { @@ -170,8 +168,7 @@ private function _getWafEndpoint() * Purge a single URL * * @param $url - * @return \Magento\Framework\Controller\Result\Json - * @throws UriException + * @return array|\Magento\Framework\Controller\Result\Json */ public function cleanUrl($url) { @@ -192,8 +189,7 @@ public function cleanUrl($url) * Purge Fastly by a given surrogate key * * @param $keys - * @return bool|\Magento\Framework\Controller\Result\Json - * @throws UriException + * @return bool|mixed */ public function cleanBySurrogateKey($keys) { @@ -249,8 +245,7 @@ public function cleanBySurrogateKey($keys) /** * Purge all of Fastly's CDN content. Can be called only once per request * - * @return bool|\Magento\Framework\Controller\Result\Json - * @throws UriException + * @return bool|mixed */ public function cleanAll() { @@ -291,10 +286,9 @@ public function cleanAll() * * @param $uri * @param $type - * @param string $method - * @param null $payload - * @return \Magento\Framework\Controller\Result\Json - * @throws UriException + * @param $method + * @param $payload + * @return array */ private function _purge($uri, $type, $method = Request::METHOD_POST, $payload = null) { From ce016da7392534b5f3258f67a0d5cb2037438b94 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Wed, 18 Jan 2023 10:49:05 +0100 Subject: [PATCH 23/27] Model/Statistic.php --- Model/Statistic.php | 68 +++++++++++++++++++++------------------------ 1 file changed, 31 insertions(+), 37 deletions(-) diff --git a/Model/Statistic.php b/Model/Statistic.php index a1b1408c..6a413aaa 100644 --- a/Model/Statistic.php +++ b/Model/Statistic.php @@ -21,8 +21,9 @@ namespace Fastly\Cdn\Model; use Fastly\Cdn\Helper\Data; +use Laminas\Http\ClientFactory; use Laminas\Http\Request; -use Laminas\Http\Response; +use Laminas\Http\RequestFactory; use Magento\Directory\Api\CountryInformationAcquirerInterface; use Magento\Directory\Model\CountryFactory; use Magento\Directory\Model\RegionFactory; @@ -42,8 +43,6 @@ /** * Class Statistic - * - * @package Fastly\Cdn\Model */ class Statistic extends AbstractModel implements IdentityInterface { @@ -116,9 +115,13 @@ class Statistic extends AbstractModel implements IdentityInterface */ private $api; /** - * @var CurlFactory + * @var ClientFactory + */ + private $clientFactory; + /** + * @var RequestFactory */ - private $curlFactory; + private $requestFactory; /** * @var StatisticRepository */ @@ -141,18 +144,20 @@ class Statistic extends AbstractModel implements IdentityInterface private $helper; /** - * Statistic constructor. * @param Context $context * @param Registry $registry - * @param \Fastly\Cdn\Model\Config $config + * @param Config $config * @param StoreManagerInterface $storeManager * @param ScopeConfigInterface $scopeConfig * @param CountryInformationAcquirerInterface $countryInformation * @param RegionFactory $regionFactory * @param Api $api - * @param CurlFactory $curlFactory + * @param ClientFactory $clientFactory + * @param RequestFactory $requestFactory + * @param CountryFactory $countryFactory * @param StatisticRepository $statisticRepository * @param DateTime $dateTime + * @param Data $helper * @param ProductMetadataInterface $productMetadata * @param Http $request * @param AbstractResource|null $resource @@ -168,7 +173,8 @@ public function __construct( CountryInformationAcquirerInterface $countryInformation, RegionFactory $regionFactory, Api $api, - CurlFactory $curlFactory, + ClientFactory $clientFactory, + RequestFactory $requestFactory, CountryFactory $countryFactory, StatisticRepository $statisticRepository, DateTime $dateTime, @@ -186,7 +192,8 @@ public function __construct( $this->countryInformation = $countryInformation; $this->regionFactory = $regionFactory; $this->api = $api; - $this->curlFactory = $curlFactory; + $this->clientFactory = $clientFactory; + $this->requestFactory = $requestFactory; $this->statisticRepository = $statisticRepository; $this->dateTime = $dateTime; $this->countryFactory = $countryFactory; @@ -198,7 +205,7 @@ public function __construct( protected function _construct() // @codingStandardsIgnoreLine - required by parent class { - $this->_init('Fastly\Cdn\Model\ResourceModel\Statistic'); + $this->_init(\Fastly\Cdn\Model\ResourceModel\Statistic::class); } public function getIdentities() @@ -591,14 +598,19 @@ private function sendReqToGA($body = '', $method = Request::METHOD_POST, $uri = } try { - $client = $this->curlFactory->create(); - $client->addOption(CURLOPT_TIMEOUT, 10); - $client->write($method, $uri, '1.1', null, http_build_query($body)); - $response = $client->read(); - $responseCode = $this->extractCodeFromResponse($response); - $client->close(); - - if ($responseCode != '200') { + $client = $this->clientFactory->create(); + $client->setOptions([ + 'timeout' => 10, + 'httpversion' => '1.1' + ]); + $request = $this->requestFactory->create(); + $request->setMethod($method); + $request->setUri($uri); + $request->setContent(http_build_query($body)); + $response = $client->send($request); + $responseCode = $response->getStatusCode(); + + if ($responseCode !== 200) { throw new LocalizedException(__('Return status ' . $responseCode)); } @@ -607,22 +619,4 @@ private function sendReqToGA($body = '', $method = Request::METHOD_POST, $uri = return false; } } - - /** - * Extract the response code from a response string - * - * @param string $responseString - * - * @return false|int - */ - private function extractCodeFromResponse(string $responseString) - { - try { - $responseCode = Response::fromString($responseString)->getStatusCode(); - } catch (Throwable $e) { - $responseCode = false; - } - - return $responseCode; - } } From c6789f08309401a0c3549db20a0a995de8132d74 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Wed, 18 Jan 2023 12:07:43 +0100 Subject: [PATCH 24/27] Model/Statistic.php --- Model/Statistic.php | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Model/Statistic.php b/Model/Statistic.php index 6a413aaa..b5543d86 100644 --- a/Model/Statistic.php +++ b/Model/Statistic.php @@ -582,14 +582,15 @@ public function daysFromInstallation() } /** - * Sends CURL request to GA + * Sends request to GA * - * @param string $body - * @param string $method - * @param string $uri + * @param $body + * @param $method + * @param $uri * @return bool + * @throws \Magento\Framework\Exception\NoSuchEntityException */ - private function sendReqToGA($body = '', $method = Request::METHOD_POST, $uri = self::GA_API_ENDPOINT) + private function sendReqToGA($body = '', $method = Request::METHOD_POST, $uri = self::GA_API_ENDPOINT): bool { $reqGAData = (array)$this->getGAReqData(); From 9d77a415a8bb709521e3ee202a98e5bd81605ecc Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Wed, 18 Jan 2023 12:50:17 +0100 Subject: [PATCH 25/27] Model/Api.php --- Model/Api.php | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Model/Api.php b/Model/Api.php index ee25602f..3d1ced9a 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -1583,15 +1583,9 @@ private function _fetch( case Request::METHOD_PUT: $headers->addHeaderLine('Content-Type: application/x-www-form-urlencoded'); - if ($body != '') { - $request->setContent($body); - } break; case Request::METHOD_PATCH: $headers->addHeaderLine('Content-Type: text/json'); - if ($body != '') { - $request->setContent($body); - } break; } @@ -1600,6 +1594,9 @@ private function _fetch( $request->setMethod($method); $request->setUri($uri); $request->setHeaders($headers); + if($body){ + $request->setContent($body); + } $response = $client->send($request); // Parse response $responseBody = $response->getBody(); From bc18396d41720bd707a0947cc1fa30c338fa0fe5 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Thu, 19 Jan 2023 09:22:37 +0100 Subject: [PATCH 26/27] Model/Api.php --- Model/Api.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Model/Api.php b/Model/Api.php index 3d1ced9a..5d028dfe 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -1591,6 +1591,9 @@ private function _fetch( /** @var \Laminas\Http\Client $client */ $client = $this->clientFactory->create(); + $client->setOptions([ + 'httpversion' => '1.1' + ]); $request->setMethod($method); $request->setUri($uri); $request->setHeaders($headers); From 058d5b10d5e5dded3d03230e2a6b3248b3e93491 Mon Sep 17 00:00:00 2001 From: Domagoj Potkoc Date: Thu, 19 Jan 2023 11:41:21 +0100 Subject: [PATCH 27/27] api.php --- Model/Api.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Model/Api.php b/Model/Api.php index 5d028dfe..b1852f1e 100644 --- a/Model/Api.php +++ b/Model/Api.php @@ -1091,12 +1091,12 @@ public function sendWebHook($message) $request->setMethod(Request::METHOD_POST); $request->setHeaders($headers); $request->setContent($body); - try{ + try { $response = $client->send($request); if ($response->getStatusCode() != 200) { $this->log->log(100, 'Failed to send message to the following Webhook: ' . $url); } - }catch (\Exception $e){ + } catch (\Exception $e) { $this->log->log(100, 'Failed to send message to the following Webhook: ' . $url); } } @@ -1581,7 +1581,6 @@ private function _fetch( // Request method specific header & option changes switch ($method) { case Request::METHOD_PUT: - $headers->addHeaderLine('Content-Type: application/x-www-form-urlencoded'); break; case Request::METHOD_PATCH: @@ -1597,7 +1596,7 @@ private function _fetch( $request->setMethod($method); $request->setUri($uri); $request->setHeaders($headers); - if($body){ + if ($body) { $request->setContent($body); } $response = $client->send($request);