<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use ArrayAccess;
use InvalidArgumentException;

class CustomData implements ArrayAccess {

  /**
   * Array of property to type mappings. Used for (de)serialization
   * @var string[]
   */
  protected static $param_types = array(
    'value' => 'float',
    'currency' => 'string',
    'content_name' => 'string',
    'content_category' => 'string',
    'content_ids' => 'string[]',
    'contents' => 'object[]',
    'content_type' => 'string',
    'order_id' => 'string',
    'predicted_ltv' => 'float',
    'num_items' => 'string',
    'status' => 'string',
    'search_string' => 'string',
    'item_number' => 'string',
    'delivery_category' => 'string',
    'custom_properties' => 'array'
  );
  /**
   * Array of attributes where the key is the local name, and the value is the original name
   * @var string[]
   */
  protected static $attributeMap = array(
    'value' => 'value',
    'currency' => 'currency',
    'content_name' => 'content_name',
    'content_category' => 'content_category',
    'content_ids' => 'content_ids',
    'contents' => 'contents',
    'content_type' => 'content_type',
    'order_id' => 'order_id',
    'predicted_ltv' => 'predicted_ltv',
    'num_items' => 'num_items',
    'status' => 'status',
    'search_string' => 'search_string',
    'item_number' => 'item_number',
    'delivery_category' => 'delivery_category',
    'custom_properties' => 'custom_properties'
  );
  /**
   * Array of attributes to setter functions (for deserialization of responses)
   * @var string[]
   */
  protected static $setters = array(
    'value' => 'setValue',
    'currency' => 'setCurrency',
    'content_name' => 'setContentName',
    'content_category' => 'setContentCategory',
    'content_ids' => 'setContentIds',
    'contents' => 'setContents',
    'content_type' => 'setContentType',
    'order_id' => 'setOrderId',
    'predicted_ltv' => 'setPredictedLtv',
    'num_items' => 'setNumItems',
    'status' => 'setStatus',
    'search_string' => 'setSearchString',
    'item_number' => 'setItemNumber',
    'delivery_category' => 'setDeliveryCategory',
    'custom_properties' => 'setCustomProperties'
  );
  /**
   * Array of attributes to getter functions (for serialization of requests)
   * @var string[]
   */
  protected static $getters = array(
    'value' => 'getValue',
    'currency' => 'getCurrency',
    'content_name' => 'getContentName',
    'content_category' => 'getContentCategory',
    'content_ids' => 'getContentIds',
    'contents' => 'getContents',
    'content_type' => 'getContentType',
    'order_id' => 'getOrderId',
    'predicted_ltv' => 'getPredictedLtv',
    'num_items' => 'getNumItems',
    'status' => 'getStatus',
    'search_string' => 'getSearchString',
    'item_number' => 'getItemNumber',
    'delivery_category' => 'getDeliveryCategory',
    'custom_properties' => 'getCustomProperties'
  );
  /**
   * Associative array for storing property values
   * @var mixed[]
   */
  protected $container = array();

  /**
   * Constructor
   * @param mixed[] $data Associated array of property value initializing the model
   */
  public function __construct(array $data = null) {
    $this->container['value'] = isset($data['value']) ? $data['value'] : null;
    $this->container['currency'] = isset($data['currency']) ? $data['currency'] : null;
    $this->container['content_name'] = isset($data['content_name']) ? $data['content_name'] : null;
    $this->container['content_category'] = isset($data['content_category']) ? $data['content_category'] : null;
    $this->container['content_ids'] = isset($data['content_ids']) ? $data['content_ids'] : null;
    $this->container['contents'] = isset($data['contents']) ? $data['contents'] : null;
    $this->container['content_type'] = isset($data['content_type']) ? $data['content_type'] : null;
    $this->container['order_id'] = isset($data['order_id']) ? $data['order_id'] : null;
    $this->container['predicted_ltv'] = isset($data['predicted_ltv']) ? $data['predicted_ltv'] : null;
    $this->container['num_items'] = isset($data['num_items']) ? $data['num_items'] : null;
    $this->container['status'] = isset($data['status']) ? $data['status'] : null;
    $this->container['search_string'] = isset($data['search_string']) ? $data['search_string'] : null;
    $this->container['item_number'] = isset($data['item_number']) ? $data['item_number'] : null;
    $this->container['delivery_category'] = isset($data['delivery_category']) ? $data['delivery_category'] : null;
    $this->container['custom_properties'] = isset($data['custom_properties']) ? $data['custom_properties'] : null;
  }

  public static function paramTypes() {
    return self::$param_types;
  }

  public static function attributeMap() {
    return self::$attributeMap;
  }

  public static function setters() {
    return self::$setters;
  }

  public static function getters() {
    return self::$getters;
  }

  /**
   * show all the invalid properties with reasons.
   *
   * @return array invalid properties with reasons
   */
  public function listInvalidProperties() {
    $invalid_properties = array();
    return $invalid_properties;
  }

  /**
   * validate all the properties in the model
   * return true if all passed
   *
   * @return bool True if all properteis are valid
   */
  public function valid() {
    return true;
  }

  /**
   * Sets value
   * @param float $value A numeric value associated with this event.
   *         This could be a monetary value or a value in some other metric.
   * @return $this
   */
  public function setValue($value) {
    $this->container['value'] = $value;

    return $this;
  }

  /**
   * Sets currency
   * @param string $currency The currency for the value specified, if applicable.
   *          Currency must be a valid ISO 4217 three digit currency code.
   * @return $this
   */
  public function setCurrency($currency) {
    $this->container['currency'] = $currency;

    return $this;
  }

  /**
   * Sets content_name
   * @param string $content_name The name of the page or product associated with the event. Example: 'lettuce'.
   * @return $this
   */
  public function setContentName($content_name) {
    $this->container['content_name'] = $content_name;

    return $this;
  }

  /**
   * Sets content_category
   * @param string $content_category The category of the content associated with the event. Example: 'grocery'
   * @return $this
   */
  public function setContentCategory($content_category) {
    $this->container['content_category'] = $content_category;

    return $this;
  }

  /**
   * Sets content_ids
   * @param string[] $content_ids The content IDs associated with the event,
   *      such as product SKUs for items in an AddToCart event: ['ABC123', 'XYZ789'].
   *      If content_type is a product, then your content IDs must be an array with a single string value.
   *      Otherwise, this array can contain any number of string values.
   * @return $this
   */
  public function setContentIds($content_ids) {
    $this->container['content_ids'] = $content_ids;

    return $this;
  }

  /**
   * Sets contents
   * @param Content[] $contents A list of Content objects that contain the product IDs associated with
   *          the event plus information about the products.
   * @return $this
   */
  public function setContents($contents) {
    $this->container['contents'] = $contents;

    return $this;
  }

  /**
   * Sets content_type
   * @param string $content_type A String equal to either 'product' or 'product_group'.
   *      Set to product if the keys you send content_ids or contents represent products.
   *      Set to product_group if the keys you send in content_ids represent product groups.
   * @return $this
   */
  public function setContentType($content_type) {
    $this->container['content_type'] = $content_type;

    return $this;
  }

  /**
   * Sets order_id
   * @param string $order_id The order ID for this transaction as a String.
   * @return $this
   */
  public function setOrderId($order_id) {
    $this->container['order_id'] = $order_id;

    return $this;
  }

  /**
   * Sets predicted_ltv
   * @param float $predicted_ltv The predicted lifetime value of a conversion event.
   * @return $this
   */
  public function setPredictedLtv($predicted_ltv) {
    $this->container['predicted_ltv'] = $predicted_ltv;

    return $this;
  }

  /**
   * Sets num_items
   * @param string $num_items Use only with InitiateCheckout events.
   *      The number of items that a user tries to buy during checkout.
   * @return $this
   */
  public function setNumItems($num_items) {
    $this->container['num_items'] = $num_items;

    return $this;
  }

  /**
   * Sets status
   * @param string $status Use only with CompleteRegistration events.
   *      The status of the registration event.
   * @return $this
   */
  public function setStatus($status) {
    $this->container['status'] = $status;

    return $this;
  }

  /**
   * Sets a search query made by a user. Use only with Search events.
   * @param string $search_string Use only with Search events.
   *      A search query made by a user.
   * @return $this
   */
  public function setSearchString($search_string) {
    $this->container['search_string'] = $search_string;

    return $this;
  }

  /**
   * Sets Type of delivery for a purchase event.
   * @param string $delivery_category Type of delivery for a purchase event.
   * @return $this
   */
  public function setDeliveryCategory($delivery_category) {
    $this->container['delivery_category'] = $delivery_category;

    return $this;
  }

