Completed
Pull Request — master (#8)
by Romain
04:20
created

Data::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
namespace ker0x\Push\Adapter\Fcm\Message;
3
4
use ker0x\Push\Adapter\Fcm\Message\Exception\InvalidDataException;
5
6
class Data implements BuilderInterface
7
{
8
9
    /**
10
     * @var array
11
     */
12
    protected $data = [];
13
14
    /**
15
     * Data constructor.
16
     *
17
     * @param array|\ker0x\Push\Adapter\Fcm\Message\DataBuilder $dataBuilder The data we want to send.
18
     * @throws \ker0x\Push\Adapter\Fcm\Message\Exception\InvalidDataException
19
     */
20
    public function __construct($dataBuilder)
21
    {
22
        if (is_array($dataBuilder)) {
23
            $dataBuilder = $this->fromArray($dataBuilder);
24
        }
25
26
        $this->data = $dataBuilder->getAllData();
27
    }
28
29
    /**
30
     * Return data as an array.
31
     *
32
     * @return array
33
     */
34
    public function build()
35
    {
36
        return $this->data;
37
    }
38
39
    /**
40
     * Build data from an array.
41
     *
42
     * @param array $dataArray Array of data for the notification.
43
     * @return \ker0x\Push\Adapter\Fcm\Message\DataBuilder
44
     * @throws \ker0x\Push\Adapter\Fcm\Message\Exception\InvalidDataException
45
     */
46
    private function fromArray(array $dataArray)
47
    {
48
        if (empty($dataArray)) {
49
            throw InvalidDataException::arrayEmpty();
50
        }
51
52
        $dataBuilder = new DataBuilder();
53
        foreach ($dataArray as $key => $value) {
54
            $dataBuilder->addData($key, $value);
55
        }
56
57
        return $dataBuilder;
58
    }
59
}
60