Test Setup Failed
Push — master ( e2ccdd...da0315 )
by Gerrit
09:14
created

DefaultControllerHelperTest   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 311
Duplicated Lines 23.79 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 5
dl 74
loc 311
rs 10
c 0
b 0
f 0

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
 * Copyright (C) 2017  Gerrit Addiks.
4
 * This package (including this file) was released under the terms of the GPL-3.0.
5
 * You should have received a copy of the GNU General Public License along with this program.
6
 * If not, see <http://www.gnu.org/licenses/> or send me a mail so i can send you a copy.
7
 * @license GPL-3.0
8
 * @author Gerrit Addiks <[email protected]>
9
 */
10
11
namespace Addiks\SymfonyGenerics\Tests\Unit\Controllers;
12
13
use PHPUnit\Framework\TestCase;
14
use Addiks\SymfonyGenerics\Controllers\DefaultControllerHelper;
15
use Doctrine\ORM\EntityManagerInterface;
16
use Twig_Environment;
17
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
18
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
19
use Symfony\Component\HttpFoundation\Session\Session;
20
use Psr\Log\LoggerInterface;
21
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
22
use stdClass;
23
use Symfony\Component\HttpFoundation\RedirectResponse;
24
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
25
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
26
use Symfony\Component\HttpFoundation\RequestStack;
27
use Symfony\Component\HttpFoundation\Response;
28
use Symfony\Component\HttpFoundation\Request;
29
use Twig\Environment;
30
use Symfony\Contracts\EventDispatcher\Event;
31
use Doctrine\Persistence\ObjectRepository;
32
33
final class DefaultControllerHelperTest extends TestCase
34
{
35
36
    private DefaultControllerHelper $controllerHelper;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
37
38
    private EntityManagerInterface $entityManager;
39
40
    private Environment $twig;
41
42
    private AuthorizationCheckerInterface $authorization;
43
44
    private UrlGeneratorInterface $urlGenerator;
45
46
    private Session $session;
47
48
    private LoggerInterface $logger;
49
50
    private EventDispatcherInterface $eventDispatcher;
51
52
    private RequestStack $requestStack;
53
54
    public function setUp()
55
    {
56
        $this->entityManager = $this->createMock(EntityManagerInterface::class);
57
        $this->twig = $this->createMock(Environment::class);
58
        $this->authorization = $this->createMock(AuthorizationCheckerInterface::class);
59
        $this->urlGenerator = $this->createMock(UrlGeneratorInterface::class);
60
        $this->session = $this->createMock(Session::class);
61
        $this->logger = $this->createMock(LoggerInterface::class);
62
        $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class);
63
        $this->requestStack = $this->createMock(RequestStack::class);
64
65
        $this->controllerHelper = new DefaultControllerHelper(
66
            $this->entityManager,
67
            $this->twig,
68
            $this->authorization,
69
            $this->urlGenerator,
70
            $this->session,
71
            $this->logger,
72
            $this->eventDispatcher,
73
            $this->requestStack
74
        );
75
    }
76
77
    /**
78
     * @test
79
     */
80
    public function shouldRenderTemplate()
81
    {
82
        $this->twig->expects($this->once())->method('render')->with(
83
            $this->equalTo('some-template'),
84
            $this->equalTo(['foo', 'bar'])
85
        )->willReturn('some-response');
86
87
        /** @var Response $actualResult */
88
        $actualResult = $this->controllerHelper->renderTemplate('some-template', ['foo', 'bar']);
89
90
        $this->assertEquals(new Response('some-response'), $actualResult);
91
    }
92
93
    /**
94
     * @test
95
     */
96
    public function shouldFindEntity()
97
    {
98
        $this->entityManager->expects($this->once())->method('find')->with(
99
            $this->equalTo('some-class'),
100
            $this->equalTo('foo')
101
        )->willReturn('some-entity');
102
103
        /** @var mixed $actualResult */
104
        $actualResult = $this->controllerHelper->findEntity('some-class', 'foo');
105
106
        $this->assertEquals('some-entity', $actualResult);
107
    }
108
109
    /**
110
     * @test
111
     */
112
    public function shouldFindEntities()
113
    {
114
        /** @var ObjectRepository $repository */
115
        $repository = $this->createMock(ObjectRepository::class);
116
        $repository->method('findBy')->with(
117
            $this->equalTo(['foo' => 'bar'])
118
        )->willReturn(['some-entity', 'some-other-entity']);
119
120
        $this->entityManager->expects($this->once())->method('getRepository')->with(
121
            $this->equalTo('some-class')
122
        )->willReturn($repository);
123
124
        /** @var mixed $actualResult */
125
        $actualResult = $this->controllerHelper->findEntities('some-class', ['foo' => 'bar']);
126
127
        $this->assertEquals(['some-entity', 'some-other-entity'], $actualResult);
128
    }
129
130
    /**
131
     * @test
132
     */
133
    public function shouldPersistEntity()
134
    {
135
        /** @var stdClass $entity */
136
        $entity = $this->createMock(stdClass::class);
137
138
        $this->entityManager->expects($this->once())->method('persist')->with($this->identicalTo($entity));
139
140
        $this->controllerHelper->persistEntity($entity);
141
    }
142
143
    /**
144
     * @test
145
     */
146
    public function shouldRemoveEntity()
147
    {
148
        /** @var stdClass $entity */
149
        $entity = $this->createMock(stdClass::class);
150
151
        $this->entityManager->expects($this->once())->method('remove')->with($this->identicalTo($entity));
152
153
        $this->controllerHelper->removeEntity($entity);
154
    }