  /**
   * Sets the item_number.
   * @param string $item_number The item number.
   * @return $this
   */
  public function setItemNumber($item_number) {
    $this->container['item_number'] = $item_number;

    return $this;
  }

  /**
   * Sets custom_properties that are not defined as the standard properties list in custom data.
   * @param array custom_properties dictionary to include custom properties that are not defined in custom data.
   * @return $this
   */
  public function setCustomProperties($custom_properties) {
    $this->container['custom_properties'] = $custom_properties;
    return $this;
  }

  /**
   * Returns true if offset exists. False otherwise.
   * @param integer $offset Offset
   * @return boolean
   */
  public function offsetExists($offset) : bool {
    return isset($this->container[$offset]);
  }

  /**
   * Gets offset.
   * @param integer $offset Offset
   * @return mixed
   */
  public function offsetGet($offset) : mixed {
    return isset($this->container[$offset]) ? $this->container[$offset] : null;
  }

  /**
   * Sets value based on offset.
   * @param integer $offset Offset
   * @param mixed $value Value to be set
   * @return void
   */
  public function offsetSet($offset, $value) : void {
    if (is_null($offset)) {
      $this->container[] = $value;
    } else {
      $this->container[$offset] = $value;
    }
  }

  /**
   * Unsets offset.
   * @param integer $offset Offset
   * @return void
   */
  public function offsetUnset($offset) : void {
    unset($this->container[$offset]);
  }

  /**
   * Add a custom property to the custom_properties bag
   * @param $key Custom property name
   * @param $value Custom property value
   * @return void
   */
  public function addCustomProperty($key, $value) {
    $this->container['custom_properties'][$key] = $value;
  }

  /**
   * Gets the value of a custom property from the custom_properties bag
   * @param $key Custom property name
   * @return string
   */
  public function getCustomProperty($key) {
    if (array_key_exists(
      $key, $this->container['custom_properties'])) {
      return $this->container['custom_properties'][$key];
    } else {
      throw new \Exception("Key not found in custom properties:'" . $key . "'");
    }
  }

  public function normalize() {
    $normalized_payload = array();

    $normalized_payload['value'] = $this->getValue();
    $normalized_payload['currency'] =
      Normalizer::normalize('currency', $this->getCurrency());
    $normalized_payload['content_name'] = $this->getContentName();
    $normalized_payload['content_category'] = $this->getContentCategory();
    $normalized_payload['content_ids'] = $this->getContentIds();
    $normalized_payload['content_type'] = $this->getContentType();
    $normalized_payload['order_id'] = $this->getOrderId();
    $normalized_payload['predicted_ltv'] = $this->getPredictedLtv();
    $normalized_payload['num_items'] = $this->getNumItems();
    $normalized_payload['status'] = $this->getStatus();
    $normalized_payload['search_string'] = $this->getSearchString();
    $normalized_payload['item_number'] = $this->getItemNumber();
    $normalized_payload['delivery_category'] =
      Normalizer::normalize('delivery_category', $this->getDeliveryCategory());

    if (isset($this->container['contents'])) {
      $contents = [];
      foreach ($this->getContents() as $content) {
        array_push($contents, $content->normalize());
      }
      $normalized_payload['contents'] = $contents;
    }

    if (isset($this->container['custom_properties'])) {
      foreach ($this->getCustomProperties() as $key => $val) {
        if (array_key_exists($key, $normalized_payload)) {
          throw new \Exception('Duplicate key defined as part of the custom_properties. key: "' . $key . '". Please make sure the keys defined in the custom_properties are not already available in standard custom_data property list.');
        }

        $normalized_payload[$key] = $val;
      }
    }

    $normalized_payload = array_filter($normalized_payload, function($val) {
      if (is_array($val)) {
        return true;
      } else {
        return strlen((string) $val);
      }
    });

    return $normalized_payload;

  }

  /**
   * Gets a numeric value associated with this event.
   * This could be a monetary value or a value in some other metric.
   * @return float
   */
  public function getValue() {
    return $this->container['value'];
  }

  /**
   * Gets currency for the value specified, if applicable.
   * @return string
   */
  public function getCurrency() {
    return $this->container['currency'];
  }

  /**
   * Gets content name of the page or product associated with the event. Example: 'lettuce'.
   * @return string
   */
  public function getContentName() {
    return $this->container['content_name'];
  }

  /**
   * Gets the category of the content associated with the event. Example: 'grocery'
   * @return string
   */
  public function getContentCategory() {
    return $this->container['content_category'];
  }

  /**
   * Gets the content IDs associated with the event,
   * such as product SKUs for items in an AddToCart event: ['ABC123', 'XYZ789'].
   * @return string[]
   */
  public function getContentIds() {
    return $this->container['content_ids'];
  }

  /**
   * Gets a list of Content objects that contain the product IDs associated with
   * the event plus information about the products.
   * @return Content[]
   */
  public function getContents() {
    return $this->container['contents'];
  }

  /**
   * Gets content type 'product' or 'product_group'
   * @return string
   */
  public function getContentType() {
    return $this->container['content_type'];
  }

  /**
   * Gets the order ID for this transaction as a String.
   * @return string
   */
  public function getOrderId() {
    return $this->container['order_id'];
  }

  /**
   * Gets the predicted lifetime value of a conversion event.
   * @return float
   */
  public function getPredictedLtv() {
    return $this->container['predicted_ltv'];
  }

  /**
   * Gets the number of items that a user tries to buy during checkout
   * @return string
   */
  public function getNumItems() {
    return $this->container['num_items'];
  }

  /**
   * Gets the status of the registration event
   * @return string
   */
  public function getStatus() {
    return $this->container['status'];
  }

  /**
   * Gets a search query made by a user.
   * @return string
   */
  public function getSearchString() {
    return $this->container['search_string'];
  }

  /**
   * Gets a delivery_category for a purchase order.
   * @return string
   */
  public function getDeliveryCategory() {
    return $this->container['delivery_category'];
  }

  /**
   * Gets the item number.
   * @return string
   */
  public function getItemNumber() {
    return $this->container['item_number'];
  }

  /**
   * Gets Custom Properties dictionary to add properties that are not defined as part of the custom data.
   * @return array
   */
  public function getCustomProperties() {
    return $this->container['custom_properties'];
  }

  /**
   * Gets the string presentation of the object
   * @return string
   */
  public function __toString() {
    if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
      return json_encode($this, JSON_PRETTY_PRINT);
    }

    return json_encode($this);
  }
}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use GuzzleHttp\Promise\PromiseInterface;

/**
 * Interface for Custom Endpoint Request
 *
 * @category Interface
 */
interface CustomEndpointRequest {
    /**
     * Synchronously send events to custom endpoint
     * @param string $pixel_id
     * @param array<Event> $events
     * @return CustomEndpointResponse
     */
    public function sendEvent(string $pixel_id, array $events): CustomEndpointResponse;

    /**
     * Asynchronously send events to custom endpoint
     * @param string $pixel_id
     * @param array<Event> $events
     * @return PromiseInterface
     */
    public function sendEventAsync(string $pixel_id, array $events): PromiseInterface;

    /**
     * Create a filter function that will filter events being sent to endpoint
     * @param Filter $filter
     */
    public function setFilter(Filter $filter);

    /**
     * Sets whether events should be send to this endpoint only
     * @param boolean $setSendToEndpointOnly
     */
    public function setSendToEndpointOnly(bool $setSendToEndpointOnly);

    /**
     * Returns whether events should be sent to this endpoint only
     * @return boolean
     */
    public function isSendToEndpointOnly(): bool;

    /**
     * Returns endpoint URL
     * @return string
     */
    public function getEndpoint(): string;
}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

/**
 * Server side response to a custom endpoint
 */
class CustomEndpointResponse {
    /**
     * Array of property to type mappings. Used for (de)serialization
     * @var string[]
     */
    protected static $param_types = array(
        'message' => 'string',
        'response_code' => 'string'
    );

    /**
     * Associative array for storing property values
     * @var mixed[]
     */
    protected $container = array();

    /**
     * Constructor
     * @param mixed[] $data Associated array of property value initializing the model
     */
    public function __construct(array $data = null) {
        $this->container['message'] = isset($data['message']) ? $data['message'] : null;
        $this->container['response_code'] = isset($data['response_code']) ? $data['response_code'] : null;
    }

    /**
     * Gets the string representation of the object
     * @return string
     */
    public function __toString() {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode($this, JSON_PRETTY_PRINT);
        }
        return json_encode($this);
    }

    /**
     * Gets message
     * @return string
     */
    public function getMessage(): string {
        return $this->container['message'];
    }

    /**
     * Gets response code
     * @return string
     */
    public function getResponseCode(): ?string {
        return $this->container['response_code'];
    }
}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use FacebookAds\Enum\AbstractEnum;

