UserApi::getUserById()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Skobkin\Bundle\PointToolsBundle\Service\Api;
4
5
use GuzzleHttp\ClientInterface;
6
use JMS\Serializer\{
7
    DeserializationContext, SerializerInterface
8
};
9
use Psr\Log\LoggerInterface;
10
use Skobkin\Bundle\PointToolsBundle\DTO\Api\{Auth, User as UserDTO};
11
use Skobkin\Bundle\PointToolsBundle\Entity\User;
12
use Skobkin\Bundle\PointToolsBundle\Exception\Api\{ForbiddenException, InvalidResponseException, NotFoundException, UserNotFoundException};
13
use Skobkin\Bundle\PointToolsBundle\Service\Factory\UserFactory;
14
15
/**
16
 * Basic Point.im user API functions from /api/user/*
17
 */
18
class UserApi extends AbstractApi
19
{
20
    private const PREFIX = '/api/user/';
21
22
    /**
23
     * @var UserFactory
24
     */
25
    private $userFactory;
26
27
    public function __construct(ClientInterface $httpClient, SerializerInterface $serializer, LoggerInterface $logger, UserFactory $userFactory)
28
    {
29
        parent::__construct($httpClient, $serializer, $logger);
30
31
        $this->userFactory = $userFactory;
32
    }
33
34
    public function isLoginAndPasswordValid(string $login, string $password): bool
35
    {
36
        $this->logger->info('Checking user auth data via point.im API');
37
38
        $auth = $this->authenticate($login, $password);
39
40
        if ($auth->isValid()) {
41
            $this->logger->debug('Authentication successfull. Logging out.');
42
43
            $this->logout($auth);
44
45
            return true;
46
        }
47
48
        return false;
49
    }
50
51
    public function authenticate(string $login, string $password): Auth
52
    {
53
        $this->logger->debug('Trying to authenticate user via Point.im API', ['login' => $login]);
54
55
        try {
56
            return $this->getPostJsonData(
57
                '/api/login',
58
                [
59
                    'login' => $login,
60
                    'password' => $password,
61
                ],
62
                Auth::class
63
            );
64
        } catch (NotFoundException $e) {
65
            throw new InvalidResponseException('API method not found', 0, $e);
66
        }
67
    }
68
69
    /**
70
     * @throws InvalidResponseException
71
     */
72
    public function logout(Auth $auth): bool
73
    {
74
        $this->logger->debug('Trying to log user out via Point.im API');
75
76
        try {
77
            $this->getPostResponseBody('/api/logout', ['csrf_token' => $auth->getCsRfToken()]);
78
79
            return true;
80
        } catch (NotFoundException $e) {
81
            throw new InvalidResponseException('API method not found', 0, $e);
82
        } catch (ForbiddenException $e) {
83
            return true;
84
        }
85
    }
86
87
    /**
88
     * Get user subscribers by user login
89
     *
90
     * @return User[]
91
     *
92
     * @throws UserNotFoundException
93
     */
94
    public function getUserSubscribersByLogin(string $login): array
95
    {
96
        $this->logger->debug('Trying to get user subscribers by login', ['login' => $login]);
97
98
        try {
99
            $usersList = $this->getGetJsonData(
100
                self::PREFIX.urlencode($login).'/subscribers',
101
                [],
102
                'array<'.UserDTO::class.'>',
103
                DeserializationContext::create()->setGroups(['user_short'])
104
            );
105
        } catch (NotFoundException $e) {
106
            throw new UserNotFoundException('User not found', 0, $e, null, $login);
107
        }
108
109
        return $this->userFactory->findOrCreateFromDTOArray($usersList);
0 ignored issues
show
Bug introduced by
It seems like $usersList defined by $this->getGetJsonData(se...s(array('user_short'))) on line 99 can also be of type object; however, Skobkin\Bundle\PointTool...dOrCreateFromDTOArray() 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...
110
    }
111
112
    /**
113
     * Get user subscribers by user id
114
     *
115
     * @return User[]
116
     *
117
     * @throws UserNotFoundException
118
     */
119
    public function getUserSubscribersById(int $id): array
120
    {
121
        $this->logger->debug('Trying to get user subscribers by id', ['id' => $id]);
122
123
        try {
124
            $usersList = $this->getGetJsonData(
125
                self::PREFIX.'id/'.$id.'/subscribers',
126
                [],
127
                'array<'.UserDTO::class.'>',
128
                DeserializationContext::create()->setGroups(['user_short'])
129
            );
130
        } catch (NotFoundException $e) {
131
            throw new UserNotFoundException('User not found', 0, $e, $id);
132
        }
133
134
        return $this->userFactory->findOrCreateFromDTOArray($usersList);
0 ignored issues
show
Bug introduced by
It seems like $usersList defined by $this->getGetJsonData(se...s(array('user_short'))) on line 124 can also be of type object; however, Skobkin\Bundle\PointTool...dOrCreateFromDTOArray() 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...
135
    }
136
137
    /**
138
     * Get full user info by login
139
     */
140
    public function getUserByLogin(string $login): User
141
    {
142
        $this->logger->debug('Trying to get user by login', ['login' => $login]);
143
144
        try {
145
            /** @var UserDTO $userInfo */
146
            $userInfo = $this->getGetJsonData(
147
                self::PREFIX.'login/'.urlencode($login),
148
                [],
149
                UserDTO::class,
150
                DeserializationContext::create()->setGroups(['user_full'])
151
            );
152
        } catch (NotFoundException $e) {
153
            throw new UserNotFoundException('User not found', 0, $e, null, $login);
154
        }
155
156
        return $this->userFactory->findOrCreateFromDTO($userInfo);
157
    }
158
159
    /**
160
     * Get full user info by id
161
     */
162
    public function getUserById(int $id): User
163
    {
164
        $this->logger->debug('Trying to get user by id', ['id' => $id]);
165
166
        try {
167
            /** @var UserDTO $userData */
168
            $userData = $this->getGetJsonData(
169
                self::PREFIX.'id/'.$id,
170
                [],
171
                UserDTO::class,
172
                DeserializationContext::create()->setGroups(['user_full'])
173
            );
174
        } catch (NotFoundException $e) {
175
            throw new UserNotFoundException('User not found', 0, $e, $id);
176
        }
177
        // Not catching ForbiddenException right now
178
179
        return $this->userFactory->findOrCreateFromDTO($userData);
180
    }
181
}
182