Subject: [PATCH] Moving getConfig() calls to be closer to the dependent HTTP requests.
---
Index: src/Service/ConstantContact.php
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/src/Service/ConstantContact.php b/src/Service/ConstantContact.php
--- a/src/Service/ConstantContact.php	(revision 94535f0411d737a60bb8dddf324014b1f574d110)
+++ b/src/Service/ConstantContact.php	(date 1710855956979)
@@ -253,9 +253,9 @@
 
   /**
    * Get token data.
-   * 
-   * Checks to see if ik_constant_contact_tokens table exists and pulls from there. 
-   * Otherwise pull from config. 
+   *
+   * Checks to see if ik_constant_contact_tokens table exists and pulls from there.
+   * Otherwise pull from config.
    * @see https://www.drupal.org/project/ik_constant_contact/issues/3215168
    *
    * @return array
@@ -266,7 +266,7 @@
 
     if ($schema->tableExists('ik_constant_contact_tokens')) {
       $tokens = $this->database->select('ik_constant_contact_tokens', 'cct')->fields('cct')->range(0,1)->orderBy('timestamp', 'DESC')->execute()->fetchAssoc();
-      
+
       if ($tokens) {
         $tokens['source'] = 'database';
       }
@@ -290,10 +290,10 @@
 
   /**
    * Shared method to generate the rest of the request body.
-   * 
+   *
    * @NOTE that email_address, permission_to_send are not added hear since the fields are
-   * different per api call type. For example, the list_memberships, the email_address field. 
-   * 
+   * different per api call type. For example, the list_memberships, the email_address field.
+   *
    * @see https://v3.developer.constantcontact.com/api_guide/contacts_create_or_update.html#method-request-body
    *
    * @param array $data - posted data from our form
@@ -340,8 +340,6 @@
    * @see https://v3.developer.constantcontact.com/api_reference/index.html#!/Contacts/createContact
    */
   private function createContact(array $data, $listIDs) {
-    $config = $this->getConfig();
-
     $body = (object) [
       'email_address' => (object) [
         'address' => NULL,
@@ -364,6 +362,10 @@
     $this->moduleHandler->invokeAll('ik_constant_contact_contact_data_alter', [$data, &$body]);
     $this->moduleHandler->invokeAll('ik_constant_contact_contact_create_data_alter', [$data, &$body]);
 
+    // Waiting to pull the configuration until now in case the refreshToken()
+    // call changes the active tokens.
+    $config = $this->getConfig();
+
     try {
       $response = $this->httpClient->request('POST', $config['contact_url'], [
         'headers' => [
@@ -422,7 +424,7 @@
    * @return mixed
    *   An stdClass of the campaign.
    * @throws \GuzzleHttp\Exception\GuzzleException
-   * 
+   *
    * @see https://v3.developer.constantcontact.com/api_guide/email_campaign_id.html
    */
   public function getCampaign(string $id) {
@@ -460,7 +462,7 @@
    * @return mixed
    *   A stdClass of the activity.
    * @throws \GuzzleHttp\Exception\GuzzleException
-   * 
+   *
    * @see https://v3.developer.constantcontact.com/api_guide/email_campaigns_activity_id.html
    */
   public function getCampaignActivity(string $id) {
@@ -500,7 +502,7 @@
    * @return array
    *   An array of campaigns.
    * @throws \GuzzleHttp\Exception\GuzzleException
-   * 
+   *
    * @see https://v3.developer.constantcontact.com/api_guide/email_campaigns_collection.html
    */
   public function getCampaigns($status = []) {
@@ -591,9 +593,9 @@
 
   /**
    * Gets contact lists from Constant Contact API.
-   * 
-   * @param $cached 
-   *  Whether to return a cached response or not. 
+   *
+   * @param $cached
+   *  Whether to return a cached response or not.
    *  @see https://www.drupal.org/project/ik_constant_contact/issues/3282088 and https://v3.developer.constantcontact.com/api_guide/faqs_manage_applications.html
    *  Cron run perhaps was calling Drupal cached version which may have allowed refresh tokens to expire.
    *
@@ -601,10 +603,9 @@
    *   Returns an array of lists that the account has access to.
    *
    * @see https://v3.developer.constantcontact.com/api_reference/index.html#!/Contact_Lists/getLists
-   * 
+   *
    */
   public function getContactLists($cached = true) {
-    $config = $this->getConfig();
     $cid = 'ik_constant_contact.lists';
     $cache = ($cached === true ? $this->cache->get($cid) : null);
 
@@ -615,6 +616,10 @@
       // Update access tokens.
       $this->refreshToken(false);
 
+      // Waiting to pull the configuration until now in case the refreshToken()
+      // call changes the active tokens.
+      $config = $this->getConfig();
+
       if (isset($config['access_token'])) {
         try {
           $response = $this->httpClient->request('GET', $config['contact_lists_url'], [
@@ -664,13 +669,13 @@
 
   /**
    * Returns custom fields available
-   * 
-   * @param $cached 
-   *  Whether to return a cached response or not. 
-   * 
+   *
+   * @param $cached
+   *  Whether to return a cached response or not.
+   *
    * @return mixed
    *   A stdClass of custom fields.
-   * 
+   *
    * @see https://v3.developer.constantcontact.com/api_guide/get_custom_fields.html
    */
   public function getCustomFields($cached = true) {
@@ -682,7 +687,7 @@
       return $cache->data;
     }
     else {
-    
+
       $url = $this->apiUrl . '/contact_custom_fields';
 
       try {
@@ -760,11 +765,11 @@
   }
 
   /**
-   * Get Enabled Contact Lists 
+   * Get Enabled Contact Lists
    *
    * @param boolean $cached
    * @return array $lists of enabled lists
-   * 
+   *
    * @see /Drupal/Form/ConstantContactLists.php
    */
   public function getEnabledContactLists($cached = true) {
@@ -830,15 +835,15 @@
       if (property_exists($error, 'message')) {
         $errorInfo[] = $error->message;
       }
-  
+
       if (property_exists($error, 'error_description')) {
         $errorInfo[] = $error->error_description;
       }
-  
+
       if (property_exists($error, 'errorCode')) {
         $errorInfo[] = $error->errorSummary;
       }
-  
+
       if (property_exists($error, 'errorCode')) {
         $errorInfo[] = $error->errorCode;
       }
@@ -897,7 +902,7 @@
   }
 
   /**
-   * Submits a contact to the API. 
+   * Submits a contact to the API.
    * Used to be used on CostantContactBlockForm but using $this->submitContactForm instead.
    * Determine if contact needs to be updated or created.
    *
@@ -943,9 +948,9 @@
     foreach ($listIDs as $listID) {
       if (!isset($enabled[$listID]) || $enabled[$listID] !== 1) {
         $msg = 'The listID provided does not exist or is not enabled.';
-  
+
         $this->loggerFactory->error($msg);
-  
+
         return [
           'error' => $msg,
         ];
@@ -999,14 +1004,12 @@
    * an array here and an object in updateContact.
    */
   private function putContact(array $contact, array $data, $listIDs) {
-    $config = $this->getConfig();
-
     $body = (object) $contact;
 
     $body = $this->buildResponseBody($data, $body);
 
     $body->email_address->permission_to_send = 'implicit';
-    // To resubscribe a contact after an unsubscribe update_source must equal Contact. 
+    // To resubscribe a contact after an unsubscribe update_source must equal Contact.
     // @see https://v3.developer.constantcontact.com/api_guide/contacts_re-subscribe.html#re-subscribing-contacts
     $body->update_source = 'Contact';
     $body->list_memberships = $listIDs;
@@ -1014,6 +1017,10 @@
     $this->moduleHandler->invokeAll('ik_constant_contact_contact_data_alter', [$data, &$body]);
     $this->moduleHandler->invokeAll('ik_constant_contact_contact_update_data_alter', [$data, &$body]);
 
+    // Waiting to pull the config until now so that any config changes can take
+    // immediate effect.
+    $config = $this->getConfig();
+
     try {
       $response = $this->httpClient->request('PUT', $config['contact_url'] . '/' . $contact['contact_id'], [
         'headers' => [
@@ -1055,7 +1062,7 @@
       return FALSE;
     }
 
-    // @TODO - Fix for pkce flow. 
+    // @TODO - Fix for pkce flow.
     // @see https://www.drupal.org/project/ik_constant_contact/issues/3285446
     // @see https://v3.developer.constantcontact.com/api_guide/pkce_flow.html
     try {
@@ -1097,11 +1104,11 @@
   public function saveContactLists(array $data) {
     $cid = 'ik_constant_contact.lists';
     $enabled = $this->config->get('ik_constant_contact.enabled_lists')->getRawData();
-    
+
     // Add an enabled flag to the list data.
     foreach ($data as $key => $value) {
       $data[$key]->enabled = (isset($enabled[$key]) && $enabled[$key] === 1);
-      $data[$key]->cached_on = strtotime('now'); 
+      $data[$key]->cached_on = strtotime('now');
     }
 
     $this->cache->set($cid, $data);
@@ -1192,9 +1199,9 @@
     foreach ($listIDs as $listID) {
       if (!isset($enabled[$listID]) || $enabled[$listID] !== 1) {
         $msg = 'The listID provided does not exist or is not enabled.';
-  
+
         $this->loggerFactory->error($msg);
-  
+
         return [
           'error' => $msg,
         ];
@@ -1225,6 +1232,10 @@
     $this->moduleHandler->invokeAll('ik_constant_contact_contact_data_alter', [$data, &$body]);
     $this->moduleHandler->invokeAll('ik_constant_contact_contact_form_submission_alter', [$data, &$body]);
 
+    // Pulling the config again so that any config changes can take immediate
+    // effect.
+    $config = $this->getConfig();
+
     try {
       $response = $this->httpClient->request('POST', $config['contact_url'] . '/sign_up_form', [
         'headers' => [
@@ -1267,7 +1278,6 @@
    *
    */
   public function unsubscribeContact(array $data) {
-    $config = $this->getConfig();
     // Check if contact already exists.
     $exists = (array) $this->getContact($data);
     $body = null;
@@ -1284,13 +1294,17 @@
       $body = $this->buildResponseBody($data, $body);
 
       $body->email_address->permission_to_send = 'unsubscribed';
-      // To resubscribe a contact after an unsubscribe update_source must equal Contact. 
+      // To resubscribe a contact after an unsubscribe update_source must equal Contact.
       // @see https://v3.developer.constantcontact.com/api_guide/contacts_re-subscribe.html#re-subscribing-contacts
       $body->update_source = 'Contact';
 
       $this->moduleHandler->invokeAll('ik_constant_contact_contact_data_alter', [$data, &$body]);
       $this->moduleHandler->invokeAll('ik_constant_contact_contact_unsubscribe_data_alter', [$data, &$body]);
 
+      // Waiting to pull the config until now so that any config changes can take
+      // immediate effect.
+      $config = $this->getConfig();
+
       try {
         $response = $this->httpClient->request('PUT', $config['contact_url'] . '/' . $exists->contact_id, [
           'headers' => [
@@ -1335,10 +1349,8 @@
    * @see https://v3.developer.constantcontact.com/api_reference/index.html#!/Contacts/putContact
    */
   private function updateContact(array $data, $contact, $listIDs) {
-    $config = $this->getConfig();
-
     if ($contact && property_exists($contact, 'contact_id')) {
-      
+
       $body = $contact;
       $body = $this->buildResponseBody($data, $body);
 
@@ -1351,6 +1363,10 @@
       $this->moduleHandler->invokeAll('ik_constant_contact_contact_data_alter', [$data, &$body]);
       $this->moduleHandler->invokeAll('ik_constant_contact_contact_update_data_alter', [$data, &$body]);
 
+      // Waiting to pull the config until now so that any config changes can take
+      // immediate effect.
+      $config = $this->getConfig();
+
       try {
         $response = $this->httpClient->request('PUT', $config['contact_url'] . '/' . $contact->contact_id, [
           'headers' => [
@@ -1374,7 +1390,7 @@
       }
       catch (\Exception $e) {
         $this->loggerFactory->error($e);
-  
+
         // Return the error to show an error on form submission
         return ['error' => $e];
       }