155
156
    /**
157
     * @test
158
     */
159
    public function shouldFlushORM()
160
    {
161
        $this->entityManager->expects($this->once())->method('flush');
162
        $this->controllerHelper->flushORM();
163
    }
164
165
    /**
166
     * @test
167
     */
168
    public function shouldHaveRequestStack()
169
    {
170
        $this->assertSame($this->requestStack, $this->controllerHelper->getRequestStack());
171
    }
172
173
    /**
174
     * @test
175
     */
176
    public function shouldHaveCurrentRequest()
177
    {
178
        /** @var Request $request */
179
        $request = $this->createMock(Request::class);
180
181
        $this->requestStack->method("getCurrentRequest")->willReturn($request);
182
183
        $this->assertSame($request, $this->controllerHelper->getCurrentRequest());
184
    }
185
186
    /**
187
     * @test
188
     */
189
    public function shouldDispatchEvent()
190
    {
191
        /** @var Event $event */
192
        $event = $this->createMock(Event::class);
193
194
        $this->eventDispatcher->expects($this->once())->method('dispatch')->with(
195
            $this->equalTo($event),
196
            $this->equalTo('foo')
197
        )->willReturn($event);
198
199
        $this->assertSame($event, $this->controllerHelper->dispatchEvent("foo", $event));
200
    }
201
202
    /**
203
     * @test
204
     */
205
    public function shouldHandleException()
206
    {
207
        /** @var Exception $exception */
208
        $exception = $this->createMock('Exception');
209
        $exception->method('__toString')->willReturn("some-string");
210
211
        $this->logger->expects($this->once())->method('log')->with(
212
            $this->equalTo('error'),
213
            $this->identicalTo('some-string')
214
        );
215
216
        $this->controllerHelper->handleException($exception);
217
    }
218
219
    /**
220
     * @test
221
     */
222
    public function shouldAddFlashMessage()
223
    {
224
        /** @var FlashBagInterface $flashBag */
225
        $flashBag = $this->createMock(FlashBagInterface::class);
226
        $flashBag->expects($this->once())->method('add')->with(
227
            $this->equalTo('some-type'),
228
            $this->equalTo("Lorem ipsum dolor sit amet!")
229
        );
230
231
        $this->session->method('getFlashBag')->willReturn($flashBag);
232
233
        $this->controllerHelper->addFlashMessage("Lorem ipsum dolor sit amet!", "some-type");
234
    }
235
236
    /**
237
     * @test
238
     */
239
    public function shouldUseDefaultCodeWhenRedirectingToRoute()
240
    {
241
        $this->urlGenerator->expects($this->once())->method('generate')->with(
242
            $this->equalTo('some_route'),
243
            $this->equalTo(['foo' => 'bar']),
244
            $this->equalTo(UrlGeneratorInterface::ABSOLUTE_URL)
245
        )->willReturn("*this-is-some-url*");
246
247
        $expectedResponse = new RedirectResponse("*this-is-some-url*", 301);
248
249
        /** @var RedirectResponse $actualResponse */
250
        $actualResponse = $this->controllerHelper->redirectToRoute("some_route", ['foo' => 'bar']);
251
252
        $this->assertEquals($expectedResponse, $actualResponse);
253
    }
254
255
    /**
256
     * @test
257
     */
258
    public function shouldRedirectToRoute()
259
    {
260
        $this->urlGenerator->expects($this->once())->method('generate')->with(
261
            $this->equalTo('some_route'),
262
            $this->equalTo(['foo' => 'bar']),
263
            $this->equalTo(UrlGeneratorInterface::ABSOLUTE_URL)
264
        )->willReturn("*this-is-some-url*");
265
266
        $expectedResponse = new RedirectResponse("*this-is-some-url*", 302);
267
268
        /** @var RedirectResponse $actualResponse */
269
        $actualResponse = $this->controllerHelper->redirectToRoute("some_route", ['foo' => 'bar'], 302);
270
271
        $this->assertEquals($expectedResponse, $actualResponse);
272
    }
273
274
    /**
275
     * @test
276
     */
277
    public function shouldDenyAccessWhenNotGranted()
278
    {
279
        $this->expectException(AccessDeniedException::class);
280
281
        /** @var stdClass $subject */
282
        $subject = $this->createMock(stdClass::class);
283
284
        $this->authorization->expects($this->once())->method('isGranted')->with(
285
            $this->equalTo("foo"),
286
            $this->equalTo($subject)
287
        )->willReturn(false);
288
289
        try {
290
            $this->controllerHelper->denyAccessUnlessGranted("foo", $subject);
291
292
        } catch (AccessDeniedException $exception) {
293
            $this->assertEquals(["foo"], $exception->getAttributes());
294
            $this->assertSame($subject, $exception->getSubject());
295
296
            throw $exception;
297
        }
298
    }
299
300
    /**
301
     * @test
302
     */
303
    public function shouldNotDenyAccessWhenGranted()
304
    {
305
        /** @var stdClass $subject */
306
        $subject = $this->createMock(stdClass::class);
307
308
        $this->authorization->expects($this->once())->method('isGranted')->with(
309
            $this->equalTo("foo"),
310
            $this->equalTo($subject)
311
        )->willReturn(true);
312
313
        $this->controllerHelper->denyAccessUnlessGranted("foo", $subject);
314
    }
315
316
}
317