Completed
Pull Request — master (#8)
by
unknown
03:17
created

Batch::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 7
rs 9.4285
cc 1
eloc 5
nc 1
nop 3
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;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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
0 ignored issues
show
Documentation introduced by
The doc-type $batch|$this->batch could not be parsed: Unknown type name "$batch" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
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