RestApi::parsePunches()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
1
<?php
2
3
namespace Katapoka\Ahgora;
4
5
use Katapoka\Ahgora\Contracts\IHttpClient;
6
use Mockery\Exception;
7
8
class RestApi extends AbstractApi
9
{
10
    /**
11
     * The API base url.
12
     */
13
    const API_BASE_URL = 'https://www.ahgora.com.br/externo';
14
15
    /**
16
     * The endpoint to get the punches.
17
     */
18
    const ENDPOINT_APURACAO = '%s/getApuracao';
19
20
    /**
21
     * The company id.
22
     * string @var
23
     */
24
    private $companyId;
25
26
    /**
27
     * The account username.
28
     * string @var
29
     */
30
    private $username;
31
32
    /**
33
     * The account password.
34
     * @var
35
     */
36
    private $password;
37
38
    /**
39
     * @var \Katapoka\Ahgora\Contracts\IHttpClient
40
     */
41
    private $httpClient;
42
43
    /**
44
     * Api constructor.
45
     *
46
     * @param IHttpClient $httpClient
47
     */
48
    public function __construct(IHttpClient $httpClient)
49
    {
50
        $this->httpClient = $httpClient;
51
    }
52
53
    /**
54
     * Set the company id of the ahgora system.
55
     *
56
     * @param string $companyId
57
     *
58
     * @return $this
59
     */
60
    public function setCompanyId($companyId)
61
    {
62
        $this->companyId = $companyId;
63
64
        return $this;
65
    }
66
67
    /**
68
     * Set the username of the employee, from the company set at the setCompanyId.
69
     *
70
     * @param string $username
71
     *
72
     * @return $this
73
     */
74
    public function setUsername($username)
75
    {
76
        $this->username = $username;
77
78
        return $this;
79
    }
80
81
    /**
82
     * Set the password of the employee, from the company set at the setCompanyId.
83
     *
84
     * @param string $password
85
     *
86
     * @return $this
87
     */
88
    public function setPassword($password)
89
    {
90
        $this->password = $password;
91
92
        return $this;
93
    }
94
95
    /**
96
     * Try to execute the login on the page.
97
     * To execute some actions the user needs to be loggedin.
98
     * After a successful login, the status loggedin is saved as true.
99
     *
100
     * @return bool Returns true if the login was successful and false otherwise
101
     */
102
    public function doLogin()
103
    {
104
        $params = [
105
            'company'   => $this->companyId,
106
            'matricula' => $this->username,
107
            'senha'     => $this->password,
108
            'mes'       => date('m'),
109
            'ano'       => date('Y'),
110
        ];
111
        try {
112
            $response = $this->httpClient->post($this->buildUrl(static::ENDPOINT_APURACAO), $params)->json();
0 ignored issues
show
Documentation introduced by
$this->buildUrl(static::ENDPOINT_APURACAO) is of type object<PHPUnit_Framework...t_Matcher_InvokedCount>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
113
114
            return isset($response->empresa->empresa) && $response->empresa->empresa === $this->companyId;
115
        } catch (Exception $e) {
116
            $this->error($e->getMessage(), $params);
117
            return false;
118
        }
119
    }
120
121
    /**
122
     * Get the punches at the given parameters.
123
     *
124
     * @param int|null $month The month you want to get the punches - Must be between 01 and 12 (both included)
125
     * @param int|null $year  The year you want to get the punches
126
     *
127
     * @return array
128
     */
129
    public function getPunches($month = null, $year = null)
130
    {
131
        $params = [
132
            'company'   => $this->companyId,
133
            'matricula' => $this->username,
134
            'senha'     => $this->password,
135
            'mes'       => str_pad($month, 2, '0', STR_PAD_LEFT),
136
            'ano'       => $year,
137
        ];
138
        try {
139
            $response = $this->httpClient->post($this->buildUrl(static::ENDPOINT_APURACAO), $params)->json();
0 ignored issues
show
Documentation introduced by
$this->buildUrl(static::ENDPOINT_APURACAO) is of type object<PHPUnit_Framework...t_Matcher_InvokedCount>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
140
            if (isset($response->error)) {
141
                throw new \BadMethodCallException($response->error);
142
            }
143
144
            return [
145
                'punches' => $this->parsePunches($response->dias),
146
                'extra'   => $this->parseExtra($response->dias),
147
            ];
148
        } catch (Exception $e) {
149
            $this->error($e->getMessage(), $params);
150
151
            return [];
152
        }
153
    }
154
155
    /**
156
     * Get the punches from some given day.
157
     *
158
     * @param int $day
159
     * @param int $month
160
     * @param int $year
161
     *
162
     * @return mixed
163
     */
164 View Code Duplication
    public function getPunchesFromDay($day, $month, $year)
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...
165
    {
166
        $date = date("Y-m-d", mktime(0, 0, 0, $month, $day, $year));
167
        list($year, $month, $day) = explode('-', $date);
168
169
        if ($day > 19) {
170
            $month++;
171
        }
172
173
        if ($month > 12) {
174
            $month = 1;
175
            $year++;
176
        }
177
        $punches = $this->getPunches($month, $year);
178
179
        return array_filter($punches['punches'], function (\DateTime $punchDateTime) use ($day) {
180
            return (int) $punchDateTime->format('d') === (int) $day;
181
        });
182
    }
183
184
    /**
185
     * Gets the employee name.
186
     *
187
     * @return string
188
     */
189
    public function getEmployeeName()
190
    {
191
        return $this->getEmployeeData('nome');
192
    }
193
194
    /**
195
     * Gets the employer name.
196
     *
197
     * @return string
198
     */
199
    public function getEmployeeRole()
200
    {
201
        return $this->getEmployeeData('cargo');
202
    }
203
204
    /**
205
     * Get the employer department.
206
     *
207
     * @return string
208
     */
209
    public function getDepartment()
210
    {
211
        return $this->getEmployeeData('departamento');
212
    }
213
214
    /**
215
     * Gets the user data and punches.
216
     *
217
     * @param null $field
218
     *
219
     * @return mixed
220
     */
221
    private function getEmployeeData($field = null)
222
    {
223
        if (!empty($field) && property_exists($this->getData()->funcionario, $field)) {
224
            return $this->getData()->funcionario->{$field};
225
        }
226
227
        return $this->getData()->funcionario;
228
    }
229
230
    /**
231
     * Gets all the data and punches. Cached method.
232
     *
233
     * @return mixed
234
     */
235
    private function getData() {
236
        return once(function () {
237
            $params = [
238
                'company'   => $this->companyId,
239
                'matricula' => $this->username,
240
                'senha'     => $this->password,
241
                'mes'       => date('m'),
242
                'ano'       => date('Y'),
243
            ];
244
            $response = $this->httpClient->post($this->buildUrl(static::ENDPOINT_APURACAO), $params)->json();
0 ignored issues
show
Documentation introduced by
$this->buildUrl(static::ENDPOINT_APURACAO) is of type object<PHPUnit_Framework...t_Matcher_InvokedCount>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
245
            if (isset($response->error)) {
246
                throw new \BadMethodCallException($response->error);
247
            }
248
249
            return $response;
250
        });
251
    }
252
253
    private function buildUrl($endpoint, array $params = []) {
254
        return once(function () use ($endpoint, $params) {
255
            return vsprintf($endpoint, array_merge([static::API_BASE_URL], $params));
256
        });
257
    }
258
259
    private function parsePunches($dias)
260
    {
261
        $tmp = [];
262
263
        foreach ($dias as $dia => $diaConfig) {
264
            foreach ($diaConfig->batidas as $batida) {
265
                $hora = substr($batida->hora, 0, 2);
266
                $minuto = substr($batida->hora, 2, 2);
267
                $tmp[] = new \DateTime(sprintf('%s %s:%s:00', $dia, $hora, $minuto));
268
            }
269
        }
270
271
        return $tmp;
272
    }
273
274
    private function parseExtra($dias)
275
    {
276
        $tmp = [];
277
278
        foreach ($dias as $dia => $dadosDia) {
279
            // Parse falta
280
            $falta = array_filter($dadosDia->resultado, function ($item) { return $item->tipo == 'FALTA'; });
281
282
            // Parse extra
283
            $extra = array_filter($dadosDia->resultado, function ($item) { return $item->tipo == 'Extra'; });
284
285
            $tmp[$dia][] = [
286
                'falta' => empty($falta) ? '00:00' : preg_replace('/^(-)?(\d{2})(\d{2})$/i', '\1\2:\3', array_shift($falta)->valor),
287
                'extra' => empty($extra) ? '00:00' : preg_replace('/^(-)?(\d{2})(\d{2})$/i', '\1\2:\3', array_shift($extra)->valor),
288
            ];
289
        }
290
291
        return $tmp;
292
    }
293
294
}
295