You are here

class MailChimpTest in Mailchimp 7.2

Same name and namespace in other branches
  1. 7.3 tests/mailchimp_test.inc \MailChimpTest

@file A virtual MailChimp API implementation for use in testing.

Hierarchy

Expanded class hierarchy of MailChimpTest

1 string reference to 'MailChimpTest'
MailchimpListsBasicTestCase::setUp in modules/mailchimp_lists/tests/mailchimp_lists.test
Pre-test setup function.

File

tests/mailchimp_tests.inc, line 7
A virtual MailChimp API implementation for use in testing.

View source
class MailChimpTest extends MailChimp {

  /**
   * Get the details of an email address's settings in a particular list.
   *
   * @return array
   *   An array that counts the successes and failures, and contains
   *   a Data index for the info. Only supports a single operation despite
   *   the structure of the success and error indexes.
   */
  public function listMemberInfo($id, $email_address) {
    $lists = $this
      ->loadLists();
    $ret = array(
      'success' => 0,
      'errors' => 0,
      'data' => array(),
    );
    if (isset($lists[$id]['data'][$email_address[0]])) {
      $member = $lists[$id]['data'][$email_address[0]];
      $ret['success'] = 1;
      $ret['data'][] = array(
        'email' => $email_address[0],
        'email_type' => $member['email_type'],
        'merges' => $member['merge_vars'],
        'status' => $member['subscribed'] ? 'subscribed' : 'unsubscribed',
      );
    }
    else {
      $ret['errors'] = 1;
    }
    return $ret;
  }

  /**
   * Get the mergevars for a list.
   *
   * @return array|bool
   *   Returns an array of mergevars if they exist, otherwise false.
   */
  public function listMergeVars($id) {
    $lists = $this
      ->loadLists();
    if (isset($lists[$id]) && isset($lists[$id]['mergevars'])) {
      return $lists[$id]['mergevars'];
    }
    return FALSE;
  }

  /**
   * Subscribe a user to a list.
   *
   * @return bool
   *   TRUE if user was added or subscribed, otherwise FALSE.
   */
  public function listSubscribe($id, $email_address, $merge_vars = NULL, $email_type = 'html', $double_optin = TRUE, $update_existing = FALSE, $replace_interests = TRUE, $send_welcome = FALSE) {
    $lists = $this
      ->loadLists();
    if (isset($lists[$id])) {
      if (isset($lists[$id]['data'][$email_address])) {
        $lists[$id]['data'][$email_address]['subscribed'] = TRUE;
      }
      else {
        $lists[$id]['data'][$email_address] = array(
          'subscribed' => TRUE,
          'email_type' => $email_type,
          'merge_vars' => $merge_vars,
        );
      }
      $this
        ->writeLists($lists);
      return TRUE;
    }
    else {
      $this->errorMessage = "Could not add " . $email_address . " to non-existant list: " . $id;
      return FALSE;
    }
  }

  /**
   * Batch subscribe method.
   */
  public function listBatchSubscribe($id, $batch, $double_optin = TRUE, $update_existing = FALSE, $replace_interests = TRUE) {
    foreach ($batch as $sub) {
      $email = isset($sub['EMAIL']) ? $sub['EMAIL'] : NULL;
      $this
        ->listSubscribe($id, $email, $merge_vars = $sub, 'html', TRUE, TRUE);
    }
  }

  /**
   * Unsubscribe a user from a list.
   *
   * @return bool
   *   True if the user was removed, false if unnecessary or no such list.
   */
  public function listUnsubscribe($id, $email_address, $delete_member = FALSE, $send_goodbye = TRUE, $send_notify = TRUE) {
    $lists = $this
      ->loadLists();
    if (isset($lists[$id])) {
      if (isset($lists[$id]['data'][$email_address])) {
        if ($lists[$id]['data'][$email_address]['subscribed']) {
          if ($delete_member) {
            unset($lists[$id]['data'][$email_address]);
          }
          else {
            $lists[$id]['data'][$email_address]['subscribed'] = FALSE;
          }
          $this
            ->writeLists($lists);
          return TRUE;
        }
        else {
          $this->errorMessage = "Could not unsubscribe " . $email_address . " from: " . $id . ": not currently subscribed.";
        }
      }
      else {
        $this->errorMessage = "Could not unsubscribe " . $email_address . " from: " . $id . ": address not on list";
      }
    }
    else {
      $this->errorMessage = "Could not unsubscribe " . $email_address . " from non-existant list: " . $id;
    }
    return FALSE;
  }

