Completed
Push — master ( d7d231...3a9895 )
by Nils
06:20
created

KoalamonReporter   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 226
Duplicated Lines 7.08 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 12
Bugs 3 Features 3
Metric Value
wmc 40
c 12
b 3
f 3
lcom 1
cbo 8
dl 16
loc 226
rs 8.2608

10 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 20 2
A setResponseRetriever() 0 4 1
A getRuleKeys() 0 9 2
A processResult() 0 4 1
A finish() 0 14 3
A getPrefix() 0 4 1
C sendGroupedByPrefix() 3 47 10
D sendSingle() 10 34 9
D sendCollected() 3 35 9
A send() 0 8 2

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like KoalamonReporter often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use KoalamonReporter, and based on these observations, apply Extract Interface, too.

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
151
        foreach ($failureMessages as $key => $failureMessage) {
152
            if ($failureMessage['message'] !== '') {
153
                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...
154
                $this->send($this->identifier . '_' . $key, $failureMessage['system'], $failureMessage['message'] . '</ul>', self::STATUS_FAILURE, '', $counter[$key], $failureMessage['tool']);
155
            } else {
156
                $this->send($this->identifier . '_' . $key, $failureMessage['system'], '', self::STATUS_SUCCESS, '', 0, $failureMessage['tool']);
157
            }
158
        }
159
    }
160
161
162
    private function sendSingle()
163
    {
164
        $rules = $this->getRuleKeys();
165
        foreach ($this->results as $result) {
166
            $failedTests = array();
167
            if ($result->isFailure()) {
168
                foreach ($result->getMessages() as $ruleLKey => $message) {
169
                    $identifier = 'smoke_' . $ruleLKey . '_' . $result->getUrl();
170
171 View Code Duplication
                    if ($this->system === '') {
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...
172
                        $system = str_replace('http://', '', $result->getUrl());
173
                    } else {
174
                        $system = $this->system;
175
                    }
176
                    $this->send($identifier, $system, 'smoke', $message, self::STATUS_FAILURE, (string)$result->getUrl());
177
                    $failedTests[] = $ruleLKey;
178
                }
179
            }
180
            foreach ($rules as $rule) {
181
                if (!in_array($rule, $failedTests, true)) {
182
                    $identifier = 'smoke_' . $rule . '_' . $result->getUrl();
183
184
                    if ($this->systemUseRetriever) {
185
                        $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...
186 View Code Duplication
                    } else if ($this->system === '') {
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...
187
                        $system = str_replace('http://', '', $result->getUrl());
188
                    } else {
189
                        $system = $this->system;
190
                    }
191
                    $this->send($identifier, $system, 'smoke_' . $rule . '_' . $result->getUrl(), self::STATUS_SUCCESS, (string)$result->getUrl());
192
                }
193
            }
194
        }
195
    }
196
197
    private function sendCollected()
198
    {
199
        $failureMessages = array();
200
        $counter = array();
201
202
        foreach ($this->getRuleKeys() as $rule) {
203
            $failureMessages[$rule] = '';
204
            $counter[$rule] = 0;
205
        }
206
207
        foreach ($this->results as $result) {
208
            if ($result->isFailure()) {
209
                foreach ($result->getMessages() as $ruleLKey => $message) {
210
                    $system = $this->system;
211
                    if ($this->systemUseRetriever) {
212
                        $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...
213
                    }
214 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...
215
                        $failureMessages[$ruleLKey]['message'] = '    The smoke test for ' . $system . ' failed (Rule: ' . $ruleLKey . ').<ul>';
216
                    }
217
                    ++$counter[$ruleLKey];
218
                    $failureMessages[$ruleLKey]['message'] .= '<li>' . $message . '(url: ' . $result->getUrl() . ', coming from: ' . $this->retriever->getComingFrom($result->getUrl()) . ')</li>';
219
                    $failureMessages[$ruleLKey]['system'] = $system;
220
                }
221
            }
222
        }
223
224
        foreach ($failureMessages as $key => $failureMessage) {
225
            if ($failureMessage !== '') {
226
                $this->send($this->identifier . '_' . $key, $this->system, $failureMessage['message'] . '</ul>', self::STATUS_FAILURE, '', $counter[$key]);
227
            } else {
228
                $this->send($this->identifier . '_' . $key, $this->system, '', self::STATUS_SUCCESS, '', 0);
229
            }
230
        }
231
    }
232
233
    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...
234
    {
235
        if (is_null($tool)) {
236
            $tool = $this->tool;
237
        }
238
        $event = new Event($identifier, $system, $status, $tool, $message, $value);
239
        $this->reporter->sendEvent($event);
240
    }
241
}
242