Payload::customerProperties()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Th3Mouk\ReactiveKlaviyo;
6
7
final class Payload
8
{
9
    /** @var string */
10
    private $event;
11
12
    /** @var Property[] */
13
    private $customer_properties = [];
14
15
    /** @var Property[] */
16
    private $properties = [];
17
18
    /** @var int|null */
19
    private $event_occured_at;
20
21
    private function __construct(string $event)
22
    {
23
        $this->event = $event;
24
    }
25
26
    public static function create(string $event): self
27
    {
28
        return new self($event);
29
    }
30
31
    public function addCustomerProperty(Property $customer_property): self
32
    {
33
        $this->customer_properties[] = $customer_property;
34
35
        return $this;
36
    }
37
38
    public function addProperty(Property $property): self
39
    {
40
        $this->properties[] = $property;
41
42
        return $this;
43
    }
44
45
    public function definePastEventDate(int $timestamp): self
46
    {
47
        $this->event_occured_at = $timestamp;
48
49
        return $this;
50
    }
51
52
    public function event(): string
53
    {
54
        return $this->event;
55
    }
56
57
    /**
58
     * @return Property[]
59
     */
60
    public function customerProperties(): array
61
    {
62
        return $this->customer_properties;
63
    }
64
65
    /**
66
     * @return Property[]
67
     */
68
    public function properties(): array
69
    {
70
        return $this->properties;
71
    }
72
73
    public function eventOccurredAt(): ?int
74
    {
75
        return $this->event_occured_at;
76
    }
77
78
    /**
79
     * @param Property[] $properties
80
     *
81
     * @return array<string, array<bool|float|int|string>|bool|float|int|string>
82
     */
83
    private function reduceProperties(array $properties): array
84
    {
85
        $reduced = [];
86
87
        /** @var Property $property */
88
        foreach ($properties as $property) {
89
            $reduced[$property->name()] = $property->value();
90
        }
91
92
        return $reduced;
93
    }
94
95
    /**
96
     * @return array<string, string|int|array<string, array<bool|float|int|string>|bool|float|int|string>>
97
     */
98
    public function toArray(): array
99
    {
100
        $optional = [];
101
102
        if (null !== $this->eventOccurredAt()) {
103
            $optional['time'] = $this->eventOccurredAt();
104
        }
105
106
        return array_merge([
107
            'event' => $this->event(),
108
            'customer_properties' => $this->reduceProperties($this->customerProperties()),
109
            'properties' => $this->reduceProperties($this->properties()),
110
        ], $optional);
111
    }
112
}
113