| 1 |
<?php |
| 2 |
declare(strict_types=1); |
| 3 |
|
| 4 |
namespace Imagify\Dependencies\WPMedia\Mixpanel; |
| 5 |
|
| 6 |
use Imagify_WPMedia_ConsumerStrategies_AbstractConsumer as WPMedia_ConsumerStrategies_AbstractConsumer; |
| 7 |
|
| 8 |
/** |
| 9 |
* Consumes messages and sends them to a host/endpoint using WordPress's HTTP API |
| 10 |
*/ |
| 11 |
class WPConsumer extends WPMedia_ConsumerStrategies_AbstractConsumer { |
| 12 |
|
| 13 |
/** |
| 14 |
* The host to connect to (e.g. api.mixpanel.com) |
| 15 |
* |
| 16 |
* @var string |
| 17 |
*/ |
| 18 |
protected $host; |
| 19 |
|
| 20 |
/** |
| 21 |
* The host-relative endpoint to write to (e.g. /engage) |
| 22 |
* |
| 23 |
* @var string |
| 24 |
*/ |
| 25 |
protected $endpoint; |
| 26 |
|
| 27 |
/** |
| 28 |
* The maximum number of seconds to allow the call to execute. Default is 30 seconds. |
| 29 |
* |
| 30 |
* @var int |
| 31 |
*/ |
| 32 |
protected $timeout; |
| 33 |
|
| 34 |
/** |
| 35 |
* The protocol to use for the cURL connection |
| 36 |
* |
| 37 |
* @var string |
| 38 |
*/ |
| 39 |
protected $protocol; |
| 40 |
|
| 41 |
/** |
| 42 |
* Creates a new WPConsumer and assigns properties from the $options array |
| 43 |
* |
| 44 |
* @param array{host:string, endpoint:string, timeout?: int, use_ssl?: bool} $options Options for the consumer. |
| 45 |
*/ |
| 46 |
public function __construct( $options ) { |
| 47 |
parent::__construct( $options ); |
| 48 |
|
| 49 |
$this->host = $options['host']; |
| 50 |
$this->endpoint = $options['endpoint']; |
| 51 |
$this->timeout = isset( $options['timeout'] ) ? $options['timeout'] : 30; |
| 52 |
$this->protocol = isset( $options['use_ssl'] ) && ( true === $options['use_ssl'] ) ? 'https' : 'http'; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Send post request to the given host/endpoint using WordPress's HTTP API |
| 57 |
* |
| 58 |
* @param mixed[] $batch Batch of data to send to mixpanel. |
| 59 |
* |
| 60 |
* @return bool |
| 61 |
*/ |
| 62 |
public function persist( $batch ) { |
| 63 |
if ( count( $batch ) <= 0 ) { |
| 64 |
return true; |
| 65 |
} |
| 66 |
|
| 67 |
$url = $this->protocol . '://' . $this->host . $this->endpoint; |
| 68 |
$data = 'data=' . $this->_encode( $batch ); |
| 69 |
|
| 70 |
$response = wp_remote_post( |
| 71 |
$url, |
| 72 |
[ |
| 73 |
'timeout' => $this->timeout, |
| 74 |
'body' => $data, |
| 75 |
] |
| 76 |
); |
| 77 |
|
| 78 |
if ( is_wp_error( $response ) ) { |
| 79 |
$this->_handleError( $response->get_error_code(), $response->get_error_message() ); |
| 80 |
return false; |
| 81 |
} |
| 82 |
|
| 83 |
return true; |
| 84 |
} |
| 85 |
} |
| 86 |
|