Completed
Pull Request — master (#104)
by
unknown
02:33 queued 49s
created

ExceptionListenerTest   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 171
Duplicated Lines 17.54 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 6
dl 30
loc 171
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
B setUp() 0 39 1
A willNotHandleIfNoDocumentUriInAttributes() 0 22 1
A willLogExceptionsWith4xxCodesAsBadRequestNotices() 15 15 2
A willLogExceptionsWith5xxCodesAsRuntimeErrors() 15 15 2
A willLogExceptionsWithUnexpectedCodesAsCriticalErrors() 0 16 2
A setLogger() 0 7 1

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 declare(strict_types = 1);
2
/*
3
 * This file is part of the KleijnWeb\SwaggerBundle package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace KleijnWeb\SwaggerBundle\Tests\EventListener;
10
11
use KleijnWeb\PhpApi\RoutingBundle\Routing\RequestMeta;
12
use KleijnWeb\SwaggerBundle\EventListener\ExceptionListener;
13
use KleijnWeb\SwaggerBundle\EventListener\Response\Error\LogRefBuilderInterface;
14
use KleijnWeb\SwaggerBundle\EventListener\Response\ErrorResponseFactoryInterface;
15
use Psr\Log\LoggerInterface;
16
use Psr\Log\LogLevel;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
19
20
/**
21
 * @author John Kleijn <[email protected]>
22
 */
23
class ExceptionListenerTest extends \PHPUnit_Framework_TestCase
24
{
25
    /**
26
     * @var GetResponseForExceptionEvent
27
     */
28
    private $event;
29
30
    /**
31
     * @var \ReflectionProperty
32
     */
33
    private $codeProperty;
34
35
    /**
36
     * @var \Exception
37
     */
38
    private $exception;
39
40
    /**
41
     * @var Request
42
     */
43
    private $request;
44
45
    /**
46
     * @var LoggerInterface
47
     */
48
    private $logger;
49
50
    /**
51
     * @var ExceptionListener
52
     */
53
    private $exceptionListener;
54
55
    /**
56
     * Set up mocking
57
     */
58
    protected function setUp()
59
    {
60
        $this->event = $this
61
            ->getMockBuilder(GetResponseForExceptionEvent::class)
62
            ->disableOriginalConstructor()
63
            ->setMethods(['getException', 'getRequest', 'setResponse'])
64
            ->getMock();
65
66
        $this->exception    = new \Exception("Mary had a little lamb");
67
        $reflection         = new \ReflectionClass($this->exception);
68
        $codeProperty       = $reflection->getProperty('code');
69
        $this->codeProperty = $codeProperty;
70
        $this->codeProperty->setAccessible(true);
71
        $attributes    = [RequestMeta::ATTRIBUTE_URI => '/foo/bar'];
72
        $this->request = new Request($query = [], $request = [], $attributes);
73
74
        $this->event
75
            ->expects($this->any())
76
            ->method('getException')
77
            ->willReturn($this->exception);
78
79
        $this->event
80
            ->expects($this->any())
81
            ->method('getRequest')
82
            ->willReturn($this->request);
83
84
        /** @var ErrorResponseFactoryInterface $errorResponseFactory */
85
        $errorResponseFactory = $this
86
            ->getMockBuilder(ErrorResponseFactoryInterface::class)
87
            ->disableOriginalConstructor()
88
            ->getMock();
89
90
        /** @var LogRefBuilderInterface $logRefBuilder */
91
        $lofRefBuilderMock = $logRefBuilder = $this->getMockForAbstractClass(LogRefBuilderInterface::class);
92
        $lofRefBuilderMock->expects($this->any())->method('create')->willReturn((string)rand());
93
94
        $this->logger            = $this->getMockForAbstractClass(LoggerInterface::class);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getMockForAbstrac...LoggerInterface::class) of type object<PHPUnit_Framework_MockObject_MockObject> is incompatible with the declared type object<Psr\Log\LoggerInterface> of property $logger.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
95
        $this->exceptionListener = new ExceptionListener($errorResponseFactory, $logRefBuilder, $this->logger);
96
    }
97
98
    /**
99
     * @test
100
     */
101
    public function willNotHandleIfNoDocumentUriInAttributes()
102
    {
103
        $event = $this
104
            ->getMockBuilder(GetResponseForExceptionEvent::class)
105
            ->disableOriginalConstructor()
106
            ->getMock();
107
108
        $event
109
            ->expects($this->any())
110
            ->method('getRequest')
111
            ->willReturn(new Request());
112
113
        $event
114
            ->expects($this->never())
115
            ->method('getException');
116
117
        $event
118
            ->expects($this->never())
119
            ->method('setResponse');
120
121
        $this->exceptionListener->onKernelException($event);
122
    }
123
124
    /**
125
     * @test
126
     */
127 View Code Duplication
    public function willLogExceptionsWith4xxCodesAsBadRequestNotices()
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...
128
    {
129
        for ($i = 0; $i < 99; $i++) {
130
            $logger = $this->getMockForAbstractClass(LoggerInterface::class);
131
            $logger
132
                ->expects($this->once())
133
                ->method('log')
134
                ->with(LogLevel::NOTICE, $this->stringStartsWith('Bad Request'));
135
136
            /** @var LoggerInterface $logger */
137
            $this->setLogger($this->exceptionListener, $logger);
138
            $this->codeProperty->setValue($this->exception, 400 + $i);
139
            $this->exceptionListener->onKernelException($this->event);
140
        }
141
    }
142
143
    /**
144
     * @test
145
     */
146 View Code Duplication
    public function willLogExceptionsWith5xxCodesAsRuntimeErrors()
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...
147
    {
148
        for ($i = 0; $i < 99; $i++) {
149
            $logger = $this->getMockForAbstractClass(LoggerInterface::class);
150
            $logger
151
                ->expects($this->once())
152
                ->method('log')
153
                ->with(LogLevel::ERROR, $this->stringStartsWith('Internal Server Error'));
154
155
            /** @var LoggerInterface $logger */
156
            $this->setLogger($this->exceptionListener, $logger);
157
            $this->codeProperty->setValue($this->exception, 500 + $i);
158
            $this->exceptionListener->onKernelException($this->event);
159
        }
160
    }
161
162
    /**
163
     * @test
164
     */
165
    public function willLogExceptionsWithUnexpectedCodesAsCriticalErrors()
166
    {
167
        $sample = [4096, 777, 22, 5, 0];
168
        foreach ($sample as $code) {
169
            $logger = $this->getMockForAbstractClass(LoggerInterface::class);
170
            $logger
171
                ->expects($this->once())
172
                ->method('log')
173
                ->with(LogLevel::CRITICAL, $this->stringStartsWith('Internal Server Error'));
174
175
            /** @var LoggerInterface $logger */
176
            $this->setLogger($this->exceptionListener, $logger);
177
            $this->codeProperty->setValue($this->exception, $code);
178
            $this->exceptionListener->onKernelException($this->event);
179
        }
180
    }
181
182
    /**
183
     * @param ExceptionListener $exceptionListener
184
     * @param LoggerInterface   $logger
185
     */
186
    private function setLogger(ExceptionListener $exceptionListener, LoggerInterface $logger)
187
    {
188
        $reflection = new \ReflectionObject($exceptionListener);
189
        $property   = $reflection->getProperty('logger');
190
        $property->setAccessible(true);
191
        $property->setValue($exceptionListener, $logger);
192
    }
193
}
194