Test Setup Failed
Push — master ( cb9c22...4c02e1 )
by Alexey
02:54
created

UserApi::getUsersFromList()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 6
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Skobkin\Bundle\PointToolsBundle\Service;
4
5
use GuzzleHttp\ClientInterface;
6
use GuzzleHttp\Exception\RequestException;
7
use JMS\Serializer\Serializer;
8
use Psr\Log\LoggerInterface;
9
use Skobkin\Bundle\PointToolsBundle\DTO\Api\Auth;
10
use Skobkin\Bundle\PointToolsBundle\Entity\User;
11
use Skobkin\Bundle\PointToolsBundle\Service\Exceptions\ApiException;
12
use Skobkin\Bundle\PointToolsBundle\Service\Exceptions\InvalidResponseException;
13
use Skobkin\Bundle\PointToolsBundle\Service\Exceptions\UserNotFoundException;
14
use Skobkin\Bundle\PointToolsBundle\Service\Factory\UserFactory;
15
use Symfony\Component\HttpFoundation\Response;
16
17
/**
18
 * Basic Point.im user API functions from /api/user/*
19
 */
20
class UserApi extends AbstractApi
21
{
22
    /**
23
     * @var UserFactory
24
     */
25
    private $userFactory;
26
27
    /**
28
     * @var Serializer
29
     */
30
    private $serializer;
31
32
    public function __construct(ClientInterface $httpClient, LoggerInterface $logger, UserFactory $userFactory, Serializer $serializer)
0 ignored issues
show
Unused Code introduced by
The parameter $userFactory is not used and could be removed.

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

Loading history...
33
    {
34
        parent::__construct($httpClient, $logger);
35
36
        $this->serializer = $serializer;
37
    }
38
39
    public function isAuthDataValid(string $login, string $password): bool
40
    {
41
        $this->logger->info('Checking user auth data via point.im API');
42
43
        $auth = $this->authenticate($login, $password);
44
45
        if (null === $auth->getError() && null !== $auth->getToken()) {
46
            $this->logger->debug('Authentication successfull. Logging out.');
47 12
48
            $this->logout($auth);
49 12
50
            return true;
51 12
        }
52 12
53 12
        return false;
54 12
    }
55
56
    public function authenticate(string $login, string $password): Auth
57
    {
58
        $this->logger->debug('Trying to authenticate user via Point.im API', ['login' => $login]);
59
60
        try {
61
            $authData = $this->getPostRequestData(
62
                '/api/login',
63
                [
64
                    'login' => $login,
65
                    'password' => $password,
66
                ]
67
            );
68
69
            return $this->serializer->deserialize($authData, Auth::class, 'json');
0 ignored issues
show
Bug introduced by
It seems like $authData defined by $this->getPostRequestDat...assword' => $password)) on line 61 can also be of type array or object; however, JMS\Serializer\Serializer::deserialize() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
70
        } catch (RequestException $e) {
71
            if (Response::HTTP_NOT_FOUND === $e->getResponse()->getStatusCode()) {
72
                throw new InvalidResponseException('API method not found', 0, $e);
73
            } else {
74
                throw $e;
75
            }
76
        }
77
    }
78
79
    public function logout(Auth $auth): bool
80
    {
81
        $this->logger->debug('Trying to log user out via Point.im API');
82
83
        try {
84
            $this->getPostRequestData('/api/logout', ['csrf_token' => $auth->getCsRfToken()]);
85
86
            return true;
87
        } catch (RequestException $e) {
88
            if (Response::HTTP_NOT_FOUND === $e->getResponse()->getStatusCode()) {
89
                throw new InvalidResponseException('API method not found', 0, $e);
90
            } elseif (Response::HTTP_FORBIDDEN === $e->getResponse()->getStatusCode()) {
91
                return true;
92
            } else {
93
                throw $e;
94
            }
95
        }
96
    }
97
98
    /**
99
     * Get user subscribers by user login
100
     *
101
     * @param string $login
102
     *
103
     * @return User[]
104
     *
105
     * @throws ApiException
106
     * @throws InvalidResponseException
107
     * @throws UserNotFoundException
108
     */
109 View Code Duplication
    public function getUserSubscribersByLogin(string $login): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
    {
111
        $this->logger->debug('Trying to get user subscribers by login', ['login' => $login]);
112
113
        try {
114
            $usersList = $this->getGetRequestData('/api/user/'.urlencode($login).'/subscribers', [], true);
115
        } catch (RequestException $e) {
116
            if (Response::HTTP_NOT_FOUND === $e->getResponse()->getStatusCode()) {
117
                throw new UserNotFoundException('User not found', 0, $e, null, $login);
118
            } else {
119
                throw $e;
120
            }
121
        }
122
123
        return $this->getUsersFromList($usersList);
0 ignored issues
show
Bug introduced by
It seems like $usersList defined by $this->getGetRequestData...ribers', array(), true) on line 114 can also be of type object or string; however, Skobkin\Bundle\PointTool...Api::getUsersFromList() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
124
    }
125
126
    /**
127
     * Get user subscribers by user id
128
     *
129
     * @param int $id
130
     *
131
     * @return User[]
132
     *
133
     * @throws ApiException
134
     * @throws InvalidResponseException
135
     * @throws UserNotFoundException
136
     */
137 View Code Duplication
    public function getUserSubscribersById(int $id): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
138
    {
139
        $this->logger->debug('Trying to get user subscribers by id', ['id' => $id]);
140
141
        try {
142
            $usersList = $this->getGetRequestData('/api/user/id/'.(int) $id.'/subscribers', [], true);
143
        } catch (RequestException $e) {
144
            if (Response::HTTP_NOT_FOUND === $e->getResponse()->getStatusCode()) {
145
                throw new UserNotFoundException('User not found', 0, $e, $id);
146
            } else {
147
                throw $e;
148
            }
149
        }
150
151
        return $this->getUsersFromList($usersList);
0 ignored issues
show
Bug introduced by
It seems like $usersList defined by $this->getGetRequestData...ribers', array(), true) on line 142 can also be of type object or string; however, Skobkin\Bundle\PointTool...Api::getUsersFromList() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
152
    }
153
154
    /**
155
     * Get user subscriptions by user login
156
     *
157
     * @param string $login
158
     *
159
     * @return User[]
160
     *
161
     * @throws ApiException
162
     * @throws InvalidResponseException
163
     * @throws UserNotFoundException
164
     */
165 View Code Duplication
    public function getUserSubscriptionsByLogin(string $login): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
166
    {
167
        $this->logger->debug('Trying to get user subscriptions by login', ['login' => $login]);
168
169
        try {
170
            $usersList = $this->getGetRequestData('/api/user/'.urlencode($login).'/subscriptions', [], true);
171
        } catch (RequestException $e) {
172
            if (Response::HTTP_NOT_FOUND === $e->getResponse()->getStatusCode()) {
173
                throw new UserNotFoundException('User not found', 0, $e, null, $login);
174
            } else {
175
                throw $e;
176
            }
177
        }
178
179
        return $this->getUsersFromList($usersList);
0 ignored issues
show
Bug introduced by
It seems like $usersList defined by $this->getGetRequestData...ptions', array(), true) on line 170 can also be of type object or string; however, Skobkin\Bundle\PointTool...Api::getUsersFromList() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
180
    }
181
182
    /**
183
     * Get user subscriptions by user id
184
     *
185
     * @param int $id
186
     *
187
     * @return User[]
188
     *
189
     * @throws ApiException
190
     * @throws InvalidResponseException
191
     * @throws UserNotFoundException
192
     */
193 View Code Duplication
    public function getUserSubscriptionsById(int $id): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
194
    {
195
        $this->logger->debug('Trying to get user subscriptions by id', ['id' => $id]);
196
197
        try {
198
            $usersList = $this->getGetRequestData('/api/user/id/'.(int) $id.'/subscriptions', [], true);
199
        } catch (RequestException $e) {
200
            if (Response::HTTP_NOT_FOUND === $e->getResponse()->getStatusCode()) {
201
                throw new UserNotFoundException('User not found', 0, $e, $id);
202
            } else {
203
                throw $e;
204
            }
205
        }
206
207
        return $this->getUsersFromList($usersList);
0 ignored issues
show
Bug introduced by
It seems like $usersList defined by $this->getGetRequestData...ptions', array(), true) on line 198 can also be of type object or string; however, Skobkin\Bundle\PointTool...Api::getUsersFromList() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
208
    }
209
210
    /**
211
     * Get single user by login
212
     *
213
     * @param string $login
214
     *
215
     * @return User
216
     *
217
     * @throws UserNotFoundException
218
     * @throws RequestException
219
     */
220 View Code Duplication
    public function getUserByLogin(string $login): User
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
221
    {
222
        $this->logger->debug('Trying to get user by login', ['login' => $login]);
223
224
        try {
225
            $userInfo = $this->getGetRequestData('/api/user/login/'.urlencode($login), [], true);
226
        } catch (RequestException $e) {
227
            if (Response::HTTP_NOT_FOUND === $e->getResponse()->getStatusCode()) {
228
                throw new UserNotFoundException('User not found', 0, $e, null, $login);
229
            } else {
230
                throw $e;
231
            }
232
        }
233
234
        return $this->getUserFromUserInfo($userInfo);
0 ignored issues
show
Bug introduced by
It seems like $userInfo defined by $this->getGetRequestData...$login), array(), true) on line 225 can also be of type object or string; however, Skobkin\Bundle\PointTool...::getUserFromUserInfo() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
235
    }
