GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Test Setup Failed
Push — master ( 9d889d...27a869 )
by Carlos
02:09
created

RongcloudGateway::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
/*
4
 * This file is part of the overtrue/easy-sms.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Overtrue\EasySms\Gateways;
13
14
use GuzzleHttp\Exception\ClientException;
15
use Overtrue\EasySms\Contracts\MessageInterface;
16
use Overtrue\EasySms\Contracts\PhoneNumberInterface;
17
use Overtrue\EasySms\Exceptions\GatewayErrorException;
18
use Overtrue\EasySms\Support\Config;
19
use Overtrue\EasySms\Traits\HasHttpRequest;
20
21
/**
22
 * Class RongcloudGateway.
23
 *
24
 * @author Darren Gao <[email protected]>
25
 *
26
 * @see http://www.rongcloud.cn/docs/sms_service.html#send_sms_code
27
 */
28
class RongcloudGateway extends Gateway
29
{
30
    use HasHttpRequest;
31
32
    const ENDPOINT_TEMPLATE = 'http://api.sms.ronghub.com/%s.%s';
33
34
    const ENDPOINT_ACTION = 'sendCode';
35
36
    const ENDPOINT_FORMAT = 'json';
37
38
    const ENDPOINT_REGION = '86';  // 中国区,目前只支持此国别
39
40
    const SUCCESS_CODE = 200;
41
42
    /**
43
     * @param \Overtrue\EasySms\Contracts\PhoneNumberInterface $to
44
     * @param \Overtrue\EasySms\Contracts\MessageInterface     $message
45
     * @param \Overtrue\EasySms\Support\Config                 $config
46
     *
47
     * @return array
48
     *
49
     * @throws \Overtrue\EasySms\Exceptions\GatewayErrorException ;
50
     */
51
    public function send(PhoneNumberInterface $to, MessageInterface $message, Config $config)
52
    {
53
        $data = $message->getData();
54
        $action = array_key_exists('action', $data) ? $data['action'] : self::ENDPOINT_ACTION;
55
        $endpoint = $this->buildEndpoint($action);
56
57
        $headers = [
58
            'Nonce' => uniqid(),
59
            'App-Key' => $config->get('app_key'),
60
            'Timestamp' => time(),
61
        ];
62
        $headers['Signature'] = $this->generateSign($headers, $config);
63
64
        switch ($action) {
65
            case 'sendCode':
66
                $params = [
67
                    'mobile' => $to->getNumber(),
68
                    'region' => self::ENDPOINT_REGION,
69
                    'templateId' => $message->getTemplate($this),
70
                ];
71
72
                break;
73
            case 'verifyCode':
74
                if (!array_key_exists('code', $data)
75
                    or !array_key_exists('sessionId', $data)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
76
                    throw new GatewayErrorException('"code" or "sessionId" is not set', 0);
77
                }
78
                $params = [
79
                    'code' => $data['code'],
80
                    'sessionId' => $data['sessionId'],
81
                ];
82
83
                break;
84
            case 'sendNotify':
85
                $params = [
86
                    'mobile' => $to->getNumber(),
87
                    'region' => self::ENDPOINT_REGION,
88
                    'templateId' => $message->getTemplate($this),
89
                    ];
90
                $params = array_merge($params, $data);
91
92
                break;
93
            default:
94
                throw new GatewayErrorException(sprintf('action: %s not supported', $action));
0 ignored issues
show
Bug introduced by
The call to GatewayErrorException::__construct() misses a required argument $code.

This check looks for function calls that miss required arguments.

Loading history...
95
        }
96
97
        try {
98
            $result = $this->post($endpoint, $params, $headers);
99
100 View Code Duplication
            if (self::SUCCESS_CODE !== $result['code']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
101
                throw new GatewayErrorException($result['errorMessage'], $result['code'], $result);
102
            }
103
        } catch (ClientException $e) {
104
            throw new GatewayErrorException($e->getMessage(), $e->getCode());
105
        }
106
107
        return $result;
108
    }
109
110
    /**
111
     * Generate Sign.
112
     *
113
     * @param array                            $params
114
     * @param \Overtrue\EasySms\Support\Config $config
115
     *
116
     * @return string
117
     */
118
    protected function generateSign($params, Config $config)
119
    {
120
        return sha1(sprintf('%s%s%s', $config->get('app_secret'), $params['Nonce'], $params['Timestamp']));
121
    }
122
123
    /**
124
     * Build endpoint url.
125
     *
126
     * @param string $action
127
     *
128
     * @return string
129
     */
130
    protected function buildEndpoint($action)
131
    {
132
        return sprintf(self::ENDPOINT_TEMPLATE, $action, self::ENDPOINT_FORMAT);
133
    }
134
}
135