/**
 * Class DeliveryCategory
 *
 * Type of delivery for a purchase event.
 *
 * @package FacebookAds\Object\ServerSide
 */
class DeliveryCategory extends AbstractEnum {

  /**
  * Customer needs to enter the store to get the purchased product.
  */
  const IN_STORE = 'in_store';

  /**
  * Customer picks up their order by driving to a store and waiting inside their vehicle.
  */
  const CURBSIDE = 'curbside';

  /**
  * Purchase is delivered to the customer's home.
  */
  const HOME_DELIVERY = 'home_delivery';
}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use ArrayAccess;

/**
 * Server-Side Event
 *
 * @category    Class
 * @package     FacebookAds\Object\ServerSide
 */
class Event implements ArrayAccess {
  /**
   * Array of property to type mappings. Used for (de)serialization
   * @var string[]
   */
  protected static $param_types = array(
    'event_name' => 'string',
    'event_time' => 'int',
    'event_source_url' => 'string',
    'opt_out' => 'bool',
    'event_id' => 'string',
    'user_data' => 'FacebookAds\Object\ServerSide\UserData',
    'custom_data' => 'FacebookAds\Object\ServerSide\CustomData',
    'data_processing_options' => 'string[]',
    'data_processing_options_country' => 'int',
    'data_processing_options_state' => 'int',
    'action_source' => 'string',
    'app_data' => 'FacebookAds\Object\ServerSide\AppData',
    'advanced_measurement_table' => 'string',
  );
  /**
   * Array of attributes where the key is the local name, and the value is the original name
   * @var string[]
   */
  protected static $attributeMap = array(
    'event_name' => 'event_name',
    'event_time' => 'event_time',
    'event_source_url' => 'event_source_url',
    'opt_out' => 'opt_out',
    'event_id' => 'event_id',
    'user_data' => 'user_data',
    'custom_data' => 'custom_data',
    'data_processing_options' => 'data_processing_options',
    'data_processing_options_country' => 'data_processing_options_country',
    'data_processing_options_state' => 'data_processing_options_state',
    'action_source' => 'action_source',
    'app_data' => 'app_data',
    'advanced_measurement_table' => 'advanced_measurement_table',
  );

  /**
   * Array of attributes to setter functions (for deserialization of responses)
   * @var string[]
   */
  protected static $setters = array(
    'event_name' => 'setEventName',
    'event_time' => 'setEventTime',
    'event_source_url' => 'setEventSourceUrl',
    'opt_out' => 'setOptOut',
    'event_id' => 'setEventId',
    'user_data' => 'setUserData',
    'custom_data' => 'setCustomData',
    'data_processing_options' => 'setDataProcessingOptions',
    'data_processing_options_country' => 'setDataProcessingOptionsCountry',
    'data_processing_options_state' => 'setDataProcessingOptionsState',
    'action_source' => 'setActionSource',
    'app_data' => 'setAppData',
    'advanced_measurement_table' => 'setAdvancedMeasurementTable',
  );
  /**
   * Array of attributes to getter functions (for serialization of requests)
   * @var string[]
   */
  protected static $getters = array(
    'event_name' => 'getEventName',
    'event_time' => 'getEventTime',
    'event_source_url' => 'getEventSourceUrl',
    'opt_out' => 'getOptOut',
    'event_id' => 'getEventId',
    'user_data' => 'getUserData',
    'custom_data' => 'getCustomData',
    'data_processing_options' => 'getDataProcessingOptions',
    'data_processing_options_country' => 'getDataProcessingOptionsCountry',
    'data_processing_options_state' => 'getDataProcessingOptionsState',
    'action_source' => 'getActionSource',
    'app_data' => 'getAppData',
    'advanced_measurement_table' => 'getAdvancedMeasurementTable',
  );
  /**
   * Associative array for storing property values
   * @var mixed[]
   */
  protected $container = array();

  /**
   * Constructor
   * @param mixed[] $data Associated array of property value initializing the model
   */
  public function __construct(array $data = null) {
    $this->container['event_name'] = isset($data['event_name']) ? $data['event_name'] : null;
    $this->container['event_time'] = isset($data['event_time']) ? $data['event_time'] : null;
    $this->container['event_source_url'] = isset($data['event_source_url']) ? $data['event_source_url'] : null;
    $this->container['opt_out'] = isset($data['opt_out']) ? $data['opt_out'] : null;
    $this->container['event_id'] = isset($data['event_id']) ? $data['event_id'] : null;
    $this->container['user_data'] = isset($data['user_data']) ? $data['user_data'] : null;
    $this->container['custom_data'] = isset($data['custom_data']) ? $data['custom_data'] : null;
    $this->container['data_processing_options'] = isset($data['data_processing_options']) ? $data['data_processing_options'] : null;
    $this->container['data_processing_options_country'] = isset($data['data_processing_options_country']) ? $data['data_processing_options_country'] : null;
    $this->container['data_processing_options_state'] = isset($data['data_processing_options_state']) ? $data['data_processing_options_state'] : null;
    $this->container['action_source'] = isset($data['action_source']) ? $data['action_source'] : null;
    $this->container['app_data'] = isset($data['app_data']) ? $data['app_data'] : null;
    $this->container['advanced_measurement_table'] = isset($data['advanced_measurement_table']) ? $data['advanced_measurement_table'] : null;
  }

  public static function paramTypes() {
    return self::$param_types;
  }

  public static function attributeMap() {
    return self::$attributeMap;
  }

  public static function setters() {
    return self::$setters;
  }

  public static function getters() {
    return self::$getters;
  }

  /**
   * show all the invalid properties with reasons.
   *
   * @return array invalid properties with reasons
   */
  public function listInvalidProperties() {
    $invalid_properties = array();
    if ($this->container['event_name'] === null) {
      $invalid_properties[] = "'event_name' can't be null";
    }
    if ($this->container['event_time'] === null) {
      $invalid_properties[] = "'event_time' can't be null";
    }
    if ($this->container['user_data'] === null) {
      $invalid_properties[] = "'user_data' can't be null";
    }
    return $invalid_properties;
  }

  /**
   * validate all the properties in the model
   * return true if all passed
   *
   * @return bool True if all properteis are valid
   */
  public function valid() {
    if ($this->container['event_name'] === null) {
      return false;
    }
    if ($this->container['event_time'] === null) {
      return false;
    }
    if ($this->container['user_data'] === null) {
      return false;
    }
    return true;
  }

  /**
   * Sets a Facebook pixel Standard Event or Custom Event name
   * @param string $event_name A Facebook pixel Standard Event or Custom Event name.
   * @return $this
   */
  public function setEventName($event_name) {
    $this->container['event_name'] = $event_name;

    return $this;
  }

  /**
   * Sets a Unix timestamp in seconds indicating when the actual event occurred
   * @param int $event_time A Unix timestamp in seconds indicating when the actual event occurred.
   * @return $this
   */
  public function setEventTime($event_time) {
    $this->container['event_time'] = $event_time;

    return $this;
  }

  /**
   * Sets the browser URL where the event happened
   * @param string $event_source_url The browser URL where the event happened.
   * @return $this
   */
  public function setEventSourceUrl($event_source_url) {
    $this->container['event_source_url'] = $event_source_url;

    return $this;
  }

  /**
   * Sets a flag that indicates Facebook should or should not use this event for ads delivery optimization
   * @param bool $opt_out A flag that indicates Facebook should or should not
   *      use this event for ads delivery optimization.
   *      If set to true, Facebook only use the event for attribution.
   * @return $this
   */
  public function setOptOut($opt_out) {
    $this->container['opt_out'] = $opt_out;

    return $this;
  }

  /**
   * Sets an ID used by Facebook to deduplicate the same event sent from both server and browser.
   * @param string $event_id This ID can be any unique string chosen by the advertiser.
   * event_id is used to deduplicate events sent by both Facebook Pixel and Server-Side API.
   * event_name is also used in the deduplication process.
   * For deduplication, the eventID from Facebook pixel must match the
   * event_id in the corresponding Server-Side API event.
   * @return $this
   */
  public function setEventId($event_id) {
    $this->container['event_id'] = $event_id;

    return $this;
  }

  /**
   * Sets UserData object that contains user data.
   * @param FacebookAds\Object\ServerSide\UserData $user_data
   * @return $this
   */
  public function setUserData($user_data) {
    $this->container['user_data'] = $user_data;

    return $this;
  }