236
237
    /**
238
     * Get single user by id
239
     *
240
     * @param int $id
241
     *
242
     * @return User
243
     *
244
     * @throws UserNotFoundException
245
     * @throws RequestException
246
     */
247 View Code Duplication
    public function getUserById(int $id): User
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
248
    {
249
        $this->logger->debug('Trying to get user by id', ['id' => $id]);
250
251
        try {
252
            $userInfo = $this->getGetRequestData('/api/user/id/'.$id, [], true);
253
        } catch (RequestException $e) {
254
            if (Response::HTTP_NOT_FOUND === $e->getResponse()->getStatusCode()) {
255
                throw new UserNotFoundException('User not found', 0, $e, $id);
256
            } else {
257
                throw $e;
258
            }
259
        }
260
261
        return $this->getUserFromUserInfo($userInfo);
0 ignored issues
show
Bug introduced by
It seems like $userInfo defined by $this->getGetRequestData...' . $id, array(), true) on line 252 can also be of type object or string; however, Skobkin\Bundle\PointTool...::getUserFromUserInfo() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
262
    }
263
264
    /**
265
     * Finds and updates or create new user from API response data
266
     *
267
     * @param array $userInfo
268
     *
269
     * @return User
270
     *
271
     * @throws ApiException
272
     * @throws InvalidResponseException
273
     */
274
    private function getUserFromUserInfo(array $userInfo): User
275
    {
276
        $this->logger->debug('Trying to create user from array', ['array' => $userInfo]);
277
278
        return $this->userFactory->createFromArray($userInfo);
279
    }
280
281
    /**
282
     * Get array of User objects from API response containing user list
283
     *
284
     * @param array $users
285
     *
286
     * @return User[]
287
     *
288
     * @throws ApiException
289
     * @throws InvalidResponseException
290
     */
291
    private function getUsersFromList(array $users = []): array
292
    {
293
        $this->logger->debug('Trying to create multiple users from array', ['array' => $users]);
294
295
        /** @var User[] $resultUsers */
296
        $resultUsers = [];
297
298
        foreach ($users as $userInfo) {
299
            $resultUsers[] = $this->getUserFromUserInfo($userInfo);
300
        }
301
302
        return $resultUsers;
303
    }
304
}
305