Completed
Push — master ( ef8259...e600b3 )
by Giacomo "Mr. Wolf"
02:28
created

BeesWaxSegmentManager::create()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 48
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 27
nc 17
nop 1
dl 0
loc 48
rs 8.8657
c 0
b 0
f 0
1
<?php
2
3
namespace Audiens\BeesWax\Segment;
4
5
use Audiens\BeesWax\BeesWaxResponse;
6
use Audiens\BeesWax\BeesWaxSession;
7
use Audiens\BeesWax\Exception\BeesWaxGenericException;
8
use Audiens\BeesWax\Exception\BeesWaxResponseException;
9
10
class BeesWaxSegmentManager
11
{
12
    protected const CREATE_PATH = '/rest/segment';
13
    protected const READ_PATH   = '/rest/segment';
14
15
    /** @var BeesWaxSession */
16
    protected $session;
17
18
    public function __construct(BeesWaxSession $session)
19
    {
20
        $this->session = $session;
21
    }
22
23
    /**
24
     * Returns a BeesWax segment.
25
     * The argument segment will be modified adding the identifier to it
26
     *
27
     * @param BeesWaxSegment $segment
28
     *
29
     * @return BeesWaxSegment
30
     * @throws \Audiens\BeesWax\Exception\BeesWaxGenericException
31
     * @throws \Audiens\BeesWax\Exception\BeesWaxResponseException
32
     */
33
    public function create(BeesWaxSegment $segment): BeesWaxSegment
34
    {
35
        if ($segment->getId()) {
36
            throw new BeesWaxGenericException(
37
                sprintf('The segment %s has already been created', $segment->getName()),
38
                BeesWaxGenericException::CODE_SEGMENT_ALREADY_CREATED
39
            );
40
        }
41
42
        $payloadData = [
43
            'segment_name' => $segment->getName(),
44
            'cpm_cost' => $segment->getCpmCost(),
45
            'ttl_days' => $segment->getTtlDays(),
46
            'aggregate_excludes' => $segment->isAggregateExcludes(),
47
        ];
48
49
        if ($advertiserId = $segment->getAdvertiserId()) {
50
            $payloadData['advertiser_id'] = $advertiserId;
51
        }
52
53
        if ($description = $segment->getDescription()) {
54
            $payloadData['segment_description'] = $description;
55
        }
56
57
        if ($alternativeId = $segment->getAlternativeId()) {
58
            $payloadData['alternative_id'] = $alternativeId;
59
        }
60
61
        $payload = json_encode($payloadData);
62
63
        $request = $this->session->getRequestBuilder()->build(static::CREATE_PATH, [], 'POST', $payload);
64
65
        $response = $request->doRequest();
66
        $this->manageSuccess($response, 'Error creating segment: %s');
67
68
        $responseData = json_decode($response->getPayload());
69
        $segmentId = $responseData->payload->id ?? null;
70
71
        if ($segmentId === null) {
72
            throw new BeesWaxResponseException(
73
                $response->getCurlHandler(),
74
                'Error creating segment: id not found'
75
            );
76
        }
77
78
        $segment->setId((string) $segmentId);
79
80
        return $segment;
81
    }
82
83
    public function update(BeesWaxSegment $segment): BeesWaxSegment
0 ignored issues
show
Unused Code introduced by
The parameter $segment is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

83
    public function update(/** @scrutinizer ignore-unused */ BeesWaxSegment $segment): BeesWaxSegment

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
84
    {
85
        throw new \RuntimeException('Not implemented yet!');
86
    }
87
88
    public function delete(BeesWaxSegment $segment): bool
0 ignored issues
show
Unused Code introduced by
The parameter $segment is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

88
    public function delete(/** @scrutinizer ignore-unused */ BeesWaxSegment $segment): bool

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
89
    {
90
        throw new \RuntimeException('Not implemented yet!');
91
    }
92
93
    /**
94
     * @param string $id
95
     *
96
     * @return BeesWaxSegment
97
     * @throws BeesWaxGenericException
98
     * @throws BeesWaxResponseException
99
     */
100
    public function read(string $id): BeesWaxSegment
101
    {
102
        $request = $this->session->getRequestBuilder()->build(static::READ_PATH, ['segment_id' => $id], 'GET', null);
103
104
        $response = $request->doRequest();
105
        $this->manageSuccess($response, 'Error reading segment: %s');
106
107
        $responseData = json_decode($response->getPayload());
108
        if (!isset($responseData->payload) || !\is_array($responseData->payload) || \count($responseData->payload) !== 1) {
109
            throw new BeesWaxGenericException(sprintf('Segment #%s not found', $id), BeesWaxGenericException::CODE_SEGMENT_NOT_FOUND);
110
        }
111
        $responseData = $responseData->payload[0];
112
113
        $segment = new BeesWaxSegment(
114
            $responseData->segment_name,
115
            $responseData->segment_description,
116
            $responseData->alternative_id,
117
            $responseData->advertiser_id,
118
            $responseData->cpm_cost,
119
            $responseData->ttl_days,
120
            $responseData->aggregate_excludes
121
        );
122
        $segment->setId((string)$responseData->segment_id);
123
124
        return $segment;
125
    }
126
127
    /**
128
     * @param BeesWaxResponse $response
129
     * @param string          $errorFormat with one string parameter
130
     *
131
     * @throws BeesWaxResponseException
132
     */
133
    private function manageSuccess(BeesWaxResponse $response, string $errorFormat): void
134
    {
135
        $responseData = json_decode($response->getPayload());
136
        $responseErrors = $responseData->errors ?? [];
137
        $statusCode = $response->getStatusCode();
138
139
        if (
140
            !empty($responseErrors)
141
            || \is_bool($responseData)
142
            || (isset($responseData->success) && !$responseData->success)
143
            || $statusCode !== 200
144
        ) {
145
            $message = \count($responseErrors) ? $responseErrors[0] : ($responseData->message ?? (string) $statusCode);
146
            throw new BeesWaxResponseException(
147
                $response->getCurlHandler(),
148
                sprintf($errorFormat, $message)
149
            );
150
        }
151
    }
152
}
153