  /**
   * Sets CustomData object that includes additional business data about the event.
   * @param FacebookAds\Object\ServerSide\CustomData $custom_data
   * @return $this
   */
  public function setCustomData($custom_data) {
    $this->container['custom_data'] = $custom_data;

    return $this;
  }

  /**
   * Sets the processing options you would like to enable for a specific event.
   * For more details see: https://developers.facebook.com/docs/marketing-apis/data-processing-options
   * @param string[], e.g. [] or ['LDU']
   * @return $this
   */
  public function setDataProcessingOptions($data_processing_options) {
    $this->container['data_processing_options'] = $data_processing_options;

    return $this;
  }

  /**
   * Sets a country that you want to associate to this data processing option. If you set a country, you must also set a state.
   * For more details see: https://developers.facebook.com/docs/marketing-apis/data-processing-options
   * @param int
   * @return $this
   */
  public function setDataProcessingOptionsCountry($data_processing_options_country) {
    $this->container['data_processing_options_country'] = $data_processing_options_country;

    return $this;
  }

  /**
   * Sets a state that you want to associate with this data processing option.
   * For more details see: https://developers.facebook.com/docs/marketing-apis/data-processing-options
   * @param int
   * @return $this
   *
   */
  public function setDataProcessingOptionsState($data_processing_options_state) {
    $this->container['data_processing_options_state'] = $data_processing_options_state;

    return $this;
  }

  /**
   * Gets action_source, this is where the Conversion occurred.
   * @return string
   */
  public function getActionSource() {
    return $this->container['action_source'];
  }

  /**
   * Sets action_source, this is where the Conversion occurred.
   * @return $this
   */
  public function setActionSource($action_source) {
    $this->container['action_source'] = $action_source;
    return $this;
  }

  /**
   * Set AppData which contains app data and device information for events happening from an app
   * @param AppData
   * @return $this
   */
  public function setAppData($app_data) {
    $this->container['app_data'] = $app_data;
    return $this;
  }

  /**
   * Returns true if offset exists. False otherwise.
   * @param integer $offset Offset
   * @return boolean
   */
  public function offsetExists($offset) : bool {
    return isset($this->container[$offset]);
  }

  /**
   * Gets offset.
   * @param integer $offset Offset
   * @return mixed
   */
  public function offsetGet($offset) : mixed {
    return isset($this->container[$offset]) ? $this->container[$offset] : null;
  }

  /**
   * Sets value based on offset.
   * @param integer $offset Offset
   * @param mixed $value Value to be set
   * @return void
   */
  public function offsetSet($offset, $value) : void {
    if (is_null($offset)) {
      $this->container[] = $value;
    } else {
      $this->container[$offset] = $value;
    }
  }

  /**
   * Unsets offset.
   * @param integer $offset Offset
   * @return void
   */
  public function offsetUnset($offset) : void {
    unset($this->container[$offset]);
  }

  /**
   * Normalize
   * @return array
   */
  public function normalize() {
    $normalized_payload = array();

    $normalized_payload['event_name'] = $this->getEventName();
    $normalized_payload['event_time'] = $this->getEventTime();
    $normalized_payload['event_source_url'] = $this->getEventSourceUrl();
    $normalized_payload['opt_out'] = $this->getOptOut();
    $normalized_payload['event_id'] = $this->getEventId();
    $normalized_payload['user_data'] = isset($this->container['user_data']) ? $this->getUserData()->normalize() : null;
    $normalized_payload['custom_data'] = isset($this->container['custom_data']) ? $this->getCustomData()
      ->normalize() : null;

    $normalized_payload['data_processing_options'] = $this->getDataProcessingOptions();
    $normalized_payload['data_processing_options_country'] = $this->getDataProcessingOptionsCountry();
    $normalized_payload['data_processing_options_state'] = $this->getDataProcessingOptionsState();
    $normalized_payload['action_source'] = Normalizer::normalize(
      'action_source',
      $this->container['action_source']
    );
    $normalized_payload['advanced_measurement_table'] = $this->getAdvancedMeasurementTable();
    $normalized_payload = array_filter($normalized_payload, function($val) { if(is_array($val)) { return true; } else { return strlen((string) $val); }});
    // Add the opt_out value back in if it was filtered out
    if ($this->getOptOut() === false) {
      $normalized_payload['opt_out'] = $this->getOptOut();
    }
    $normalized_payload['app_data'] = isset($this->container['app_data']) ? $this->getAppData()->normalize() : null;
    return $normalized_payload;
  }

  /**
   * Gets Facebook pixel Standard Event or Custom Event name.
   * @return string
   */
  public function getEventName() {
    return $this->container['event_name'];
  }

  /**
   * Gets Unix timestamp in seconds indicating when the actual event occurred.
   * @return int
   */
  public function getEventTime() {
    return $this->container['event_time'];
  }

  /**
   * Gets browser URL where the event happened.
   * @return string
   */
  public function getEventSourceUrl() {
    return $this->container['event_source_url'];
  }

  /**
   * Gets flag that indicates Facebook should or should not use this event for ads delivery optimization.
   * If set to true, we only use the event for attribution.
   * @return bool
   */
  public function getOptOut() {
    return $this->container['opt_out'];
  }

  /**
   * Gets Event ID can be any string chosen by the advertiser. It is used by Facebook to deduplicate
   * the same event sent from both server and browser.
   * @return string
   */
  public function getEventId() {
    return $this->container['event_id'];
  }

  /**
   * Gets UserData object that contains user data
   * @return FacebookAds\Object\ServerSide\UserData
   */
  public function getUserData() {
    return $this->container['user_data'];
  }

  /**
   * Gets customData object that includes additional business data about the event.
   * @return FacebookAds\Object\ServerSide\CustomData
   */
  public function getCustomData() {
    return $this->container['custom_data'];
  }

  /**
   * Gets DataProcessionOptions value of Processing options you would like to enable for a specific event.
   * @return string[]
   */
  public function getDataProcessingOptions() {
    return $this->container['data_processing_options'];
  }

  /**
   * Gets DataProcessionOptionsState value that represents the state that you want to associate with this data processing option.
   * @return int
   */
  public function getDataProcessingOptionsState() {
    return $this->container['data_processing_options_state'];
  }

  /**
   * Gets DataProcessionOptionsCountry value that represents the country that you want to associate to this data processing option.
   * @return int
   */
  public function getDataProcessingOptionsCountry() {
    return $this->container['data_processing_options_country'];
  }

  /**
   * Get AppData which contains app data and device information for events happening from an app
   * @return AppData
   */
  public function getAppData() {
    return $this->container['app_data'];
  }

  /**
   * Sets advanced_measurement_table, Only used for the Advanced Measurement API in the Advanced Analytics product.
   * @return $this
   */
  public function setAdvancedMeasurementTable($advanced_measurement_table) {
    $this->container['advanced_measurement_table'] = $advanced_measurement_table;
    return $this;
  }

  /**
   * Gets advanced_measurement_table, Only used for the Advanced Measurement API in the Advanced Analytics product.
   * @return string
   */
  public function getAdvancedMeasurementTable() {
    return $this->container['advanced_measurement_table'];
  }

  /**
   * Gets the string representation of the object
   * @return string
   */
  public function __toString() {
    if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
      return json_encode($this, JSON_PRETTY_PRINT);
    }

    return json_encode($this);
  }
}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use ArrayAccess;
use FacebookAds\Api;
use FacebookAds\ApiConfig;
use FacebookAds\Object\AdsPixel;

/**
 * Conversions API Event Request
 *
 * @category    Class
 */
class EventRequest implements ArrayAccess {
  /**
   * Array of property to type mappings. Used for (de)serialization
   * @var string[]
   */
  protected static $param_types = array(
    'events' => '\FacebookAds\Object\ServerSide\Event[]',
    'test_event_code' => 'string',
    'partner_agent' => 'string',
    'namespace_id' => 'string',
    'upload_id' => 'string',
    'upload_tag' => 'string',
    'upload_source' => 'string'
  );
  /**
   * Array of attributes where the key is the local name, and the value is the original name
   * @var string[]
   */
  protected static $attributeMap = array(
    'events' => 'events',
    'test_event_code' => 'test_event_code',
    'partner_agent' => 'partner_agent',
    'namespace_id' => 'namespace_id',
    'upload_id' => 'upload_id',
    'upload_tag' => 'upload_tag',
    'upload_source' => 'upload_source'
  );
  /**
   * Array of attributes to setter functions (for deserialization of responses)
   * @var string[]
   */
  protected static $setters = array(
    'events' => 'setEvents',
    'test_event_code' => 'setTestEventCode',
    'partner_agent' => 'setPartnerAgent',
    'namespace_id' => 'setNamespaceId',
    'upload_id' => 'setUploadId',
    'upload_tag' => 'setUploadTag',
    'upload_source' => 'setUploadSource'
  );
  /**
   * Array of attributes to getter functions (for serialization of requests)
   * @var string[]
   */
  protected static $getters = array(
    'events' => 'getEvents',
    'test_event_code' => 'getTestEventCode',
    'partner_agent' => 'getPartnerAgent',
    'namespace_id' => 'getNamespaceId',
    'upload_id' => 'getUploadId',
    'upload_tag' => 'getUploadTag',
    'upload_source' => 'getUploadSource'
  );
  /**
   * Associative array for storing property values
   * @var mixed[]
   */
  protected $container = array();

