|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Hborras\TwitterAdsSDK\TwitterAds; |
|
4
|
|
|
|
|
5
|
|
|
use Hborras\TwitterAdsSDK\TwitterAds\Resource; |
|
6
|
|
|
use Hborras\TwitterAdsSDK\TwitterAds\Account; |
|
7
|
|
|
use Hborras\TwitterAdsSDK\Arrayable; |
|
8
|
|
|
use Hborras\TwitterAdsSDK\TwitterAds\Errors\BatchLimitExceeded; |
|
9
|
|
|
|
|
10
|
|
|
abstract class Batch extends Resource |
|
11
|
|
|
{ |
|
12
|
|
|
private $batch = []; |
|
13
|
|
|
private $batchSize; |
|
14
|
|
|
private $account; |
|
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
public function __construct(Account $account=null, $batchSize=10, $batch=[]) |
|
17
|
|
|
{ |
|
18
|
|
|
parent::__construct($account); |
|
19
|
|
|
$this->account = $account; |
|
20
|
|
|
$this->batchSize = $batchSize; |
|
21
|
|
|
$this->batch = $this->assureBatchSize($batch); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* {@inheritdoc} |
|
26
|
|
|
*/ |
|
27
|
|
|
public function getId() |
|
28
|
|
|
{ |
|
29
|
|
|
//Always use POST request by setting the ID to null |
|
30
|
|
|
return null; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function getAccount() |
|
34
|
|
|
{ |
|
35
|
|
|
return $this->account; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* {@inheritdoc} |
|
40
|
|
|
*/ |
|
41
|
|
|
public function toParams() |
|
42
|
|
|
{ |
|
43
|
|
|
$data = []; |
|
44
|
|
|
|
|
45
|
|
|
foreach ($this->batch as $member) { |
|
46
|
|
|
$data[] = $member->toArray(); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
return $data; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function getBatch() |
|
53
|
|
|
{ |
|
54
|
|
|
return $this->batch; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function add(Arrayable $data) |
|
58
|
|
|
{ |
|
59
|
|
|
$this->assureBatchSize(); |
|
60
|
|
|
|
|
61
|
|
|
$this->batch[] = $data; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* Assures the batch is not over the batch size limit. |
|
66
|
|
|
* |
|
67
|
|
|
* @param $batch|null |
|
68
|
|
|
* |
|
69
|
|
|
* @throws BatchLimitExceeded when the batch is full |
|
70
|
|
|
* @return $batch|$this->batch |
|
|
|
|
|
|
71
|
|
|
*/ |
|
72
|
|
|
public function assureBatchSize($batch=null) |
|
73
|
|
|
{ |
|
74
|
|
|
if (count($batch ?: $this->batch) < $this->batchSize) { |
|
75
|
|
|
return $batch ?: $this->batch; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
throw new BatchLimitExceeded(sprintf( |
|
79
|
|
|
'Cannot add data to batch. Max size is %s', |
|
80
|
|
|
$this->batchSize |
|
81
|
|
|
)); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|