DataLayer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\GoogleTagManager;
4
5
class DataLayer
6
{
7
    /**
8
     * @var array
9
     */
10
    protected $data;
11
12
    public function __construct($data = [])
13
    {
14
        $this->data = $data;
15
    }
16
17
    /**
18
     * Add data to the data layer. Supports dot notation.
19
     * Inspired by laravel's config repository class.
20
     *
21
     * @param array|string $key
22
     * @param mixed        $value
23
     */
24
    public function set($key, $value = null)
25
    {
26
        if (is_array($key)) {
27
            foreach ($key as $innerKey => $innerValue) {
28
                array_set($this->data, $innerKey, $innerValue);
29
            }
30
31
            return;
32
        }
33
34
        array_set($this->data, $key, $value);
35
    }
36
37
    /**
38
     * Empty the data layer.
39
     */
40
    public function clear()
41
    {
42
        $this->data = [];
43
    }
44
45
    /**
46
     * Return a json representation of the data layer.
47
     *
48
     * @return string
49
     */
50
    public function toJson()
51
    {
52
        return empty($this->data) ? null : json_encode($this->data);
53
    }
54
}
55