  /**
   * Emulates batch unsubscribe.
   */
  public function listBatchUnsubscribe($id, $emails, $delete_member = FALSE, $send_goodbye = TRUE, $send_notify = TRUE) {
    foreach ($emails as $email) {
      $this
        ->listUnsubscribe($id, $email, $delete_member, $send_goodbye, $send_notify);
    }
  }

  /**
   * Update a list member.
   *
   * @return bool
   *   True if an update took place, otherwise False.
   */
  public function listUpdateMember($id, $email_address, $merge_vars, $email_type = '', $replace_interests = TRUE) {
    $lists = $this
      ->loadLists();
    if (isset($lists[$id])) {
      if (isset($lists[$id]['data'][$email_address])) {
        foreach ($merge_vars as $var => $value) {
          $lists[$id]['data'][$email_address]['merge_vars'][$var] = $value;
        }
        if (isset($merge_vars['EMAIL']) && strcmp($email_address, $merge_vars['EMAIL'])) {
          $lists[$id][$merge_vars['EMAIL']] = $lists[$id]['data'][$email_address];
          unset($lists[$id]['data'][$email_address]);
        }
        $this
          ->writeLists($lists);
        return TRUE;
      }
      else {
        $this->errorMessage = "Could not update " . $email_address . " on: " . $id . ": not currently a member.";
      }
    }
    else {
      $this->errorMessage = "Could not update " . $email_address . " on non-existant list: " . $id;
    }
    return FALSE;
  }

  /**
   * Load lists.
   *
   * @return array
   *   Stored lists formatted as the actual MC API returns them.
   */
  public function lists($filters = array(), $start = 0, $limit = 25, $sort_field = 'created', $sort_dir = 'DESC') {
    $lists = $this
      ->loadLists();
    $ret = array(
      'data' => array(),
      'total' => 0,
    );
    foreach ($lists as $list_id => $list_array) {
      $ret['data'][] = array(
        'id' => $list_id,
        'name' => $list_array['name'],
      );
      $ret['total']++;
    }
    return $ret;
  }

  /**
   * Loads list values, initializing if necessary.
   *
   * @return array
   *   Stored lists.
   */
  protected function loadLists() {
    $list_data = variable_get('mailchimp_test_list_data', $this
      ->defaultLists());
    return $list_data;
  }

  /**
   * Creates initial list values.
   *
   * @return array
   *   Basic lists.
   */
  protected function defaultLists() {
    $default_mergevars = array();
    $default_mergevars[] = array(
      'name' => 'Email',
      'order' => 0,
      'tag' => 'EMAIL',
      'req' => TRUE,
      'webid' => 'test',
      'field_type' => 'text',
      'size' => 40,
      'default' => '',
      'public' => TRUE,
    );
    $default_mergevars[] = array(
      'name' => 'First Name',
      'order' => 1,
      'tag' => 'FIRSTNAME',
      'req' => FALSE,
      'webid' => 'test',
      'field_type' => 'text',
      'size' => 40,
      'default' => '',
      'public' => TRUE,
    );
    $default_mergevars[] = array(
      'name' => 'Last Name',
      'order' => 2,
      'tag' => 'LASTNAME',
      'req' => FALSE,
      'web_id' => 'test',
      'field_type' => 'text',
      'size' => 40,
      'default' => '',
      'public' => TRUE,
    );
    $lists = array(
      MAILCHIMP_TESTLIST_ANONYMOUS => array(
        'name' => 'Test List A',
        'data' => array(),
        'mergevars' => $default_mergevars,
      ),
      MAILCHIMP_TESTLIST_OPTIONAL => array(
        'name' => 'Test List B',
        'data' => array(),
        'mergevars' => $default_mergevars,
      ),
      MAILCHIMP_TESTLIST_REQUIRED => array(
        'name' => 'Test List C',
        'data' => array(),
        'mergevars' => $default_mergevars,
      ),
    );
    return $lists;
  }

