Completed
Pull Request — master (#22)
by
unknown
06:08
created

TriggerCampaignForUserAndActionListItemWithResult()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
ccs 5
cts 5
cp 1
cc 1
eloc 5
nc 1
nop 3
crap 1
1
<?php
2
3
/**
4
 * This file is part of the Mediapart Selligent Client API
5
 *
6
 * CC BY-NC-SA <https://github.com/mediapart/selligent>
7
 *
8
 * For the full license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Mediapart\Selligent;
13
14
use Psr\Log\LoggerInterface;
15
use Psr\Log\LoggerAwareInterface;
16
17
use Mediapart\Selligent\Response\GetUserByFilterResponse;
18
19
/**
20
 *
21
 */
22
class Transport implements LoggerAwareInterface
23
{
24
    /**
25
     * @var \SoapClient
26
     */
27
    protected $client;
28
29
    /**
30
     * @var int
31
     */
32
    protected $list;
33
34
    /**
35
     * @var string
36
     */
37
    protected $campaign;
38
39
    /**
40
     * @var LoggerInterface
41
     */
42
    protected $logger = null;
43
44
    /**
45
     * @param \SoapClient $client
46
     * @param string $list
47
     * @param string $campaign
48
     */
49 11
    public function __construct(\SoapClient $client, $list = null, $campaign = null)
50
    {
51 11
        $this->client = $client;
52
53 11
        if (!is_null($list)) {
54 8
            $this->setList($list);
55 8
        }
56 11
        if (!is_null($campaign)) {
57 8
            $this->setCampaign($campaign);
58 8
        }
59 11
    }
60
61
    /**
62
     * {@inheritDoc}
63
     */
64 7
    public function setLogger(LoggerInterface $logger)
65
    {
66 7
        $this->logger = $logger;
67 7
    }
68
69
    /**
70
     *
71
     * @param string $list Name of the list 
72
     * @throws Exception if the list was not found in the remote server
73
     * @return self
74
     */
75 10
    public function setList($list)
76
    {
77 10
        $response = $this->client->GetListID(['name' => $list]);
78
79 10
        if (Response::SUCCESSFUL !== $response->getCode()) {
80 1
            throw new \Exception();
81
        } else {
82 9
            $this->list = $response->getId();
83
84 9
            return $this;
85
        }
86
    }
87
88
    /**
89
     * @return int
90
     */
91 2
    public function getList()
92
    {
93 2
        return $this->list;
94
    }
95
96
    /**
97
     *
98
     * @param string $campaign Gate Name
99
     * @return self
100
     */
101 9
    public function setCampaign($campaign)
102
    {
103 9
        $this->campaign = $campaign;
104
105 9
        return $this;
106
    }
107
108
    /**
109
     * @return string
110
     */
111 2
    public function getCampaign()
112
    {
113 2
        return $this->campaign;
114
    }
115
116
    /**
117
     * @param GetUserByFilterResponse $response
118
     * @param string $idKey
119
     *
120
     * @return integer
121
     */
122 2
    private function getExistingUserId(GetUserByFilterResponse $response, $idKey)
123
    {
124 2
        $properties = $response->getProperties();
125 2
        if (isset($properties[$idKey])) {
126 1
            $id = $properties[$idKey];
127 1
            if ($this->logger) {
128 1
                $this->logger->info('User already registered', [$idKey => $id]);
129 1
            }
130 1
            return $id;
131
        } else {
132 1
            throw new \UnexpectedValueException(sprintf(
133 1
                "key %s do not exists in %s",
134 1
                $idKey,
135 1
                implode(',', array_keys((array) $properties))
136 1
            ));
137
        }
138
    }
139
140
    /**
141
     * @param Properties $user
142
     * @return integer
143
     */
144 2
    private function createUser(Properties $user)
145
    {
146 2
        $response = $this->client->CreateUser([
147 2
            'List' => $this->list,
148 2
            'Changes' => $user,
149 2
        ]);
150 2
        $id = null;
151 2
        if (Response::SUCCESSFUL === $response->getCode()) {
152 1
            $id = $response->getUserId();
153 1
            if ($this->logger) {
154 1
                $this->logger->notice(
155 1
                    'New user registered',
156
                    [
157 1
                        'id' => $id, 
158
                        'properties' => $user
159 1
                    ]
160 1
                );
161 1
            }
162 1
        }
163 2
        return $id;
164
    }
165
166
    /**
167
     * Subscribe the given user, if not already in list, and returns his identifier
168
     *
169
     * @param Properties $user
170
     * @return int User id
171
     * @throws UnexpectedValueException if $idKey is not an existing Property
172
     * @throws Exception If something happens during the request
173
     */
174 5
    public function subscribe(Properties $user, $idKey = 'ID')
175
    {
176 5
        $response = $this->client->GetUserByFilter([
177 5
            'List' => $this->list,
178 5
            'Filter' => $user,
179 5
        ]);
180
181
        try {
182 5
            switch ($response->getCode()) {
183
184
                /* the user already exists */
185 5
                case Response::SUCCESSFUL:
186 2
                    $id = $this->getExistingUserId($response, $idKey);
187 1
                    break;
188
189
                /* the user do not exist, we create it */
190 3
                case Response::ERROR_NORESULT:
191 2
                    if($id = $this->createUser($user)) {
192 1
                        break;
193
                    }
194
195
                /* something wrong */
196 2
                default:
197 2
                    throw new \Exception(
198 2
                        $response->getError(),
199 2
                        $response->getCode()
200 2
                    );
201 3
            }
202 5
        } catch (\Exception $e) {
203 3
            if ($this->logger) {
204 3
                $this->logger->error($e->getMessage());
205 3
            }
206 3
            throw $e;
207
        }
208
209 2
        return $id;
210
    }
211
212
    /**
213
     * @param int $userId
214
     * @param Properties $inputData
215
     * @param array $actionProperties
216
     */
217
    public function TriggerCampaignForUserAndActionListItemWithResult($userId, Properties $inputData, array $actionProperties = [])
218 2
    {
219
        $options['Actioncode'] = $actionProperties['Actioncode'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
220
        $options['ActionListID'] = $actionProperties['ActionListID'];
221 2
        $options['ActionListItemData'] = $inputData;
222 2
223 2
        $this->triggerCampaign($userId,'TriggerCampaignForUserAndActionListItemWithResult', $options);
224 2
    }
225 2
226
    /**
227 2
     * @param int $userId
228
     * @param Properties $inputData
229
     */
230 2
    public function TriggerCampaignForUserWithResult($userId, Properties $inputData)
231
    {
232 2
        $options['InputData'] = $inputData;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
233 2
234 2
        $this->triggerCampaign($userId,'TriggerCampaignForUserWithResult', $options);
235 2
    }
236 2
237
    /**
238 2
     * @param int $userId
239 1
     * @param string $method
240 1
     * @param array $options
241 1
     * @return mixed
242 1
     * @throws \Exception
243 1
     */
244 1
    private function triggerCampaign($userId, $method = 'TriggerCampaignForUserWithResult', array $options)
245 1
    {
246
        $options = array_merge($this->getOptions($userId), $options);
247 1
248 1
        $response = call_user_func([$this->client, $method], $options);
249 1
250 1
        $context = [
251
            'request' => [
252
                'method' => $method,
253
                'value' => $options,
254
           ],
255
            'response' => [
256
                'code' => $response->getCode(),
257
                'error' => $response->getError(),
258
                'result' => $response->getResult(),
259
            ],
260
        ];
261
262
        if (Response::SUCCESSFUL !== $response->getCode()) {
263
            if ($this->logger) {
264
                $this->logger->error('triggerCampaign has failed', $context);
265
            }
266
            throw new \Exception(
267
                $response->getError(),
268
                $response->getCode()
269
            );
270
        } else {
271
            if ($this->logger) {
272
                $this->logger->info('triggerCampaign with success', $context);
273
            }
274
            return $response->getResult();
275
        }
276
    }
277
278
    /**
279
     * @param int $userId
280
     * @return array
281
     */
282
    private function getOptions($userId)
283
    {
284
        $options = [
285
            'List' => $this->list,
286
            'UserID' => $userId,
287
            'GateName' => $this->campaign,
288
        ];
289
290
        return $options;
291
    }
292
}
293