Client::getAuthHeaders()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 6
ccs 0
cts 0
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Andreshg112\HablameSms;
4
5
use Andreshg112\HablameSms\Exceptions\CouldNotSendNotification;
6
use GuzzleHttp\Client as GuzzleClient;
7
8
class Client
9
{
10
    private const API_URL = 'https://api103.hablame.co/api/';
11
12
    /** Clave API suministrada por Háblame SMS. */
13
    private string $apikey;
14
15
    /** Número del cliente en Háblame SMS. */
16
    private string $account;
17
18
    /** Cliente de Guzzle. */
19
    private GuzzleClient $http;
20
21
    /** Token enviado por correo al cliente desde el panel de Háblame SMS. */
22
    private string $token;
23
24
    /**
25 8
     * Crea una instancia recibiendo el número del cliente, la clave, y el token. Adicionalmente, puede recibir una
26
     * instancia de Guzzle con la que ejecutará las peticiones, útil para pruebas y para especificar un número de
27 8
     * reintentos.
28
     */
29 8
    public function __construct(string $account, string $apikey, string $token, GuzzleClient $http = null)
30
    {
31 8
        $this->account = $account;
32 8
33
        $this->apikey = $apikey;
34
35
        $this->token = $token;
36
37
        $this->http = $http ?? new GuzzleClient();
38
    }
39 1
40
    /**
41 1
     * Consulta el saldo.
42
     * @return array The response body.
43 1
     */
44
    public function checkBalance(): array
45 1
    {
46
        $url = self::API_URL . 'account/v1/status';
47 1
48
        $response = $this->http->get($url, ['headers' => $this->getAuthHeaders()]);
49
50
        return json_decode((string)$response->getBody(), true);
51
    }
52
53
    private function getAuthHeaders(): array
54
    {
55
        return [
56
            'account' => $this->account,
57
            'apikey' => $this->apikey,
58
            'token' => $this->token,
59 1
        ];
60
    }
61
62
    /**
63
     * Envía un mensaje de texto (SMS) al destinatario indicado.
64
     *
65 1
     * @param  string  $phoneNumbers  Número telefonico a enviar SMS.
66
     * @param  string  $sms  Mensaje de texto a enviar.
67
     * @param  string|null  $datetime  [optional] Fecha de envío. Si está vacío, se envía inmediatamente.
68 1
     * @param  bool  $flash  [optional] Indica si es un mensaje flash, es decir, que ocupa la pantalla.
69 1
     * @param  bool  $priority  [optional] Indica si el mensaje es prioritario (costo adicional). Se ignora si se especifican varios destinatarios.
70 1
     * @return array The response body.
71 1
     * @throws \Andreshg112\HablameSms\Exceptions\CouldNotSendNotification
72 1
     */
73 1
    public function sendMessage(
74
        string $phoneNumbers,
75
        string $sms,
76 1
        string $datetime = null,
77
        bool $flash = false,
78 1
        bool $priority = false
79
    ): array {
80
        $arrayNumbers = array_values(array_filter(explode(',', $phoneNumbers)));
81
82
        if (empty($arrayNumbers)) {
83
            throw new CouldNotSendNotification('No phone number has been specified');
84
        }
85
86
        $params = [
87
            'flash' => (int)$flash,
88
            'sendDate' => isset($datetime) ? strtotime($datetime) : null,
89
        ];
90
91
        if (count($arrayNumbers) === 1) {
92
            $params += ['toNumber' => $phoneNumbers, 'sms' => $sms];
93
94
            $url = self::API_URL . 'sms/v3/send/' . ($priority ? 'priority' : 'marketing');
95
        } else {
96
            if ($priority) {
97
                throw new CouldNotSendNotification('Priority SMS can only be sent to one number');
98
            }
99
100
            $params['bulk'] = array_map(function ($phoneNumber) use ($sms) {
101
                return ['numero' => $phoneNumber, 'sms' => $sms];
102
            }, $arrayNumbers);
103
104
            $url = self::API_URL . 'sms/v3/send/marketing/bulk';
105
        }
106
107
        $response = $this->http->post($url, ['headers' => $this->getAuthHeaders(), 'json' => array_filter($params)]);
108
109
        return json_decode((string)$response->getBody(), true);
110
    }
111
}
112