Completed
Push — master ( 3a9895...c027ea )
by Nils
02:42
created

KoalamonReporter::sendGroupedByPrefix()   D

Complexity

Conditions 10
Paths 63

Size

Total Lines 46
Code Lines 28

Duplication

Lines 3
Ratio 6.52 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 3
loc 46
rs 4.983
cc 10
eloc 28
nc 63
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
        $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...
119
120
        foreach ($this->getRuleKeys() as $rule) {
121
            foreach ($systems as $system) {
122
                $identifer = $this->tool . '_' . $this->getPrefix($rule) . '_' . $system;
123
                $failureMessages[$identifer]['message'] = '';
124
                $failureMessages[$identifer]['system'] = $system;
125
                $failureMessages[$identifer]['tool'] = $this->getPrefix($rule);
126
127
                $counter[$identifer] = 0;
128
            }
129
        }
130
131
        foreach ($this->results as $result) {
132
            if ($result->isFailure()) {
133
                foreach ($result->getMessages() as $ruleLKey => $message) {
134
                    $system = $this->system;
135
                    if ($this->systemUseRetriever) {
136
                        $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...
137
                    }
138
139
                    $identifer = $this->tool . '_' . $this->getPrefix($ruleLKey) . '_' . $system;
140
141 View Code Duplication
                    if ($failureMessages[$identifer] === '') {
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...
142
                        $failureMessages[$identifer]['message'] = '    The smoke test for ' . $system . ' failed (Rule: ' . $ruleLKey . ').<ul>';
143
                    }
144
                    ++$counter[$ruleLKey];
145
                    $failureMessages[$identifer]['message'] .= '<li>' . $message . '(url: ' . $result->getUrl() . ', coming from: ' . $this->retriever->getComingFrom($result->getUrl()) . ')</li>';
146
                }
147
            }
148
        }
149
150
        foreach ($failureMessages as $key => $failureMessage) {
151
            if ($failureMessage['message'] !== '') {
152
                var_dump('fehler');
0 ignored issues
show
Security Debugging Code introduced by
var_dump('fehler'); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
153
                $this->send($this->identifier . '_' . $key, $failureMessage['system'], $failureMessage['message'] . '</ul>', self::STATUS_FAILURE, '', $counter[$key], $failureMessage['tool']);
154
            } else {
155
                $this->send($this->identifier . '_' . $key, $failureMessage['system'], '', self::STATUS_SUCCESS, '', 0, $failureMessage['tool']);
156
            }
157
        }
158
    }
159
160
    private function sendSingle()
161
    {
162
        $rules = $this->getRuleKeys();
163
        foreach ($this->results as $result) {
164
            $failedTests = array();
165
            if ($result->isFailure()) {
166
                foreach ($result->getMessages() as $ruleLKey => $message) {
167
                    $identifier = 'smoke_' . $ruleLKey . '_' . $result->getUrl();
168
169
                    if ($this->system === '') {
170
                        $system = str_replace('http://', '', $result->getUrl());
171
                    } else {
172
                        $system = $this->system;
173
                    }
174
                    $this->send($identifier, $system, 'smoke', $message, self::STATUS_FAILURE, (string) $result->getUrl());
175
                    $failedTests[] = $ruleLKey;
176
                }
177
            }
178
            foreach ($rules as $rule) {
179
                if (!in_array($rule, $failedTests, true)) {
180
                    $identifier = 'smoke_' . $rule . '_' . $result->getUrl();
181
182
                    if ($this->systemUseRetriever) {
183
                        $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...
184
                    } elseif ($this->system === '') {
185
                        $system = str_replace('http://', '', $result->getUrl());
186
                    } else {
187
                        $system = $this->system;
188
                    }
189
                    $this->send($identifier, $system, 'smoke_' . $rule . '_' . $result->getUrl(), self::STATUS_SUCCESS, (string) $result->getUrl());
190
                }
191
            }
192
        }
193
    }
194
195
    private function sendCollected()
196
    {
197
        $failureMessages = array();
198
        $counter = array();
199
200
        foreach ($this->getRuleKeys() as $rule) {
201
            $failureMessages[$rule] = '';
202
            $counter[$rule] = 0;
203
        }
204
205
        foreach ($this->results as $result) {
206
            if ($result->isFailure()) {
207
                foreach ($result->getMessages() as $ruleLKey => $message) {
208
                    $system = $this->system;
209
                    if ($this->systemUseRetriever) {
210
                        $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...
211
                    }
212 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...
213
                        $failureMessages[$ruleLKey]['message'] = '    The smoke test for ' . $system . ' failed (Rule: ' . $ruleLKey . ').<ul>';
214
                    }
215
                    ++$counter[$ruleLKey];
216
                    $failureMessages[$ruleLKey]['message'] .= '<li>' . $message . '(url: ' . $result->getUrl() . ', coming from: ' . $this->retriever->getComingFrom($result->getUrl()) . ')</li>';
217
                    $failureMessages[$ruleLKey]['system'] = $system;
218
                }
219
            }
220
        }
221
222
        foreach ($failureMessages as $key => $failureMessage) {
223
            if ($failureMessage !== '') {
224
                $this->send($this->identifier . '_' . $key, $this->system, $failureMessage['message'] . '</ul>', self::STATUS_FAILURE, '', $counter[$key]);
225
            } else {
226
                $this->send($this->identifier . '_' . $key, $this->system, '', self::STATUS_SUCCESS, '', 0);
227
            }
228
        }
229
    }
230
231
    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...
232
    {
233
        if (is_null($tool)) {
234
            $tool = $this->tool;
235
        }
236
        $event = new Event($identifier, $system, $status, $tool, $message, $value);
237
        $this->reporter->sendEvent($event);
238
    }
239
}
240