Completed
Push — master ( c8ecd7...a2fca0 )
by William Johnson S.
02:27
created

HttpApi::setUsername()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 7
ccs 0
cts 4
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Katapoka\Ahgora;
4
5
use InvalidArgumentException;
6
use Katapoka\Ahgora\Contracts\IAhgoraApi;
7
use Katapoka\Ahgora\Contracts\IHttpClient;
8
use Katapoka\Ahgora\Contracts\IHttpResponse;
9
10
/**
11
 * Class responsible for getting the data from the Ahgora system.
12
 */
13
class HttpApi implements IAhgoraApi
14
{
15
    use Loggable;
16
17
    const AHGORA_BASE_URL = 'https://www.ahgora.com.br';
18
    const AHGORA_COMPANY_URL = '%s/externo/index/%s';
19
    const AHGORA_LOGIN_URL = '%s/externo/login';
20
21
    /** @var \Katapoka\Ahgora\Contracts\IHttpClient */
22
    private $httpClient;
23
    /** @var string */
24
    private $password;
25
    /** @var string */
26
    private $companyId;
27
    /** @var string */
28
    private $username;
29
    /** @var bool */
30
    private $loggedIn = false;
31
32
    /**
33
     * Api constructor.
34
     *
35
     * @param IHttpClient $httpClient
36
     */
37 1
    public function __construct(IHttpClient $httpClient)
38
    {
39 1
        $this->httpClient = $httpClient;
40 1
        $this->debug('Api instance created');
41 1
    }
42
43
    /**
44
     * Set the company id of the ahgora system.
45
     *
46
     * @param string $companyId
47
     *
48
     * @return $this
49
     */
50
    public function setCompanyId($companyId)
51
    {
52
        $this->companyId = $companyId;
53
        $this->debug('Company ID set', ['company_id' => $companyId]);
54
55
        return $this;
56
    }
57
58
    /**
59
     * Set the username of the employee, from the company set at the setCompanyId.
60
     *
61
     * @param string $username
62
     *
63
     * @return $this
64
     */
65
    public function setUsername($username)
66
    {
67
        $this->username = $username;
68
        $this->debug('Username set', ['username' => $username]);
69
70
        return $this;
71
    }
72
73
    /**
74
     * Set the password of the employee, from the company set at the setCompanyId.
75
     *
76
     * @param string $password
77
     *
78
     * @return $this
79
     */
80
    public function setPassword($password)
81
    {
82
        $this->password = $password;
83
        $this->debug('Password set', ['password' => $password]);
84
85
        return $this;
86
    }
87
88
    /**
89
     * Try to execute the login on the page.
90
     * To execute some actions the user needs to be loggedin.
91
     * After a successful login, the status loggedin is saved as true.
92
     *
93
     * @return bool Returns true if the login was successful and false otherwise
94
     */
95
    public function doLogin()
96
    {
97
        $hasLoggedIn = false;
98
        $this->debug('Started login proccess');
99
100
101
        $accessEnabled = $this->checkAccessEnabled();
102
103
        if ($accessEnabled) {
104
            $response = $this->executeLogin();
105
            $hasLoggedIn = $this->checkLoginStatus($response);
106
        }
107
108
        $this->debug($accessEnabled ? "Company has external access enabled" : "Company hasn't external access enabled");
109
110
        $this->setLoggedIn($hasLoggedIn);
111
112
        return $hasLoggedIn;
113
    }
114
115
    /**
116
     * Execute the login on the server and returns the server response.
117
     *
118
     * @return IHttpResponse
119
     */
120
    private function executeLogin()
121
    {
122
        return $this->httpClient->post($this->loginUrl(), [
123
            'empresa'   => $this->companyId,
124
            'matricula' => $this->username,
125
            'senha'     => $this->password,
126
        ]);
127
    }
128
129
    /**
130
     * Check if the company has external access on the Ahgora system.
131
     *
132
     * @return bool
133
     */
134
    private function checkAccessEnabled()
135
    {
136
        $response = $this->httpClient->get($this->companyUrl());
137
138
        return stripos($response->getBody(), 'Sua Empresa não liberou o acesso a essa ferramenta') === false;
139
    }
140
141
    /**
142
     * Check the return of the login action.
143
     * How it works: If statusCode 200 and no body, login ok, otherwise, login failed.
144
     * Should return a json with property "r" with "error" and "text" with the message
145
     *
146
     * @param IHttpResponse $response
147
     *
148
     * @return bool
149
     */
150
    private function checkLoginStatus(IHttpResponse $response)
151
    {
152
        try {
153
            if ($response->getHttpStatus() === IHttpClient::HTTP_STATUS_OK) {
154
                $json = $this->safeJsonDecode($response->getBody(), true);
155
                if ($json['r'] === 'success') {
156
                    return true;
157
                }
158
            }
159
        } catch (InvalidArgumentException $iaex) {
160
            $this->error($iaex->getMessage(), ['expcetion' => $iaex]);
161
        }
162
163
        return false;
164
    }
165
166
    /**
167
     * Safely decodes a json.
168
     *
169
     * @param string $string
170
     * @param bool   $asArray
171
     *
172
     * @throws InvalidArgumentException
173
     *
174
     * @return mixed
175
     */
176
    private function safeJsonDecode($string, $asArray = false)
177
    {
178
        $json = json_decode($string, $asArray);
179
        if (json_last_error() !== JSON_ERROR_NONE) {
180
            $this->debug('Failed to debug json', ['str' => $string]);
181
            throw new InvalidArgumentException('Failed to decode json');
182
        } else {
183
            return $json;
184
        }
185
    }
186
187
    /**
188
     * Safely set if the user is loggedin or not.
189
     * Did a separate method do eventually trigger events, if necessary.
190
     *
191
     * @param bool $loggedIn
192
     *
193
     * @return $this
194
     */
195
    private function setLoggedIn($loggedIn = true)
196
    {
197
        if (!is_bool($loggedIn)) {
198
            throw new InvalidArgumentException('LoggedIn parameter must be boolean');
199
        }
200
201
        $this->debug('setLoggedIn', ['logged_in' => $loggedIn]);
202
        $this->loggedIn = $loggedIn;
203
204
        return $this;
205
    }
206
207
    /**
208
     * Build the company url string.
209
     *
210
     * @return string
211
     */
212
    private function companyUrl()
213
    {
214
        $companyUrl = sprintf(self::AHGORA_COMPANY_URL, self::AHGORA_BASE_URL, $this->companyId);
215
        $this->debug('CompanyURL', ['company_url' => $companyUrl]);
216
217
        return $companyUrl;
218
    }
219
220
    /**
221
     * Build the login url.
222
     *
223
     * @return string
224
     */
225
    private function loginUrl()
226
    {
227
        $loginUrl = sprintf(self::AHGORA_LOGIN_URL, self::AHGORA_BASE_URL);
228
        $this->debug('loginUrl', ['login_url' => $loginUrl]);
229
230
        return $loginUrl;
231
    }
232
233
    /**
234
     * Get the punchs at the given parameters.
235
     *
236
     * @param int|null $month The month you want to get the punchs - Must be between 01 and 12 (both included)
237
     * @param int|null $year  The year you want to get the punchs
238
     *
239
     * @return array
240
     */
241
    public function getPunchs($month = null, $year = null)
242
    {
243
        return [];
244
    }
245
246
    /**
247
     * Gets the employer name.
248
     *
249
     * @return string
250
     */
251
    public function getEmployeeRole()
252
    {
253
        return "NOT IMPLEMENTED YET";
254
    }
255
256
    /**
257
     * Get the employer department.
258
     *
259
     * @return string
260
     */
261
    public function getDepartment()
262
    {
263
        return "NOT IMPLEMENTED YET";
264
    }
265
}
266