Completed
Push — master ( 7a67a4...253eb0 )
by
unknown
15s
created

Inline::generateShippingOptions()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0072

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.5806
c 0
b 0
f 0
ccs 12
cts 13
cp 0.9231
cc 4
eloc 13
nc 4
nop 1
crap 4.0072
1
<?php
2
3
/*
4
 * This file is part of the PhpBotFramework.
5
 *
6
 * PhpBotFramework is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, version 3.
9
 *
10
 * PhpBotFramework is distributed in the hope that it will be useful, but
11
 * WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace PhpBotFramework\Core;
20
21
use PhpBotFramework\Exceptions\BotException;
22
23
/**
24
 * \class Inline
25
 * \brief All inline API Methods.
26
 */
27
trait Inline
28
{
29
    abstract protected function execRequest(string $url);
30
31
    /** @internal
32
      * \brief Store ID of the callback query received. */
33
    protected $_callback_query_id;
34
35
    /** @internal
36
     * \brief Store ID of the PreCheckout query received. */
37
    protected $_pre_checkout_query_id;
38
39
    /** @internal
40
     * \brief Store ID of the Shipping query received. */
41
    protected $_shipping_query_id;
42
43
    /** @internal
44
      * \brief Store ID of the inline query received. */
45
    protected $_inline_query_id;
46
47
    /**
48
     * \addtogroup Api API Methods
49
     * @{
50
     */
51
52
    /** \brief Answer a callback query.
53
     * \details Remove the 'updating' circle icon on an inline keyboard button showing a message/alert to the user.
54
     * It'll always answer the current callback query. [Api reference](https://core.telegram.org/bots/api#answercallbackquery)
55
     * @param string $text <i>Optional</i>. Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters.
56
     * @param bool $show_alert <i>Optional</i>. If true, an alert will be shown by the client instead of a notification at the top of the chat screen.
57
     * @param string $url <i>Optional</i>. URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.
58
     * Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter.
59
     * @return bool True on success.
60
     */
61
    public function answerCallbackQuery($text = '', $show_alert = false, string $url = '') : bool
62
    {
63
        if (!isset($this->_callback_query_id)) {
64
            throw new BotException("Callback query id not set, wrong update");
65
        }
66
67
        $parameters = [
68
            'callback_query_id' => $this->_callback_query_id,
69
            'text' => $text,
70
            'show_alert' => $show_alert,
71
            'url' => $url
72
        ];
73
74
        return $this->execRequest('answerCallbackQuery?' . http_build_query($parameters));
75
    }
76
77
    /**
78
     * \brief Send an update once the user has confirmed their payment.
79
     * @param bool $ok True is everything is alright, elsewhere False.
80
     * @param string $error The error message if something went wrong.
81
     * @return bool True on success.
82
     */
83 View Code Duplication
    public function answerPreCheckoutQuery(bool $ok = true, string $error = null) {
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...
84
        if (!isset($this->_pre_checkout_query_id)) {
85
            throw new BotException('Callback query ID not set, wrong update');
86
        }
87
88
        $parameters = [
89
            'pre_checkout_query_id' => $this->_pre_checkout_query_id,
90
            'ok' => $ok,
91
            'error_message' => $error
92
        ];
93
94
        return $this->execRequest('answerPreCheckoutQuery?' . http_build_query($parameters));
95
    }
96
97
    /**
98
     * \brief Send an update once the user has confirmed their shipping details.
99
     * @param bool $ok True is everything is alright, elsewhere False.
100
     * @param string $error The error message if something went wrong.
101
     * @param array $shipping_options The various shipping options available.
102
     * For example: array('FedEx' => ['Dispatch' => 15.90, 'Italy Taxes' => 2.50])
103
     * @return bool True on success.
104
     */
105 View Code Duplication
    public function answerShippingQuery(bool $ok = true, string $error = null, array $shipping_options) {
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...
106
        if (!isset($this->_shipping_query_id)) {
107
            throw new BotException('Callback query ID not set, wrong update');
108
        }
109
110
        $parameters = [
111
            'shipping_query_id' => $this->_shipping_query_id,
112
            'ok' => $ok,
113
            'error_message' => $error,
114
            'shipping_options' => $this->generateShippingOptions($shipping_options)
115
        ];
116
117
        return $this->execRequest('answerShippingQuery?' . http_build_query($parameters));
118
    }
119
120
    /**
121
     * \brief Generate shipping options to pass to 'answerShippingQuery'.
122
     * @param array $shipping_options The various shipping options represented like PHP data types.
123
     * @return string A JSON string representation of the shipping options.
124
     */
125 1
    private function generateShippingOptions(array $shipping_options) {
126 1
      $response = [];
127 1
      $option_index = 1;
128
129 1
      foreach ($shipping_options as $option => $prices) {
130 1
        array_push($response, ['id' => strval($option_index), 'title' => $option, 'prices' => []]);
131
132
        // Register prices for the specific shipping option
133 1
        foreach ($prices as $service => $price) {
134 1
          if ($price < 0) {
135
            throw new Exception('Invalid negative price passed to "answerShippingQuery"');
136
          }
137
138 1
          $formatted_price = intval($price * 100);
139
140
          // Selects the most recent shipping option pushed into the array.
141 1
          array_push($response[$option_index - 1]['prices'], [
142 1
            'label' => $service, 'amount' => $formatted_price
143
          ]);
144
        }
145
146 1
        $option_index++;
147
      }
148
149 1
      return json_encode($response);
150
    }
151
152
    /**
153
     * \brief Answer a inline query (when the user write @botusername "Query") with a button, that will make user switch to the
154
     * private chat with the bot, on the top of the results. [Api reference](https://core.telegram.org/bots/api#answerinlinequery)
155
     * @param string $results A JSON-serialized array of results for the inline query. Use PhpBotFramework\Entities\InlineQueryResult class to create and get them.
156
     * @param string $switch_pm_text If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter $switch_pm_parameter.
157
     * @param bool $is_personal Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query.
158
     * @param int $cache_time The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300.
159
     * @return bool True on success.
160
     */
161
    public function answerInlineQuery(string $results = '', string $switch_pm_text = '', $switch_pm_parameter = '', bool $is_personal = true, int $cache_time = 300) : bool
162
    {
163
        if (!isset($this->_inline_query_id)) {
164
            throw new BotException("Inline query id not set, wrong update");
165
        }
166
167
        $parameters = [
168
            'inline_query_id' => $this->_inline_query_id,
169
            'switch_pm_text' => $switch_pm_text,
170
            'is_personal' => $is_personal,
171
            'switch_pm_parameter' => $switch_pm_parameter,
172
            'cache_time' => $cache_time
173
        ];
174
175
        if (isset($results) && $results !== '') {
176
            $parameters['results'] = $results;
177
        }
178
179
        return $this->execRequest('answerInlineQuery?' . http_build_query($parameters));
180
    }
181
182
    /** @} */
183
}
184