  protected $http_client = null;

  protected $endpoint_request  = null;

  /**
   * Constructor
   * @param string $pixel_id pixel id
   * @param mixed[] $data Associated array of property value initializing the model
   */
  public function __construct($pixel_id, array $data = null) {
    $this->container['pixel_id'] = $pixel_id;
    $this->container['events'] = isset($data['events']) ? $data['events'] : null;
    $this->container['test_event_code'] = isset($data['test_event_code']) ? $data['test_event_code'] : null;
    $this->container['partner_agent'] = isset($data['partner_agent']) ? $data['partner_agent'] : null;
    $this->container['namespace_id'] = isset($data['namespace_id']) ? $data['namespace_id'] : null;
    $this->container['upload_id'] = isset($data['upload_id']) ? $data['upload_id'] : null;
    $this->container['upload_tag'] = isset($data['upload_tag']) ? $data['upload_tag'] : null;
    $this->container['upload_source'] = isset($data['upload_source']) ? $data['upload_source'] : null;
  }

  public static function paramTypes() {
    return self::$param_types;
  }

  public static function attributeMap() {
    return self::$attributeMap;
  }

  public static function setters() {
    return self::$setters;
  }

  public static function getters() {
    return self::$getters;
  }

  /**
   * show all the invalid properties with reasons.
   *
   * @return array invalid properties with reasons
   */
  public function listInvalidProperties() {
    $invalid_properties = array();
    if ($this->container['events'] === null) {
      $invalid_properties[] = "'events' can't be null";
    }
    return $invalid_properties;
  }

  /**
   * validate all the properties in the model
   * return true if all passed
   *
   * @return bool True if all properties are valid
   */
  public function valid() {
    if ($this->container['events'] === null) {
      return false;
    }
    return true;
  }

  /**
   * Sets an array of Server Event objects
   * @param FacebookAds\Object\ServerSide\Event[] $events An array of Server Event objects
   * @return $this
   */
  public function setEvents($events) {
    $this->container['events'] = $events;
    return $this;
  }

  /**
   * Gets code used to verify that your server events are received correctly by Facebook. Use this
   * code to test your server events in the Test Events feature in Events Manager.
   * See Test Events Tool
   * (https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api#testEvents)
   * for an example.
   * @return string
   */
  public function getTestEventCode() {
    return $this->container['test_event_code'];
  }

  /**
   * Sets code used to verify that your server events are received correctly by Facebook. Use this
   * code to test your server events in the Test Events feature in Events Manager.
   * See Test Events Tool
   * (https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api#testEvents)
   * for an example.
   * @param string $test_event_code Code used to verify that your server events are received correctly by Facebook.
   * Use this code to test your server events in the Test Events feature in Events Manager. See Test Events Tool
   * (https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api#testEvents)
   * for an example.
   * @return $this
   */
  public function setTestEventCode($test_event_code) {
    $this->container['test_event_code'] = $test_event_code;
    return $this;
  }

  /**
   * Sets Partner Agent, which specifies who is sending the event.
   * @param string $partner_agent The partner agent who is sending the event
   * @return $this
   */
  public function setPartnerAgent($partner_agent) {
    $this->container['partner_agent'] = $partner_agent;

    return $this;
  }

  /**
   * Sets a custom HTTP Client object, which overrides the default HTTP service
   * used to send the event request.
   * @param HttpServiceInterface $http_client An object that implements the HttpServiceInterface
   * @return $this
   */
  public function setHttpClient($http_client) {
    $this->http_client = $http_client;
    return $this;
  }

    /**
     * Sets a custom Endpoint Request that is used to send the event request
     * in addition to CAPI Request.
     * @param CustomEndpointRequest $custom_endpoint An object that implements the CustomEndpointRequest
     * @return $this
     */
    public function setCustomEndpoint(CustomEndpointRequest $custom_endpoint) {
        $this->endpoint_request = $custom_endpoint;
        return $this;
    }

  /**
   * Execute the request
   */
  public function execute()
  {
      if ($this->endpoint_request != null && $this->endpoint_request->isSendToEndpointOnly()) {
        // do not send to CAPI Endpoint. If no exception was thrown, we can assume all events were sent successfully
        $customEndpointResponses = $this->sendEventsToCustomEndpoint();
        return new EventResponse(array(
            'data' => array('events_received' => count($this->container['events']), 'custom_endpoint_responses'=>$customEndpointResponses)
        ));

    } else if ($this->endpoint_request != null) {
        $capiResponse = $this->sendToCAPIEndpoint();
        $capiResponse->setCustomEndpointResponses(array($this->endpoint_request->getEndpoint() => $this->sendEventsToCustomEndpoint()));
        return $capiResponse;
    }
    return $this->sendToCAPIEndpoint();
  }

    /**
     * Synchronously send events to Custom Endpoint.
     *
     * @return array
     */
  private function sendEventsToCustomEndpoint(): array
  {
      $customEndpointResponse = $this->endpoint_request->sendEvent($this->container['pixel_id'], $this->container['events']);
      return array($this->endpoint_request->getEndpoint() => $customEndpointResponse);
  }

    /**
     * Synchronously send events to Facebook Conversions API.
     *
     * @return EventResponse response
     */
  private function sendToCAPIEndpoint(): EventResponse
  {
      if ($this->http_client != null) {
          $http_client = $this->http_client;
      } else {
          $http_client = HttpServiceClientConfig::getInstance()->getClient();
      }

      if ($http_client != null) {
          return $this->httpClientExecute($http_client);
      }
      return $this->defaultExecute();
  }

  private function defaultExecute() {
    $fields = array();
    $normalized_param = $this->normalize();
    $ads_pixel = new AdsPixel($this->container['pixel_id']);
    $response = $ads_pixel->createEvent(
      $fields,
      $normalized_param
    );
    return new EventResponse($response->exportAllData());
  }

  private function httpClientExecute($http_client) {
    $base_url = 'https://graph.facebook.com/v' . ApiConfig::APIVersion;
    $url = $base_url . '/' . $this->container['pixel_id'] . '/events';

    $headers = array(
      'User-Agent' => 'fbbizsdk-php-v' . ApiConfig::SDKVersion,
      'Accept-Encoding' => '*',
    );

    $curl_options = array(
      CURLOPT_CONNECTTIMEOUT => 10,
      CURLOPT_TIMEOUT => 60,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_HEADER => true,
      CURLOPT_CAINFO => Util::getCaBundlePath(),
    );

    $params = $this->normalize();
    if (HttpServiceClientConfig::getInstance()->getAccessToken() == null) {
      $params['access_token'] = Api::instance()->getSession()->getAccessToken();
    } else {
      $params['access_token'] = HttpServiceClientConfig::getInstance()->getAccessToken();
    }

    $appsecret = null;
    if (HttpServiceClientConfig::getInstance()->getAppsecret() == null) {
      $appsecret = Api::instance()->getSession()->getAppSecret();
    } else {
      $appsecret = HttpServiceClientConfig::getInstance()->getAppsecret();
    }
    if ($appsecret != null) {
      $params['appsecret_proof'] = Util::getAppsecretProof($params['access_token'], $appsecret);
    }

    return $http_client->executeRequest(
      $url,
      HttpMethod::POST,
      $curl_options,
      $headers,
      $params
    );
  }

  /**
   * Normalize
   * @return array
   */
  public function normalize() {
    $normalized_events = array();
    $events = $this->getEvents();
    if (!is_null($events)) {
      foreach ($events as $event) {
        $normalized_event = $event->normalize();
        array_push($normalized_events, $normalized_event);
      }
    }

    $normalized_payload = array(
      'data' => $normalized_events,
      'test_event_code' => $this->container['test_event_code'],
      'partner_agent' => $this->container['partner_agent'],
      'namespace_id' => $this->container['namespace_id'],
      'upload_id' => $this->container['upload_id'],
      'upload_tag' => $this->container['upload_tag'],
      'upload_source' => $this->container['upload_source'],
    );
    $normalized_payload = array_filter($normalized_payload);

    return $normalized_payload;
  }

