MAILCHIMP_TOKENS::audience_field_possible_tokens( $tokens = array(),  $args = array() )


Parameters Parameters

$tokens

(Optional)

Default value: array()

$args

(Optional)

Default value: array()


Top ↑

Return Return

(array|mixed)


Source Source

File: src/integrations/mailchimp/tokens/mailchimp-tokens.php

	public function audience_field_possible_tokens( $tokens = array(), $args = array() ) {

		// If its from heartbeat, or if its not from recipe edit page, or if not from automator rest, bail out.
		if ( false === $this->is_recipe_or_rest() ) {
			return $tokens;
		}

		// If the value is empty, bail.
		if ( empty( $args['value'] ) ) {
			return $tokens;
		}

		$list_id = $args['value'];

		// If value is "Any", bail.
		if ( '-1' === $list_id ) {
			return $tokens;
		}

		$request_params = array(
			'action'  => 'get_list_fields',
			'list_id' => $list_id,
		);

		// Transient is unique for each Audience.
		$key = 'automator_mailchimp_audience_' . $list_id . '_fields';

		$fields = get_transient( $key );

		if ( false === $fields ) {

			try {

				$has_requested = Automator()->cache->get( 'automator_mailchimp_audience_tokens_has_requested' );

				// Avoid multiple API calls.
				if ( false === $has_requested ) {

					// Request from MailChimp api if there are no transients saved.
					$response = Automator()->helpers->recipe->mailchimp->options->api_request( $request_params );

					if ( isset( $response['data']['merge_fields'] ) && ! empty( $response['data']['merge_fields'] ) ) {

						foreach ( $response['data']['merge_fields'] as $field ) {

							$fields[] = array(
								'tokenId'         => $field['tag'],
								'tokenName'       => $field['name'],
								'tokenType'       => 'text',
								'tokenIdentifier' => 'MAILCHIMP_MERGEFIELD_' . $field['tag'],
							);

						}

						set_transient( $key, $fields, 5 * MINUTE_IN_SECONDS );

					}

					Automator()->cache->set( 'automator_mailchimp_audience_tokens_has_requested', 'yes' );
				}
			} catch ( \Exception $e ) {

				$response = array();

				automator_log( $e->getMessage(), 'MailChimp error', true );

			}
		}

		if ( is_array( $fields ) ) {

			$tokens = array_merge( (array) $tokens, (array) $fields );

		}

		return $tokens;

	}