  /**
   * Saves list changes.
   */
  protected function writeLists($lists) {
    variable_set('mailchimp_test_list_data', $lists);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
MailChimp::callServer public function Override MCAPI::callServer() to leverage Drupal's core HTTP handling. Overrides MCAPI::callServer
MailChimpTest::defaultLists protected function Creates initial list values.
MailChimpTest::listBatchSubscribe public function Batch subscribe method. Overrides MCAPI::listBatchSubscribe
MailChimpTest::listBatchUnsubscribe public function Emulates batch unsubscribe. Overrides MCAPI::listBatchUnsubscribe
MailChimpTest::listMemberInfo public function Get the details of an email address's settings in a particular list. Overrides MCAPI::listMemberInfo
MailChimpTest::listMergeVars public function Get the mergevars for a list. Overrides MCAPI::listMergeVars
MailChimpTest::lists public function Load lists. Overrides MCAPI::lists
MailChimpTest::listSubscribe public function Subscribe a user to a list. Overrides MCAPI::listSubscribe
MailChimpTest::listUnsubscribe public function Unsubscribe a user from a list. Overrides MCAPI::listUnsubscribe
MailChimpTest::listUpdateMember public function Update a list member. Overrides MCAPI::listUpdateMember
MailChimpTest::loadLists protected function Loads list values, initializing if necessary.
MailChimpTest::writeLists protected function Saves list changes.
MCAPI::$apiUrl property Cache the information on the API location on the server
MCAPI::$api_key property Cache the user api_key so we only have to log in once per client instantiation
MCAPI::$chunkSize property Default to a 8K chunk size
MCAPI::$errorCode property
MCAPI::$errorMessage property
MCAPI::$secure property Cache the user api_key so we only have to log in once per client instantiation
MCAPI::$timeout property Default to a 300 second timeout on server calls
MCAPI::$version property
MCAPI::apikeyAdd function Add an API Key to your account. We will generate a new key for you and return it.
MCAPI::apikeyExpire function Expire a Specific API Key. Note that if you expire all of your keys, a new, valid one will be created and returned next time you call login(). If you are trying to shut off access to your account for an old developer, change your MailChimp password,…
MCAPI::apikeys function Retrieve a list of all MailChimp API Keys for this User
MCAPI::callMethod function Internal function - proxy method for certain XML-RPC calls | DO NOT CALL
MCAPI::campaignAbuseReports function Get all email addresses that complained about a given campaign
MCAPI::campaignAdvice function Retrieve the text presented in our app for how a campaign performed and any advice we may have for you - best suited for display in customized reports pages. Note: some messages will contain HTML - clean tags as necessary
MCAPI::campaignAnalytics function Retrieve the Google Analytics data we've collected for this campaign. Note, requires Google Analytics Add-on to be installed and configured.
MCAPI::campaignBounceMessages function Retrieve the full bounce messages for the given campaign. Note that this can return very large amounts of data depending on how large the campaign was and how much cruft the bounce provider returned. Also, message over 30 days old are subject to being…
MCAPI::campaignClickDetailAIM function Return the list of email addresses that clicked on a given url, and how many times they clicked
MCAPI::campaignClickStats function Get an array of the urls being tracked, and their click counts for a given campaign
MCAPI::campaignContent function Get the content (both html and text) for a campaign either as it would appear in the campaign archive or as the raw, original content
MCAPI::campaignCreate function Create a new draft campaign to send
MCAPI::campaignDelete function Delete a campaign. Seriously, "poof, gone!" - be careful!
MCAPI::campaignEcommAddOrder function Attach Ecommerce Order Information to a Campaign. This will generall be used by ecommerce package plugins <a href="/plugins/ecomm360.phtml">that we provide</a> or by 3rd part system developers.
MCAPI::campaignEcommOrders function Retrieve the Ecommerce Orders tracked by campaignEcommAddOrder()
MCAPI::campaignEmailDomainPerformance function Get the top 5 performing email domains for this campaign. Users want more than 5 should use campaign campaignEmailStatsAIM() or campaignEmailStatsAIMAll() and generate any additional stats they require.
MCAPI::campaignEmailStatsAIM function Given a campaign and email address, return the entire click and open history with timestamps, ordered by time
MCAPI::campaignEmailStatsAIMAll function Given a campaign and correct paging limits, return the entire click and open history with timestamps, ordered by time, for every user a campaign was delivered to.
MCAPI::campaignFolders function List all the folders for a user account
MCAPI::campaignHardBounces function Get all email addresses with Hard Bounces for a given campaign
MCAPI::campaignNotOpenedAIM function Retrieve the list of email addresses that did not open a given campaign
MCAPI::campaignOpenedAIM function Retrieve the list of email addresses that opened a given campaign with how many times they opened - note: this AIM function is free and does not actually require the AIM module to be installed
MCAPI::campaignPause function Pause an AutoResponder orRSS campaign from sending
MCAPI::campaignReplicate function Replicate a campaign.
MCAPI::campaignResume function Resume sending an AutoResponder or RSS campaign
MCAPI::campaigns function Get the list of campaigns and their details matching the specified filters
MCAPI::campaignSchedule function Schedule a campaign to be sent in the future
MCAPI::campaignSegmentTest function Allows one to test their segmentation rules before creating a campaign using them
MCAPI::campaignSendNow function Send a given campaign immediately
MCAPI::campaignSendTest function Send a test of this campaign to the provided email address
MCAPI::campaignShareReport function Get the URL to a customized VIP Report for the specified campaign and optionally send an email to someone with links to it. Note subsequent calls will overwrite anything already set for the same campign (eg, the password)
MCAPI::campaignSoftBounces function Get all email addresses with Soft Bounces for a given campaign
MCAPI::campaignStats function Given a list and a campaign, get all the relevant campaign statistics (opens, bounces, clicks, etc.)
MCAPI::campaignTemplates function Retrieve all templates defined for your user account
MCAPI::campaignUnschedule function Unschedule a campaign that is scheduled to be sent in the future
MCAPI::campaignUnsubscribes function Get all unsubscribed email addresses for a given campaign
MCAPI::campaignUpdate function Update just about any setting for a campaign that has <em>not</em> been sent. See campaignCreate() for details
MCAPI::createFolder function Create a new folder to file campaigns in
MCAPI::generateText function Have HTML content auto-converted to a text-only format. You can send: plain HTML, an array of Template content, an existing Campaign Id, or an existing Template Id. Note that this will <b>not</b> save anything to or update any of your…
MCAPI::getAccountDetails function Retrieve lots of account information including payments made, plan info, some account stats, installed modules, contact info, and more. No private information like Credit Card numbers is available.
MCAPI::getAffiliateInfo Deprecated function <strong>DEPRECATED:</strong> Retrieve your User Unique Id and your Affiliate link to display/use for <a href="/monkeyrewards/" target="_blank">Monkey Rewards</a>. While we don't use the User Id for any…
MCAPI::getTimeout function
MCAPI::httpBuildQuery function Re-implement http_build_query for systems that do not already have it
MCAPI::inlineCss function Send your HTML content to have the CSS inlined and optionally remove the original styles.
MCAPI::listAbuseReports function Get all email addresses that complained about a given campaign
MCAPI::listGrowthHistory function Access the Growth History by Month for a given list.
MCAPI::listInterestGroupAdd function Add a single Interest Group - if interest groups for the List are not yet enabled, adding the first group will automatically turn them on.
MCAPI::listInterestGroupDel function Delete a single Interest Group - if the last group for a list is deleted, this will also turn groups for the list off.
MCAPI::listInterestGroups function Get the list of interest groups for a given list, including the label and form information
MCAPI::listInterestGroupUpdate function Change the name of an Interest Group
MCAPI::listMembers function Get all of the list members for a list that are of a particular status
MCAPI::listMergeVarAdd function Add a new merge tag to a given list
MCAPI::listMergeVarDel function Delete a merge tag from a given list and all its members. Seriously - the data is removed from all members as well! Note that on large lists this method may seem a bit slower than calls you typically make.
MCAPI::listMergeVarUpdate function Update most parameters for a merge tag on a given list. You cannot currently change the merge type
MCAPI::listWebhookAdd function Add a new Webhook URL for the given list
MCAPI::listWebhookDel function Delete an existing Webhook URL from a given list
MCAPI::listWebhooks function Return the Webhooks configured for the given list
MCAPI::MCAPI function Connect to the MailChimp API for a given list. All MCAPI calls require login before functioning
MCAPI::ping function "Ping" the MailChimp API - a simple method you can call that will return a constant value as long as everything is good. Note than unlike most all of our methods, we don't throw an Exception if we are having issues. You will simply…
MCAPI::setTimeout function
MCAPI::useSecure function