-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatafeedr.php
1661 lines (1427 loc) · 39.2 KB
/
datafeedr.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Datafeedr API PHP Library
*
* @version 3.0.0
*
* Copyright (c) 2007 ~ 2017, Datafeedr - All Rights Reserved
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* Class DatafeedrApi
*
* This is the core Datafeedr API class.
*/
class DatafeedrApi {
protected $_accessId;
protected $_secretKey;
protected $_hasZlib;
protected $_host;
protected $_retry;
protected $_retryTimeout;
protected $_returnObjects;
protected $_timeout;
protected $_transport;
protected $_https;
protected $_url;
protected $_userAgent;
protected $_status;
protected $_errors;
const SORT_DESCENDING = - 1;
const SORT_ASCENDING = + 1;
const DEFAULT_HOST = 'api.datafeedr.com';
const REQUEST_COMPRESSION_THRESHOLD = 1024;
const VERSION = '3.0.0';
/**
* DatafeedrApi constructor.
*
* @since 1.0.0
*
* @param string $accessId Datafeedr API Access ID.
* @param string $secretKey Datafeedr API Secret Key.
* @param array $options Options.
*
* Possble options:
*
* - host: API host name. Default: 'api.datafeedr.com'
* - https: TRUE if using https. Default: FALSE.
* - transport: HTTP transport name or function. Default: 'wordpress'
* - timeout: HTTP connection timeout, in seconds. Default: 0
* - returnObjects: True to return Objects. False to return associative arrays Default: false
* - retry: How many times to repeat a request on a temporary failure. Default: 0 (do not repeat)
* - retryTimeout: Timeout between retry requests, in seconds. Default: 5
*
* The `transport` option tells how HTTP requests should be made.
* It can be either a string that describes one of built-in transports ("curl", "file" or "wordpress"),
* or a callable object that should accept a URL, an array of headers and a string of post data and
* should return an array [int http response status, string response body].
*
*
* @throws DatafeedrError Throws error if any option is invalid.
*/
public function __construct( $accessId, $secretKey, $options = null ) {
$this->_accessId = $accessId;
$this->_secretKey = $secretKey;
$this->_errors = array(
1 => 'DatafeedrBadRequestError',
2 => 'DatafeedrAuthenticationError',
3 => 'DatafeedrLimitExceededError',
4 => 'DatafeedrQueryError',
7 => 'DatafeedrExternalError',
9 => 'DatafeedrServerError',
);
$this->_parseOptions( $options );
}
/**
* Returns API status information.
*
* @since 1.0.0
*
* @return array An array of API Status information.
*/
public function getStatus() {
$this->apiCall( 'status' );
return $this->_status;
}
/**
* Return status information from the last request.
*
* If no API request has been made, return NULL
*
* @since 1.0.0
*
* @return array|null Status information or NULL.
*/
public function lastStatus() {
return $this->_status;
}
/**
* Return the list of networks.
*
* @since 1.0.0
*
* @param integer|array $networkId Optional. Network ID or an array of network IDs.
* @param boolean $includeEmpty Optional. If FALSE, omit networks with 0 products.
* @param array $fields Optional. An array of fields to retrieve.
*
* @return array An array of Networks.
*/
public function getNetworks( $networkId = null, $includeEmpty = false, $fields = null ) {
$request = array();
if ( $networkId ) {
$request['_ids'] = $this->_intarray( $networkId );
}
$request['skip_empty'] = intval( ! $includeEmpty );
if ( $fields ) {
$request['fields'] = $fields;
}
$response = $this->apiCall( 'networks', $request );
return $this->_get( $response, 'networks' );
}
/**
* Return the list of merchants.
*
* @since 1.0.0
*
* @param integer|array $networkId Optional. Network ID or array of Network IDs.
* @param bool $includeEmpty Optional. If FALSE, omit merchants with 0 products.
* @param array $fields Optional. An array of fields to retrieve.
*
* @return array An array of merchants.
*/
public function getMerchants( $networkId = null, $includeEmpty = false, $fields = null ) {
$request = array();
if ( $networkId ) {
$request['source_ids'] = $this->_intarray( $networkId );
}
$request['skip_empty'] = intval( ! $includeEmpty );
if ( $fields ) {
$request['fields'] = $fields;
}
$response = $this->apiCall( 'merchants', $request );
return $this->_get( $response, 'merchants' );
}
/**
* Return a list of merchants by their IDs.
*
* @since 1.0.0
*
* @param integer|array $merchantId Merchant ID or array of Merchant IDs.
* @param boolean $includeEmpty Optional. If FALSE, omit merchants with 0 products.
* @param array $fields Optional. An array of fields to retrieve.
*
* @return array An array of merchants.
*/
public function getMerchantsById( $merchantId, $includeEmpty = false, $fields = null ) {
$request = array();
$request['_ids'] = $this->_intarray( $merchantId );
$request['skip_empty'] = intval( ! $includeEmpty );
if ( $fields ) {
$request['fields'] = $fields;
}
$response = $this->apiCall( 'merchants', $request );
return $this->_get( $response, 'merchants' );
}
/**
* Return a list of searchable fields.
*
* @todo - Does this return a list of all fields for a specific network or only indexed/searchable fields? Update docs accordingly.
*
* @since 1.0.0
*
* @param integer|array $networkId Optional. Network ID or array of network IDs.
*
* @return array An array of searchable fields.
*/
public function getFields( $networkId = null ) {
$request = array();
if ( $networkId ) {
$request['source_ids'] = $this->_intarray( $networkId );
}
$response = $this->apiCall( 'fields', $request );
return $this->_get( $response, 'fields' );
}
/**
* Return a list of products by their IDs.
*
* @since 1.0.0
*
* @param integer|array $productId Product ID or an array of products IDs.
* @param array $fields Optional. An array of fields to retrieve.
*
* @return array An array of Products.
*/
public function getProducts( $productId, $fields = null ) {
$request = array();
$request['_ids'] = $this->_intarray( $productId );
$request['string_ids'] = 1;
if ( $fields ) {
$request['fields'] = $fields;
}
$response = $this->apiCall( 'get', $request );
return $this->_get( $response, 'products' );
}
/**
* Return a list of Zanox merchant IDs ("zmids").
*
* @since 1.0.0
*
* @param integer|array $merchantId Merchant ID or an array of merchant IDs.
* @param integer $adspaceId Zanox Adspace ID.
* @param string $connectId Zanox Connection ID.
*
* @return array An array of arrays (adspace_id, merchant_id, program_id, zmid).
*/
public function getZanoxMerchantIds( $merchantId, $adspaceId, $connectId ) {
$request = array();
$request['merchant_ids'] = $this->_intarray( $merchantId );
$request['adspace_id'] = $adspaceId;
$request['connect_id'] = $connectId;
$response = $this->apiCall( 'zanox_merchant_ids', $request );
return $this->_get( $response, 'zanox_merchant_ids' );
}
/**
* Return a list of PerformanceHorizon campaign references ("camrefs").
*
* @since 2.0.0
*
* @param integer|array $merchantId Merchant ID or an array of merchant IDs.
* @param string $applicationKey PerformanceHorizon application_key.
* @param string $userApiKey PerformanceHorizon user_api_key.
* @param string $publisherId PerformanceHorizon publisher_id.
*
* @return array An array of arrays (campaign_id, camref, merchant_id).
*/
public function getPerformanceHorizonCamrefs( $merchantId, $applicationKey, $userApiKey, $publisherId ) {
$request = array();
$request['merchant_ids'] = $this->_intarray( $merchantId );
$request['application_key'] = $applicationKey;
$request['user_api_key'] = $userApiKey;
$request['publisher_id'] = $publisherId;
$response = $this->apiCall( 'performancehorizon_camrefs', $request );
return $this->_get( $response, 'performancehorizon_camrefs' );
}
/**
* Return a list of Effiliation affiliate ids.
*
* @since 2.0.2
*
* @param integer|array $merchantId Merchant ID or an array of merchant IDs.
* @param string $apiKey Effiliation api_key.
*
* @return array An array of arrays (affiliate_id, merchant_id).
*/
public function getEffiliationAffiliateIds( $merchantId, $apiKey ) {
$request = array();
$request['merchant_ids'] = $this->_intarray( $merchantId );
$request['api_key'] = $apiKey;
$response = $this->apiCall( 'effiliation_affiliate_ids', $request );
return $this->_get( $response, 'effiliation_affiliate_ids' );
}
/**
* Create a new DatafeedrSearchRequest object.
*
* @since 1.0.0
*
* @return DatafeedrSearchRequest
*/
public function searchRequest() {
return new DatafeedrSearchRequest( $this );
}
/**
* Create a new DatafeedrMerchantSearchRequest object.
*
* @since 1.0.0
*
* @return DatafeedrMerchantSearchRequest
*/
public function merchantSearchRequest() {
return new DatafeedrMerchantSearchRequest( $this );
}
/**
* Create a new DatafeedrAmazonSearchRequest object.
*
* @since 1.0.0
*
* @param string $awsAccessKeyId Amazon Access Key.
* @param string $awsSecretKey Amazon Secret Key.
* @param string $awsAssociateTag Amazon Associates tag.
* @param string $locale The country locale code.
*
* @return DatafeedrAmazonSearchRequest
*/
public function amazonSearchRequest( $awsAccessKeyId, $awsSecretKey, $awsAssociateTag, $locale = 'US' ) {
return new DatafeedrAmazonSearchRequest( $this, $awsAccessKeyId, $awsSecretKey, $awsAssociateTag, $locale );
}
/**
* Create a new DatafeedrAmazonLookupRequest object.
*
* @since 1.0.0
*
* @param string $awsAccessKeyId Amazon Access Key.
* @param string $awsSecretKey Amazon Secret Key.
* @param string $awsAssociateTag Amazon Associates tag.
* @param string $locale The country locale code.
*
* @return DatafeedrAmazonLookupRequest
*/
public function amazonLookupRequest( $awsAccessKeyId, $awsSecretKey, $awsAssociateTag, $locale = 'US' ) {
return new DatafeedrAmazonLookupRequest( $this, $awsAccessKeyId, $awsSecretKey, $awsAssociateTag, $locale );
}
/**
* Perform the raw API call.
*
* @since 1.0.0
*
* @param string $action API Action. (Examples: status, merchants, networks, search, etc...)
* @param array $request Optional. Request data.
*
* @throws DatafeedrHTTPError Throws error if request status is not 200.
*
* @return array Returns $response array.
*/
public function apiCall( $action, $request = null ) {
if ( ! $request ) {
$request = array();
}
$request['aid'] = $this->_accessId;
$request['timestamp'] = gmdate( 'Y-m-d H:i:s' );
if ( $this->_https ) {
$request['akey'] = $this->_secretKey;
} else {
$message = $request['aid'] . $action . $request['timestamp'];
$request['signature'] = hash_hmac( 'sha256', $message, $this->_secretKey, false );
}
$postdata = json_encode( $request );
$url = $this->_url . '/' . $action;
$headers = array(
'Host: ' . $this->_host,
'Content-Type: application/json',
'Accept: application/json',
'Connection: close',
'User-Agent: ' . $this->_userAgent
);
if ( $this->_hasZlib && strlen( $postdata ) >= self::REQUEST_COMPRESSION_THRESHOLD ) {
$postdata = gzcompress( $postdata );
$headers [] = 'Content-Encoding: deflate';
}
$headers [] = 'Content-Length: ' . strlen( $postdata );
list( $status, $response ) = $this->_performRequest( $url, $headers, $postdata );
if ( strlen( $response ) ) {
$response = json_decode( $response, ! $this->_returnObjects );
}
$error = $this->_get( $response, 'error' );
if ( $error ) {
$type = $this->_get( $response, 'type' );
$cls = isset( $this->_errors[ $type ] ) ? $this->_errors[ $type ] : 'DatafeedrError';
throw new $cls( $this->_get( $response, 'message' ), $error );
}
if ( 200 != $status ) {
throw new DatafeedrHTTPError( "Status $status" );
}
$this->_status = $this->_get( $response, 'status' );
return $response;
}
/**
* Returns the default set of options.
*
* @since 2.0.0
*
* @returns array $options.
*
*/
protected function _defaultOptions() {
return array(
'host' => self::DEFAULT_HOST,
'https' => false,
'transport' => 'wordpress_or_curl',
'timeout' => 30,
'returnObjects' => false,
'retry' => 0,
'retryTimeout' => 5
);
}
/**
* Parse constructor options.
*
* @since 2.0.0
*
* @param array $options .
*
* @throws DatafeedrError Throws error if any option is invalid.
*/
protected function _parseOptions( $options ) {
$opts = $this->_defaultOptions();
if ( ! is_null( $options ) ) {
if ( ! is_array( $options ) ) {
throw new DatafeedrError( "Options must be an array" );
}
foreach ( $options as $key => $value ) {
if ( isset( $opts[ $key ] ) ) {
$opts[ $key ] = $value;
}
}
}
$pt = $opts['https'] ? 'https' : 'http';
$tr = $opts['transport'];
$this->_url = $pt . '://' . $opts['host'];
$this->_https = $opts['https'];
$this->_host = $opts['host'];
$this->_timeout = intval( $opts['timeout'] );
$this->_returnObjects = intval( $opts['returnObjects'] );
$this->_retry = intval( $opts['retry'] );
$this->_retryTimeout = intval( $opts['retryTimeout'] );
switch ( $tr ) {
case 'curl':
$this->_transport = array( $this, '_transportCurl' );
break;
case 'file':
$this->_transport = array( $this, '_transportFile' );
break;
case 'wordpress':
if ( ! function_exists( 'wp_remote_post' ) ) {
throw new DatafeedrError( "Wordpress transport requires wp_remote_post" );
}
$this->_transport = array( $this, '_transportWordpress' );
break;
case 'wordpress_or_curl':
if ( ! function_exists( 'wp_remote_post' ) ) {
$this->_transport = array( $this, '_transportCurl' );
$tr = 'curl';
} else {
$this->_transport = array( $this, '_transportWordpress' );
$tr = 'wordpress';
}
break;
default:
if ( ! is_callable( $tr ) ) {
throw new DatafeedrError( "Transport must be a function" );
}
$this->_transport = $tr;
$tr = 'custom';
}
$this->_hasZlib = function_exists( 'gzcompress' );
$this->_userAgent = sprintf( 'datafeedr.php.%s/%s/zlib=%s', self::VERSION, $tr,
$this->_hasZlib ? 'yes' : 'no' );
}
/**
* Perform an HTTP request.
*
* @since 2.0.0
*
* @param string $url
* @param array $headers
* @param string $postdata
*
* @throws DatafeedrConnectionError
*
* @return array An array of (status, responseBody)
*/
protected function _performRequest( $url, $headers, $postdata ) {
$retry = $this->_retry;
while ( true ) {
try {
return call_user_func( $this->_transport, $url, $headers, $postdata );
} catch ( DatafeedrConnectionError $err ) {
if ( $retry <= 0 ) {
throw $err;
}
sleep( $this->_retryTimeout );
$retry --;
}
}
return array();
}
/**
* Convert an ID or an array of IDs to a simple array of IDs.
*
* @since 1.0.0
*
* @param integer|string|array $id_or_ids An ID or an array of IDs.
*
* @return array An array of IDs.
*/
protected function _intarray( $id_or_ids ) {
if ( is_numeric( $id_or_ids ) ) {
return array( $id_or_ids );
}
if ( is_array( $id_or_ids ) ) {
return array_values( $id_or_ids );
}
return array();
}
/**
* Returns a specific value from an array or object for a given key or property. If key or
* property does not exist, returns $default.
*
* @since 1.0.0
*
* @param array|object $obj An array or object to extract value from.
* @param string $prop The array key or object property to get the value for.
* @param null $default Optional. The value to return if $obj or $prop does not exist.
*
* @return mixed|null The returned value.
*/
protected function _get( $obj, $prop, $default = null ) {
if ( is_array( $obj ) && isset( $obj[ $prop ] ) ) {
return $obj[ $prop ];
}
if ( is_object( $obj ) && isset( $obj->$prop ) ) {
return $obj->$prop;
}
return $default;
}
/**
* Perform an HTTP POST request using the CURL library.
*
* @since 1.0.0
*
* @param string $url Request url.
* @param array $headers Array of headers.
* @param string $postdata Post data.
*
* @throws DatafeedrConnectionError Throws error if curl_errno() returns an error.
*
* @return array (int http status, string response body)
*/
protected function _transportCurl( $url, $headers, $postdata ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $this->_timeout );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
curl_setopt( $ch, CURLOPT_ENCODING, '' );
$response = curl_exec( $ch );
$status = intval( curl_getinfo( $ch, CURLINFO_HTTP_CODE ) );
$errno = curl_errno( $ch );
$errmsg = curl_error( $ch );
curl_close( $ch );
if ( $errno ) {
throw new DatafeedrConnectionError( $errmsg, $errno );
}
return array( $status, $response );
}
/**
* Perform a HTTP post request using file functions.
*
* @since 1.0.0
*
* @param string $url Request url.
* @param array $headers Array of headers.
* @param string $postdata Post data.
*
* @throws DatafeedrConnectionError Throws error if $response is false.
*
* @return array (int http status, string response body)
*/
protected function _transportFile( $url, $headers, $postdata ) {
$options = array(
'http' => array(
'method' => 'POST',
'content' => $postdata,
'header' => implode( "\r\n", $headers ),
'ignore_errors' => true,
'timeout' => $this->_timeout,
)
);
$context = stream_context_create( $options );
$response = file_get_contents( $url, false, $context );
$status = 200;
if ( isset( $http_response_header ) && isset( $http_response_header[0] ) ) {
if ( preg_match( '/HTTP.+?(\d\d\d)/', $http_response_header[0], $match ) ) {
$status = intval( $match[1] );
}
} else if ( $response === false ) {
throw new DatafeedrConnectionError( "Invalid response" );
}
return array( $status, $response );
}
/**
* Perform a HTTP post request using Wordpress functions.
*
* @since 1.0.0
*
* @param string $url Request url.
* @param array $headers Array of headers.
* @param string $postdata Post data.
*
* @throws DatafeedrConnectionError Throws error if $response is WP_Error and the error code is 'http_request_failed'.
* @throws DatafeedrHTTPError Throws error if $response is WP_Error.
*
* @return array (int http status, string response body)
*/
protected function _transportWordpress( $url, $headers, $postdata ) {
$ha = array();
foreach ( $headers as $h ) {
$h = explode( ':', $h, 2 );
$ha[ strtolower( $h[0] ) ] = $h[1];
}
$args = array(
'method' => 'POST',
'headers' => $ha,
'body' => $postdata,
'httpversion' => '1.1',
'timeout' => $this->_timeout,
'blocking' => true,
'compress' => false,
'decompress' => true,
'user-agent' => $ha['user-agent']
);
$res = wp_remote_post( $url, $args );
if ( is_wp_error( $res ) ) {
$code = $res->get_error_code();
$message = $res->get_error_message();
if ( $code === 'http_request_failed' ) {
throw new DatafeedrConnectionError( $message );
} else {
throw new DatafeedrHTTPError( $message );
}
}
return array( $res['response']['code'], $res['body'] );
}
}
/**
* Generic Datafeedr API search request.
*/
class DatafeedrSearchRequestBase {
/**
* The DatafeedrAPI object.
*
* @since 1.0.0
* @var DatafeedrAPI $_api
*/
protected $_api;
/**
* An array containing the full response of the last API request.
*
* @since 1.0.0
* @var array $_lastResponse Response array.
*/
protected $_lastResponse;
/**
* DatafeedrSearchRequestBase constructor.
*
* @since 1.0.0
*
* @param DatafeedrApi $api
*/
public function __construct( $api ) {
$this->_api = $api;
}
/**
* Get the number of found products.
*
* @since 1.0.0
*
* @return integer
*/
public function getFoundCount() {
return $this->_responseItem( 'found_count', 0 );
}
/**
* Get the number of products that can be retrieved from the server.
*
* @since 1.0.0
*
* @return integer
*/
public function getResultCount() {
return $this->_responseItem( 'result_count', 0 );
}
/**
* Returns the full response from the last search.
*
* Possible items in array include the following:
*
* Array (
* 'found_count' => integer,
* 'length' => integer,
* 'merchants' => array,
* 'networks' => array,
* 'price_groups' => array,
* 'products' => array,
* 'result_count' => integer,
* 'status' => array,
* 'time' => integer,
* 'version' => string,
* )
*
* @since 1.0.0
*
* @return array An array of the full response.
*/
public function getResponse() {
return $this->_lastResponse;
}
/**
* Returns a specific item or property from the response data.
*
* @since 1.0.0
*
* @param string $prop The item or property to get from the response array or object.
* @param mixed $default Return if $prop is not found in the array or object.
*
* @throws DatafeedrError Throws error if $this->_lastResponse is NULL.
*
* @return mixed Specific item or property from response data.
*/
protected function _responseItem( $prop, $default ) {
if ( is_null( $this->_lastResponse ) ) {
throw new DatafeedrError( "Reading from an empty request" );
}
if ( is_object( $this->_lastResponse ) && isset( $this->_lastResponse->$prop ) ) {
return $this->_lastResponse->$prop;
}
if ( is_array( $this->_lastResponse ) && isset( $this->_lastResponse[ $prop ] ) ) {
return $this->_lastResponse[ $prop ];
}
return $default;
}
/**
* Sets the $_lastResponse property to the the full response from the last API request.
*
* @since 1.0.0
*
* @param string $action The request action (ex. status, search, merchants, networks, etc...)
* @param array $request The current API request.
*/
function _apiCall( $action, $request = null ) {
$this->_lastResponse = $this->_api->apiCall( $action, $request );
}
}
/**
* Class DatafeedrSearchRequest
*
* Search request for Datafeedr API.
*/
class DatafeedrSearchRequest extends DatafeedrSearchRequestBase {
protected $_query;
protected $_sort;
protected $_fields;
protected $_limit;
protected $_offset;
protected $_priceGroups;
protected $_excludeDuplicates;
protected $_merchantLimit;
/**
* DatafeedrSearchRequest constructor.
*
* @since 1.0.0
*
* @param DatafeedrApi $api
*/
public function __construct( $api ) {
parent::__construct( $api );
$this->_query = array();
$this->_sort = array();
$this->_fields = array();
$this->_limit = 0;
$this->_offset = 0;
$this->_priceGroups = 0;
$this->_excludeDuplicates = '';
$this->_merchantLimit = 0;
}
/**
* Add a query filter.
*
* @since 1.0.0
*
* @param string $filter Query filter.
*
* @return DatafeedrSearchRequest Returns $this.
*/
public function addFilter( $filter ) {
$this->_query[] = $filter;
return $this;
}
/**
* Adds a sort field.
*
* @since 1.0.0
*
* @param string $field Field name.
* @param integer $order One of DatafeedrApi::SORT_ASCENDING or DatafeedrApi::SORT_DESCENDING
*
* @throws DatafeedrError Throws error if sort order is invalid.
*
* @return DatafeedrSearchRequest Returns $this.
*/
public function addSort( $field, $order = DatafeedrApi::SORT_ASCENDING ) {
if ( strlen( $field ) && ( $field[0] == '+' || $field[0] == '-' ) ) {
$this->_sort [] = $field;
} else if ( $order == DatafeedrApi::SORT_ASCENDING ) {
$this->_sort [] = '+' . $field;
} else if ( $order == DatafeedrApi::SORT_DESCENDING ) {
$this->_sort [] = '-' . $field;
} else {
throw new DatafeedrError( "Invalid sort order" );
}
return $this;
}
/**
* Set which fields to retrieve.
*
* @since 1.0.0
*
* @param array $fields An array of fields to return for each requested item.
*
* Example:
*
* Array (
* 'name',
* 'price',
* 'description',
* 'url',
* )
*
* @return DatafeedrSearchRequest Returns $this.
*/
public function setFields( $fields ) {
$this->_fields = $fields;
return $this;
}
/**
* Exclude duplicate filter.
*
* @since 1.0.0
*
* @param string $filter Equality filter in form "field1 field2 | field3".
*
* @return DatafeedrSearchRequest Returns $this.
*/
public function excludeDuplicates( $filter ) {
if ( is_array( $filter ) ) {
$filter = implode( ' ', $filter );
}
$this->_excludeDuplicates = $filter;
return $this;
}
/**
* Set a limit of number of records to return.
*
* @since 1.0.0
*
* @param integer $limit The maximum number of records to return.