  /**
   * Gets an array of Server Event objects
   * @return FacebookAds\Object\ServerSide\Event[]
   */
  public function getEvents() {
    return $this->container['events'];
  }

  /**
   * Gets Partner Agent, which specifies who is sending the event.
   * @return string
   */
  public function getPartnerAgent() {
    return $this->container['partner_agent'];
  }

  /**
   * Gets namespace_id, a scope used to resolve extern_id or Third-party ID.
   * Can be another data set or data partner ID.
   * @return string
   */
  public function getNamespaceId() {
    return $this->container['namespace_id'];
  }

  /**
   * Sets namespace_id, a scope used to resolve extern_id or Third-party ID.
   * Can be another data set or data partner ID.
   * @return $this
   */
  public function setNamespaceId($namespace_id) {
    $this->container['namespace_id'] = $namespace_id;
    return $this;
  }

  /**
   * Gets upload_id, a unique id used to denote the current set being uploaded.
   * @return string
   */
  public function getUploadId() {
    return $this->container['upload_id'];
  }

  /**
   * Sets upload_id, a unique id used to denote the current set being uploaded.
   * @return $this
   */
  public function setUploadId($upload_id) {
    $this->container['upload_id'] = $upload_id;
    return $this;
  }

  /**
   * Gets upload_tag, a tag string added to track your Offline event uploads.
   * @return string
   */
  public function getUploadTag() {
    return $this->container['upload_tag'];
  }

  /**
   * Sets upload_tag, a tag string added to track your Offline event uploads.
   * @return $this
   */
  public function setUploadTag($upload_tag) {
    $this->container['upload_tag'] = $upload_tag;
    return $this;
  }

  /**
   * Gets upload_source, the origin/source of data for the dataset to be uploaded.
   * @return string
   */
  public function getUploadSource() {
    return $this->container['upload_source'];
  }

  /**
   * Sets upload_source, the origin/source of data for the dataset to be uploaded.
   * @return $this
   */
  public function setUploadSource($upload_source) {
    $this->container['upload_source'] = $upload_source;
    return $this;
  }

  /**
   * Returns true if offset exists. False otherwise.
   * @param integer $offset Offset
   * @return boolean
   */
  public function offsetExists($offset) : bool {
    return isset($this->container[$offset]);
  }

  /**
   * Gets offset.
   * @param integer $offset Offset
   * @return mixed
   */
  public function offsetGet($offset) : mixed {
    return isset($this->container[$offset]) ? $this->container[$offset] : null;
  }

  /**
   * Sets value based on offset.
   * @param integer $offset Offset
   * @param mixed $value Value to be set
   * @return void
   */
  public function offsetSet($offset, $value) : void {
    if (is_null($offset)) {
      $this->container[] = $value;
    } else {
      $this->container[$offset] = $value;
    }
  }

  /**
   * Unsets offset.
   * @param integer $offset Offset
   * @return void
   */
  public function offsetUnset($offset) : void {
    unset($this->container[$offset]);
  }

  /**
   * Gets the string presentation of the object
   * @return string
   */
  public function __toString() {
    if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
      return json_encode($this, JSON_PRETTY_PRINT);
    }

    return json_encode($this);
  }
}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use FacebookAds\Api;
use FacebookAds\ApiConfig;
use FacebookAds\Http\Client;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\Utils;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\MultipartStream;

class EventRequestAsync extends EventRequest {
  /**
   * Return an asynchronous request Promise
   * @return \GuzzleHttp\Promise\PromiseInterface
   */
  public function execute() {
    $normalized_param = $this->normalize();
    $pixel_id = $this->container['pixel_id'];
    if ($this->endpoint_request != null && $this->endpoint_request->isSendToEndpointOnly()) {
        return $this->endpoint_request->sendEventAsync($pixel_id, $this->container['events'])->then(function($customEndpointResponse) {
            $response = $customEndpointResponse;
            return new EventResponse(array(
                'data' => array('events_received' => count($this->container['events']), 'custom_endpoint_responses'=>$response)
            ));
        });
    }
    $sendCAPIRequestPromise = $this->eventPromise(
          $pixel_id,
          $normalized_param
    );
    if ($this->endpoint_request != null) {
        $customEndpointRequestPromise = $this->endpoint_request->sendEventAsync($this->container['pixel_id'], $this->container['events']);
        // put both promises in an an array
        $promises = Utils::all(array($sendCAPIRequestPromise, $customEndpointRequestPromise));
        $promises->then(function($responses) {
                $CAPIResponse = $responses[0];
                $customEndpointResponse = $responses[1];
                $CAPIResponse->setCustomEndpointResponses($customEndpointResponse);
                return $CAPIResponse;
        });
        return $promises;
    }
    return $sendCAPIRequestPromise;
  }

  private function eventPromise($pixel_id, array $params = array()) {
    $access_token = Api::instance()->getSession()->getAccessToken();
    $headers = array(
      'User-Agent' => 'fbbizsdk-php-v'.ApiConfig::APIVersion,
      'Accept-Encoding' => '*',
    );

    $domain = Client::DEFAULT_LAST_LEVEL_DOMAIN . '.' . Client::DEFAULT_GRAPH_BASE_DOMAIN;
    $base_url = 'https://' . $domain . '/v' . ApiConfig::APIVersion;

    $url = $base_url.'/'.$pixel_id.'/events';

    $events_json = \GuzzleHttp\json_encode($params['data']);
    $multipart_contents = [
      [
        'name' => 'access_token',
        'contents' => $access_token,
        'headers' => array('Content-Type' => 'multipart/form-data'),
      ],
      [
        'name' => 'data',
        'contents' => $events_json,
        'headers' => array('Content-Type' => 'multipart/form-data'),
      ]
    ];

    foreach ($params as $key => $value) {
      if ($key !== 'data') {
        $multipart_contents[] = [
          'name' => $key,
          'contents' => $value,
          'headers' => array('Content-Type' => 'multipart/form-data'),
        ];
      }
    }

    $body = new MultipartStream($multipart_contents);
    $request = new Request('POST', $url, $headers, $body);

    $client = AsyncClient::getInstance()->getClient();
    return $client->sendAsync($request);
  }
}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use ArrayAccess;

/**
 * Conversions API event response.
 *
 * @category    Class
 */
class EventResponse implements ArrayAccess {

  /**
   * Array of property to type mappings. Used for (de)serialization
   * @var string[]
   */
  protected static $param_types = array(
    'events_received' => 'int',
    'messages' => 'string[]',
    'fbtrace_id' => 'string',
    'custom_endpoint_responses' => 'array'
  );
  /**
   * Array of attributes where the key is the local name, and the value is the original name
   * @var string[]
   */
  protected static $attributeMap = array(
    'events_received' => 'events_received',
    'messages' => 'messages',
    'fbtrace_id' => 'fbtrace_id',
    'custom_endpoint_responses' => 'custom_endpoint_responses',
  );
  /**
   * Array of attributes to setter functions (for deserialization of responses)
   * @var string[]
   */
  protected static $setters = array(
    'events_received' => 'setEventsReceived',
    'messages' => 'setMessages',
    'fbtrace_id' => 'setFbTraceId',
    'custom_endpoint_responses' => 'custom_endpoint_responses'
  );
  /**
   * Array of attributes to getter functions (for serialization of requests)
   * @var string[]
   */
  protected static $getters = array(
    'events_received' => 'getEventsReceived',
    'messages' => 'getMessages',
    'fbtrace_id' => 'getFbTraceId',
    'custom_endpoint_responses' => 'custom_endpoint_responses'
  );
  /**
   * Associative array for storing property values
   * @var mixed[]
   */
  protected $container = array();

  /**
   * Constructor
   * @param mixed[] $data Associated array of property value initalizing the model
   */
  public function __construct(array $data = null) {
    $this->container['events_received'] = isset($data['events_received']) ? $data['events_received'] : null;
    $this->container['messages'] = isset($data['messages']) ? $data['messages'] : null;
    $this->container['fbtrace_id'] = isset($data['fbtrace_id']) ? $data['fbtrace_id'] : null;
    $this->container['custom_endpoint_responses'] = isset($data['custom_endpoint_responses']) ? $data['custom_endpoint_responses'] : null;
  }

  public static function paramTypes() {
    return self::$param_types;
  }

  public static function attributeMap() {
    return self::$attributeMap;
  }

  public static function setters() {
    return self::$setters;
  }

  public static function getters() {
    return self::$getters;
  }

  /**
   * show all the invalid properties with reasons.
   *
   * @return array invalid properties with reasons
   */
  public function listInvalidProperties() {
    $invalid_properties = array();
    return $invalid_properties;
  }

