Telegram   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 131
Duplicated Lines 3.82 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 1
dl 5
loc 131
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A pluginName() 0 4 1
B __construct() 5 31 7
A execute() 0 40 3
A buildMessage() 0 23 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Fabrica\Tools\Plugin;
4
5
use Fabrica\Tools\Builder;
6
use Fabrica\Models\Infra\Ci\Build;
7
use GuzzleHttp\Client;
8
9
/**
10
 * Telegram Plugin
11
 *
12
 * @author LEXASOFT <[email protected]>
13
 */
14
class Telegram extends \PHPCensor\Plugin
15
{
16
    protected $apiKey;
17
    protected $message;
18
    protected $buildMsg;
19
    protected $recipients;
20
    protected $sendLog;
21
22
    /**
23
     * @return string
24
     */
25
    public static function pluginName()
26
    {
27
        return 'telegram';
28
    }
29
30
    /**
31
     * Standard Constructor
32
     *
33
     * @param  Builder $builder
34
     * @param  Build   $build
35
     * @param  array   $options
36
     * @throws \Exception
37
     */
38
    public function __construct(Builder $builder, Build $build, array $options = [])
39
    {
40
        parent::__construct($builder, $build, $options);
41
42
        if (empty($options['api_key'])) {
43
            throw new \Exception("Not setting telegram api_key");
44
        }
45
46
        if (empty($options['recipients'])) {
47
            throw new \Exception("Not setting recipients");
48
        }
49
50
        $this->apiKey  = $options['api_key'];
51
        $this->message = '[%ICON_BUILD%] [%PROJECT_TITLE%](%PROJECT_URI%)' .
52
            ' - [Build #%BUILD%](%BUILD_URI%) has finished ' .
53
            'for commit [%SHORT_COMMIT% (%COMMIT_EMAIL%)](%COMMIT_URI%) ' .
54
            'on branch [%BRANCH%](%BRANCH_URI%)';
55
56
        if (isset($options['message'])) {
57
            $this->message = $options['message'];
58
        }
59
60
        $this->recipients = [];
61 View Code Duplication
        if (is_string($options['recipients'])) {
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...
62
            $this->recipients = [$options['recipients']];
63
        } elseif (is_array($options['recipients'])) {
64
            $this->recipients = $options['recipients'];
65
        }
66
67
        $this->sendLog = isset($options['send_log']) && ((bool) $options['send_log'] !== false);
68
    }
69
70
    /**
71
     * Run Telegram plugin.
72
     *
73
     * @return bool
74
     */
75
    public function execute()
76
    {
77
        $message = $this->buildMessage();
78
        $client  = new Client();
79
        $url     = '/bot'. $this->apiKey . '/sendMessage';
80
81
        foreach ($this->recipients as $chatId) {
82
            $params = [
83
                'chat_id'    => $chatId,
84
                'text'       => $message,
85
                'parse_mode' => 'Markdown',
86
            ];
87
            $client->post(
88
                ('https://api.telegram.org' . $url), [
89
                'headers' => [
90
                    'Content-Type' => 'application/json',
91
                ],
92
                'json' => $params,
93
                ]
94
            );
95
96
            if ($this->sendLog) {
97
                $params = [
98
                    'chat_id'    => $chatId,
99
                    'text'       => $this->buildMsg,
100
                    'parse_mode' => 'Markdown',
101
                ];
102
                $client->post(
103
                    ('https://api.telegram.org' . $url), [
104
                    'headers' => [
105
                        'Content-Type' => 'application/json',
106
                    ],
107
                    'json' => $params,
108
                    ]
109
                );
110
            }
111
        }
112
113
        return true;
114
    }
115
116
    /**
117
     * Build message.
118
     *
119
     * @return string
120
     */
121
    private function buildMessage()
122
    {
123
        $this->buildMsg = '';
124
        $buildIcon      = $this->build->isSuccessful() ? '✅' : '❌';
125
        $buildLog       = $this->build->getLog();
126
        $buildLog       = str_replace(['[0;32m', '[0;31m', '[0m', '/[0m'], '', $buildLog);
127
        $buildMessages  = explode('RUNNING PLUGIN: ', $buildLog);
128
129
        foreach ($buildMessages as $bm) {
130
            $pos      = mb_strpos($bm, "\n");
131
            $firstRow = mb_substr($bm, 0, $pos);
132
133
            //skip long outputs
134
            if (in_array($firstRow, ['slack_notify', 'php_loc', 'telegram'])) {
135
                continue;
136
            }
137
138
            $this->buildMsg .= '*RUNNING PLUGIN: ' . $firstRow . "*\n";
139
            $this->buildMsg .= $firstRow == 'composer' ? '' : ('```' . mb_substr($bm, $pos) . '```');
140
        }
141
142
        return $this->builder->interpolate(str_replace(['%ICON_BUILD%'], [$buildIcon], $this->message));
143
    }
144
}
145