Completed
Branch master (1f9106)
by Nils
02:44
created

KoalamonReporter::sendCollected()   D

Complexity

Conditions 10
Paths 66

Size

Total Lines 41
Code Lines 25

Duplication

Lines 3
Ratio 7.32 %

Importance

Changes 7
Bugs 2 Features 0
Metric Value
c 7
b 2
f 0
dl 3
loc 41
rs 4.8196
cc 10
eloc 25
nc 66
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace whm\Smoke\Extensions\SmokeReporter\Reporter;
4
5
use Koalamon\Client\Reporter\Event;
6
use Koalamon\Client\Reporter\Reporter as KoalaReporter;
7
use Symfony\Component\Console\Output\OutputInterface;
8
use whm\Html\Uri;
9
use whm\Smoke\Config\Configuration;
10
use whm\Smoke\Extensions\SmokeResponseRetriever\Retriever\Retriever;
11
use whm\Smoke\Scanner\Result;
12
13
/**
14
 * Class XUnitReporter.
15
 */
16
class KoalamonReporter implements Reporter
17
{
18
    /**
19
     * @var Result[]
20
     */
21
    private $results = [];
22
23
    private $config;
24
    private $system;
25
    private $collect;
26
    private $identifier;
27
    private $systemUseRetriever;
28
    private $tool = 'smoke';
29
    private $groupBy;
30
    private $server;
31
32
    /**
33
     * @var KoalaReporter
34
     */
35
    private $reporter;
36
37
    /*
38
     * @var Retriever
39
     */
40
    private $retriever;
41
42
    private $output;
43
44
    const STATUS_SUCCESS = 'success';
45
    const STATUS_FAILURE = 'failure';
46
47
    public function init($apiKey, Configuration $_configuration, OutputInterface $_output, $server = 'http://www.koalamon.com', $system = '', $identifier = '', $tool = '', $collect = true, $systemUseRetriever = false, $groupBy = false)
48
    {
49
        $httpClient = new \GuzzleHttp\Client();
50
        $this->reporter = new KoalaReporter('', $apiKey, $httpClient, $server);
51
52
        $this->config = $_configuration;
53
        $this->systemUseRetriever = $systemUseRetriever;
54
55
        $this->system = $system;
56
        $this->collect = $collect;
57
        $this->identifier = $identifier;
58
        $this->groupBy = $groupBy;
59
60
        if ($tool) {
61
            $this->tool = $tool;
62
        }
63
64
        $this->server = $server;
65
        $this->output = $_output;
66
    }
67
68
    public function setResponseRetriever(Retriever $retriever)
69
    {
70
        $this->retriever = $retriever;
71
    }
72
73
    /**
74
     * @param Rule [];
75
     *
76
     * @return array
77
     */
78
    private function getRuleKeys()
79
    {
80
        $keys = array();
81
        foreach ($this->config->getRules() as $key => $rule) {
82
            $keys[] = $key;
83
        }
84
85
        return $keys;
86
    }
87
88
    public function processResult(Result $result)
89
    {
90
        $this->results[] = $result;
91
    }
92
93
    public function finish()
94
    {
95
        $this->output->writeln('Sending results to ' . $this->server . " ... \n");
96
97
        if ($this->groupBy === 'prefix') {
98
            $this->sendGroupedByPrefix();
99
        } else {
100
            if ($this->collect) {
101
                $this->sendCollected();
102
            } else {
103
                $this->sendSingle();
104
            }
105
        }
106
    }
107
108
    private function getPrefix($string)
109
    {
110
        return substr($string, 0, strpos($string, '_'));
111
    }
112
113
    private function sendGroupedByPrefix()
114
    {
115
        $failureMessages = array();
116
        $counter = array();
117
118
        if ($this->systemUseRetriever) {
119
            $systems = $this->retriever->getSystems();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface whm\Smoke\Extensions\Smo...ver\Retriever\Retriever as the method getSystems() does only exist in the following implementations of said interface: whm\Smoke\Extensions\Smo...ever\Koalamon\Retriever, whm\Smoke\Extensions\Smo...ListRetriever\Retriever.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
120
        } else {
121
            $systems = array($this->system);
122
        }
123
124
        foreach ($this->getRuleKeys() as $rule) {
125
            foreach ($systems as $system) {
126
                $identifier = $this->tool . '_' . $this->getPrefix($rule) . '_' . $system;
127
                $failureMessages[$identifier]['message'] = '';
128
                $failureMessages[$identifier]['system'] = $system;
129
                $failureMessages[$identifier]['tool'] = $this->getPrefix($rule);
130
131
                $counter[$identifier] = 0;
132
            }
133
        }
134
135
        foreach ($this->results as $result) {
136
            if ($result->isFailure()) {
137
                foreach ($result->getMessages() as $ruleLKey => $message) {
138
                    $system = $this->system;
139
                    if ($this->systemUseRetriever) {
140
                        $system = $this->retriever->getSystem(($result->getUrl()));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface whm\Smoke\Extensions\Smo...ver\Retriever\Retriever as the method getSystem() does only exist in the following implementations of said interface: whm\Smoke\Extensions\Smo...ListRetriever\Retriever.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
141
                    }
142
143
                    $identifer = $this->tool . '_' . $this->getPrefix($ruleLKey) . '_' . $system;
144
145 View Code Duplication
                    if ($failureMessages[$identifer]['message'] === '') {
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...
146
                        $failureMessages[$identifer]['message'] = 'The ' . $this->getPrefix($ruleLKey) . ' test for ' . $system . ' failed.<ul>';
147
                    }
148
                    ++$counter[$identifer];
149
                    $failureMessages[$identifer]['message'] .= '<li>' . $message . '<br>url: ' . $result->getUrl() . ', coming from: ' . $this->retriever->getComingFrom($result->getUrl()) . '</li>';
150
                }
151
            }
152
        }
153
154
        foreach ($failureMessages as $key => $failureMessage) {
155
            if ($failureMessage['message'] !== '') {
156
                $this->send($this->identifier . '_' . $key, $failureMessage['system'], $failureMessage['message'] . '</ul>', self::STATUS_FAILURE, '', $counter[$key], $failureMessage['tool']);
157
            } else {
158
                $this->send($this->identifier . '_' . $key, $failureMessage['system'], '', self::STATUS_SUCCESS, '', 0, $failureMessage['tool']);
159
            }
160
        }
161
    }
162
163
    private function sendSingle()
164
    {
165
        $rules = $this->getRuleKeys();
166
        foreach ($this->results as $result) {
167
            $failedTests = array();
168
            if ($result->isFailure()) {
169
                foreach ($result->getMessages() as $ruleLKey => $message) {
170
                    $identifier = 'smoke_' . $ruleLKey . '_' . $result->getUrl();
171
172
                    if ($this->system === '') {
173
                        $system = str_replace('http://', '', $result->getUrl());
174
                    } else {
175
                        $system = $this->system;
176
                    }
177
                    $this->send($identifier, $system, 'smoke', $message, self::STATUS_FAILURE, (string) $result->getUrl());
178
                    $failedTests[] = $ruleLKey;
179
                }
180
            }
181
            foreach ($rules as $rule) {
182
                if (!in_array($rule, $failedTests, true)) {
183
                    $identifier = 'smoke_' . $rule . '_' . $result->getUrl();
184
185
                    if ($this->systemUseRetriever) {
186
                        $system = $this->retriever->getSystem($result->getUrl());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface whm\Smoke\Extensions\Smo...ver\Retriever\Retriever as the method getSystem() does only exist in the following implementations of said interface: whm\Smoke\Extensions\Smo...ListRetriever\Retriever.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
187
                    } elseif ($this->system === '') {
188
                        $system = str_replace('http://', '', $result->getUrl());
189
                    } else {
190
                        $system = $this->system;
191
                    }
192
                    $this->send($identifier, $system, 'smoke_' . $rule . '_' . $result->getUrl(), self::STATUS_SUCCESS, (string) $result->getUrl());
193
                }
194
            }
195
        }
196
    }
197
198
    private function sendCollected()
199
    {
200
        $failureMessages = array();
201
        $counter = array();
202
203
        foreach ($this->getRuleKeys() as $rule) {
204
            $failureMessages[$rule] = '';
205
            $counter[$rule] = 0;
206
        }
207
208
        foreach ($this->results as $result) {
209
            if ($result->isFailure()) {
210
                foreach ($result->getMessages() as $ruleLKey => $message) {
211
                    $system = $this->system;
212
                    if ($this->systemUseRetriever) {
213
                        $system = $this->retriever->getSystem(new Uri($result->getUrl()));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface whm\Smoke\Extensions\Smo...ver\Retriever\Retriever as the method getSystem() does only exist in the following implementations of said interface: whm\Smoke\Extensions\Smo...ListRetriever\Retriever.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
214
                    }
215 View Code Duplication
                    if ($failureMessages[$ruleLKey] === '') {
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...
216
                        $failureMessages[$ruleLKey]['message'] = '    The smoke test for ' . $system . ' failed (Rule: ' . $ruleLKey . ').<ul>';
217
                    }
218
                    ++$counter[$ruleLKey];
219
220
                    $comingFrom = '';
221
                    if ($this->retriever->getComingFrom($result->getUrl())) {
222
                        $comingFrom = ', coming from: ' . $this->retriever->getComingFrom($result->getUrl());
223
                    }
224
225
                    $failureMessages[$ruleLKey]['message'] .= '<li>' . $message . ' (url: ' . $result->getUrl() . $comingFrom . ')</li > ';
226
                    $failureMessages[$ruleLKey]['system'] = $system;
227
                }
228
            }
229
        }
230
231
        foreach ($failureMessages as $key => $failureMessage) {
232
            if ($failureMessage !== '') {
233
                $this->send($this->identifier . '_' . $key, $this->system, $failureMessage['message'] . ' </ul > ', self::STATUS_FAILURE, '', $counter[$key]);
234
            } else {
235
                $this->send($this->identifier . '_' . $key, $this->system, '', self::STATUS_SUCCESS, '', 0);
236
            }
237
        }
238
    }
239
240
    private function send($identifier, $system, $message, $status, $url = '', $value = 0, $tool = null)
0 ignored issues
show
Unused Code introduced by
The parameter $url is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
241
    {
242
        if (is_null($tool)) {
243
            $tool = $this->tool;
244
        }
245
        $event = new Event($identifier, $system, $status, $tool, $message, $value);
246
        $this->reporter->sendEvent($event);
247
    }
248
}
249