  /**
   * validate all the properties in the model
   * return true if all passed
   *
   * @return bool True if all properteis are valid
   */
  public function valid() {
    return true;
  }

  /**
   * Gets number of events received.
   * @return int
   */
  public function getEventsReceived() {
    return $this->container['events_received'];
  }

  /**
   * Sets number of events received.
   * @param int $events_received number of events received.
   * @return $this
   */
  public function setEventsReceived($events_received) {
    $this->container['events_received'] = $events_received;

    return $this;
  }

    /**
     * Sets custom endpoint response results.
     * @param array $custom_endpoint_responses Custom Endpoint Response that maps to the Custom Endpoint Requests sent.
     * @return $this
     */
    public function setCustomEndpointResponses(array $custom_endpoint_responses) {
        $this->container['custom_endpoint_responses'] = $custom_endpoint_responses;

        return $this;
    }

    /**
     * Gets custom endpoint response results.
     * @return mixed $array
     */
    public function getCustomEndpointResponses() {
        return $this->container['custom_endpoint_responses'];
    }

  /**
   * Gets response messages.
   * @return string[]
   */
  public function getMessages() {
    return $this->container['messages'];
  }

  /**
   * Sets response messages.
   * @param string[] $messages response messages.
   * @return $this
   */
  public function setMessages($messages) {
    $this->container['messages'] = $messages;

    return $this;
  }

  /**
   * Gets Facebook trace id
   * @return string
   */
  public function getFbTraceId() {
    return $this->container['fbtrace_id'];
  }

  /**
   * Sets Facebook trace id
   * @param $fbtrace_id Facebook trace id
   * @return $this
   */
  public function setFbTraceId($fbtrace_id) {
    $this->container['fbtrace_id'] = $fbtrace_id;
    return $this;
  }

  /**
   * Returns true if offset exists. False otherwise.
   * @param integer $offset Offset
   * @return boolean
   */
  public function offsetExists($offset) : bool {
    return isset($this->container[$offset]);
  }

  /**
   * Gets offset.
   * @param integer $offset Offset
   * @return mixed
   */
  public function offsetGet($offset) : mixed {
    return isset($this->container[$offset]) ? $this->container[$offset] : null;
  }

  /**
   * Sets value based on offset.
   * @param integer $offset Offset
   * @param mixed $value Value to be set
   * @return void
   */
  public function offsetSet($offset, $value) : void {
    if (is_null($offset)) {
      $this->container[] = $value;
    } else {
      $this->container[$offset] = $value;
    }
  }

  /**
   * Unsets offset.
   * @param integer $offset Offset
   * @return void
   */
  public function offsetUnset($offset) : void {
    unset($this->container[$offset]);
  }

  /**
   * Gets the string presentation of the object
   * @return string
   */
  public function __toString() {
    if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
      return json_encode($this, JSON_PRETTY_PRINT);
    }
    return json_encode($this);
  }
}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use ArrayAccess;

class ExtendedDeviceInfo implements ArrayAccess {

  const EXT_INFO_VERSION        = 0;
  const APP_PACKAGE_NAME        = 1;
  const SHORT_VERSION           = 2;
  const LONG_VERSION            = 3;
  const OS_VERSION              = 4;
  const DEVICE_MODEL_NAME       = 5;
  const LOCALE                  = 6;
  const TIMEZONE_ABBREVIATION   = 7;
  const CARRIER                 = 8;
  const SCREEN_WIDTH            = 9;
  const SCREEN_HEIGHT           = 10;
  const SCREEN_DENSITY          = 11;
  const CPU_CORE_COUNT          = 12;
  const TOTAL_DISK_SPACE_GB     = 13;
  const FREE_DISK_SPACE_GB      = 14;
  const DEVICE_TIME_ZONE        = 15;

  protected static $param_types = array(
    'ext_info_version' => 'string',
    'app_package_name' => 'string',
    'short_version' => 'string',
    'long_version' => 'string',
    'os_version' => 'string',
    'device_model_name' => 'string',
    'locale' => 'string',
    'timezone_abbreviation' => 'string',
    'carrier' => 'string',
    'screen_width' => 'int',
    'screen_height' => 'int',
    'screen_density' => 'string',
    'cpu_core_count' => 'int',
    'total_disk_space_gb' => 'int',
    'free_disk_space_gb' => 'int',
    'device_time_zone' => 'string',
  );

  protected static $attributeMap = array(
    'ext_info_version' => 'ext_info_version',
    'app_package_name' => 'app_package_name',
    'short_version' => 'short_version',
    'long_version' => 'long_version',
    'os_version' => 'os_version',
    'device_model_name' => 'device_model_name',
    'locale' => 'locale',
    'timezone_abbreviation' => 'timezone_abbreviation',
    'carrier' => 'carrier',
    'screen_width' => 'screen_width',
    'screen_height' => 'screen_height',
    'screen_density' => 'screen_density',
    'cpu_core_count' => 'cpu_core_count',
    'total_disk_space_gb' => 'total_disk_space_gb',
    'free_disk_space_gb' => 'free_disk_space_gb',
    'device_time_zone' => 'device_time_zone',
  );

  protected static $setters = array(
    'ext_info_version' => 'setExtInfoVersion',
    'app_package_name' => 'setAppPackageName',
    'short_version' => 'setShortVersion',
    'long_version' => 'setLongVersion',
    'os_version' => 'setOsVersion',
    'device_model_name' => 'setDeviceModelName',
    'locale' => 'setLocale',
    'timezone_abbreviation' => 'setTimezoneAbbreviation',
    'carrier' => 'setCarrier',
    'screen_width' => 'setScreenWidth',
    'screen_height' => 'setScreenHeight',
    'screen_density' => 'setScreenDensity',
    'cpu_core_count' => 'setCpuCoreCount',
    'total_disk_space_gb' => 'setTotalDiskSpaceGb',
    'free_disk_space_gb' => 'setFreeDiskSpaceGb',
    'device_time_zone' => 'setDeviceTimeZone',
  );

  protected static $getters = array(
    'ext_info_version' => 'getExtInfoVersion',
    'app_package_name' => 'getAppPackageName',
    'short_version' => 'getShortVersion',
    'long_version' => 'getLongVersion',
    'os_version' => 'getOsVersion',
    'device_model_name' => 'getDeviceModelName',
    'locale' => 'getLocale',
    'timezone_abbreviation' => 'getTimezoneAbbreviation',
    'carrier' => 'getCarrier',
    'screen_width' => 'getScreenWidth',
    'screen_height' => 'getScreenHeight',
    'screen_density' => 'getScreenDensity',
    'cpu_core_count' => 'getCpuCoreCount',
    'total_disk_space_gb' => 'getTotalDiskSpaceGb',
    'free_disk_space_gb' => 'getFreeDiskSpaceGb',
    'device_time_zone' => 'getDeviceTimeZone',
  );

  protected $container = array();

  public function __construct(array $data = null) {
    $this->container['ext_info_version'] = isset($data['ext_info_version']) ? $data['ext_info_version'] : null;
    $this->container['app_package_name'] = isset($data['app_package_name']) ? $data['app_package_name'] : null;
    $this->container['short_version'] = isset($data['short_version']) ? $data['short_version'] : null;
    $this->container['long_version'] = isset($data['long_version']) ? $data['long_version'] : null;
    $this->container['os_version'] = isset($data['os_version']) ? $data['os_version'] : null;
    $this->container['device_model_name'] = isset($data['device_model_name']) ? $data['device_model_name'] : null;
    $this->container['locale'] = isset($data['locale']) ? $data['locale'] : null;
    $this->container['timezone_abbreviation'] = isset($data['timezone_abbreviation']) ? $data['timezone_abbreviation'] : null;
    $this->container['carrier'] = isset($data['carrier']) ? $data['carrier'] : null;
    $this->container['screen_width'] = isset($data['screen_width']) ? $data['screen_width'] : null;
    $this->container['screen_height'] = isset($data['screen_height']) ? $data['screen_height'] : null;
    $this->container['screen_density'] = isset($data['screen_density']) ? $data['screen_density'] : null;
    $this->container['cpu_core_count'] = isset($data['cpu_core_count']) ? $data['cpu_core_count'] : null;
    $this->container['total_disk_space_gb'] = isset($data['total_disk_space_gb']) ? $data['total_disk_space_gb'] : null;
    $this->container['free_disk_space_gb'] = isset($data['free_disk_space_gb']) ? $data['free_disk_space_gb'] : null;
    $this->container['device_time_zone'] = isset($data['device_time_zone']) ? $data['device_time_zone'] : null;
  }

  public static function paramTypes() {
    return $self::param_types;
  }

  public static function attributeMap() {
    return self::$attributeMap;
  }

  public static function setters() {
    return self::$setters;
  }

  public static function getters() {
    return self::$getters;
  }

  /**
   * show all the invalid properties with reasons.
   *
   * @return array invalid properties with reasons
   */
  public function listInvalidProperties() {
    $invalid_properties = array();
    return $invalid_properties;
  }

  /**
   * validate all the properties in the model
   * return true if all passed
   *
   * @return bool True if all properties are valid
   */
  public function valid() {
    return true;
  }

  public function setExtInfoVersion($ext_info_version) {
    $this->container['ext_info_version'] = $ext_info_version;

    return $this;
  }

  public function setAppPackageName($app_package_name) {
    $this->container['app_package_name'] = $app_package_name;

    return $this;
  }

  public function setShortVersion($short_version) {
    $this->container['short_version'] = $short_version;

    return $this;
  }

  public function setLongVersion($long_version) {
    $this->container['long_version'] = $long_version;

    return $this;
  }

  public function setOsVersion($os_version) {
    $this->container['os_version'] = $os_version;

    return $this;
  }

  public function setDeviceModelName($device_model_name) {
    $this->container['device_model_name'] = $device_model_name;

    return $this;
  }

  public function setLocale($locale) {
    $this->container['locale'] = $locale;

    return $this;
  }

  public function setTimezoneAbbreviation($timezone_abbreviation) {
    $this->container['timezone_abbreviation'] = $timezone_abbreviation;

    return $this;
  }

  public function setCarrier($carrier) {
    $this->container['carrier'] = $carrier;

    return $this;
  }

  public function setScreenWidth($screen_width) {
    $this->container['screen_width'] = $screen_width;

    return $this;
  }

  public function setScreenHeight($screen_height) {
    $this->container['screen_height'] = $screen_height;

    return $this;
  }

  public function setScreenDensity($screen_density) {
    $this->container['screen_density'] = $screen_density;

    return $this;
  }

  public function setCpuCoreCount($cpu_core_count) {
    $this->container['cpu_core_count'] = $cpu_core_count;

    return $this;
  }

  public function setTotalDiskSpaceGb($total_disk_space_gb) {
    $this->container['total_disk_space_gb'] = $total_disk_space_gb;

    return $this;
  }

  public function setFreeDiskSpaceGb($free_disk_space_gb) {
    $this->container['free_disk_space_gb'] = $free_disk_space_gb;

    return $this;
  }

  public function setDeviceTimeZone($device_time_zone) {
    $this->container['device_time_zone'] = $device_time_zone;

    return $this;
  }

  /**
   * Returns true if offset exists. False otherwise.
   * @param integer $offset Offset
   * @return boolean
   */
  public function offsetExists($offset) : bool {
    return isset($this->container[$offset]);
  }

  /**
   * Gets offset.
   * @param integer $offset Offset
   * @return mixed
   */
  public function offsetGet($offset) : mixed {
    return isset($this->container[$offset]) ? $this->container[$offset] : null;
  }

  /**
   * Sets value based on offset.
   * @param integer $offset Offset
   * @param mixed $value Value to be set
   * @return void
   */
  public function offsetSet($offset, $value) : void {
    if (is_null($offset)) {
      $this->container[] = $value;
    } else {
      $this->container[$offset] = $value;
    }
  }

  /**
   * Unsets offset.
   * @param integer $offset Offset
   * @return void
   */
  public function offsetUnset($offset) : void {
    unset($this->container[$offset]);
  }

  public function normalize() {
    $extended_device_info_array = array();
    $extended_device_info_array[self::EXT_INFO_VERSION] = $this->getExtInfoVersion();
    $extended_device_info_array[self::APP_PACKAGE_NAME] = $this->getAppPackageName();
    $extended_device_info_array[self::SHORT_VERSION] = $this->getShortVersion();
    $extended_device_info_array[self::LONG_VERSION] = $this->getLongVersion();
    $extended_device_info_array[self::OS_VERSION] = $this->getOsVersion();
    $extended_device_info_array[self::DEVICE_MODEL_NAME] = $this->getDeviceModelName();
    $extended_device_info_array[self::LOCALE] = $this->getLocale();
    $extended_device_info_array[self::TIMEZONE_ABBREVIATION] = $this->getTimezoneAbbreviation();
    $extended_device_info_array[self::CARRIER] = $this->getCarrier();
    $extended_device_info_array[self::SCREEN_WIDTH] = $this->getScreenWidth();
    $extended_device_info_array[self::SCREEN_HEIGHT] = $this->getScreenHeight();
    $extended_device_info_array[self::SCREEN_DENSITY] = $this->getScreenDensity();
    $extended_device_info_array[self::CPU_CORE_COUNT] = $this->getCpuCoreCount();
    $extended_device_info_array[self::TOTAL_DISK_SPACE_GB] = $this->getTotalDiskSpaceGb();
    $extended_device_info_array[self::FREE_DISK_SPACE_GB] = $this->getFreeDiskSpaceGb();
    $extended_device_info_array[self::DEVICE_TIME_ZONE] = $this->getDeviceTimeZone();

    return $extended_device_info_array;
  }

  public function getExtInfoVersion() {
    return $this->container['ext_info_version'];
  }

  public function getAppPackageName() {
    return $this->container['app_package_name'];
  }

  public function getShortVersion() {
    return $this->container['short_version'];
  }

  public function getLongVersion() {
    return $this->container['long_version'];
  }

  public function getOsVersion() {
    return $this->container['os_version'];
  }

  public function getDeviceModelName() {
    return $this->container['device_model_name'];
  }

  public function getLocale() {
    return $this->container['locale'];
  }

  public function getTimezoneAbbreviation() {
    return $this->container['timezone_abbreviation'];
  }

  public function getCarrier() {
    return $this->container['carrier'];
  }

  public function getScreenWidth() {
    return $this->container['screen_width'];
  }

  public function getScreenHeight() {
    return $this->container['screen_height'];
  }

  public function getScreenDensity() {
    return $this->container['screen_density'];
  }

  public function getCpuCoreCount() {
    return $this->container['cpu_core_count'];
  }

  public function getTotalDiskSpaceGb() {
    return $this->container['total_disk_space_gb'];
  }

  public function getFreeDiskSpaceGb() {
    return $this->container['free_disk_space_gb'];
  }

  public function getDeviceTimeZone() {
    return $this->container['device_time_zone'];
  }

  /**
   * Gets the string presentation of the object
   * @return string
   */
  public function __toString() {
    if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
      return json_encode($this, JSON_PRETTY_PRINT);
    }

    return json_encode($this);
  }

}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

interface Filter
{
    /**
     * Returns a boolean on whether the event should be filtered
     * @param Event $event
     * @return bool
     */
    public function shouldSendEvent(Event $event): bool;
}


<?php
/**
 * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use FacebookAds\Enum\AbstractEnum;

/**
 * Class Gender
 * @package FacebookAds\Object\ServerSide
 */
class Gender extends AbstractEnum {

  const MALE = 'm';
  const FEMALE = 'f';

  public function getFieldTypes() {
    return array(
      'm' => 'string',
      'f' => 'string',
    );
  }
}


<?php
/**
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

use FacebookAds\Enum\AbstractEnum;

final class HttpMethod extends AbstractEnum {
  const POST = 'POST';
  const PUT = 'PUT';
  const GET = 'GET';
  const DELETE = 'DELETE';
}


<?php
/**
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

class HttpServiceClientConfig extends Singleton {
  protected $client = null;
  protected $access_token = null;
  protected $appsecret = null;

  public function __construct() {}

  public function getClient() {
    return $this->client;
  }

  public function getAccessToken() {
    return $this->access_token;
  }

  public function getAppsecret() {
    return $this->appsecret;
  }

  public function setClient($client) {
    $this->client = $client;
  }

  public function setAccessToken($access_token) {
    $this->access_token = $access_token;
  }

  public function setAppsecret($appsecret) {
    $this->appsecret = $appsecret;
  }
}


<?php
/**
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

namespace FacebookAds\Object\ServerSide;

interface HttpServiceInterface {
  /**
   * @param string $url The graph API endpoint that will be requested
   * @param FacebookAds\Object\ServerSide\HttpMethod $method The HTTP request method
   * @param array $curl_options Contains curl options
   * @param array $headers Contains HTTP request headers including User-Agent and Accept-Encoding
   * @param array $params Contains request parameters including access_token, data, test_event_code, etc.
   * @return FacebookAds\Object\ServerSide\EventResponse
   */
  public function executeRequest($url, $method, array $curl_options, array $headers, array $params);
}