BookingRestControllerTest::setUp()   B
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 29
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 29
rs 8.8571
cc 2
eloc 21
nc 2
nop 0
1
<?php
2
3
namespace JhFlexiTimeTest\Controller;
4
5
use JhFlexiTime\Controller\BookingRestController;
6
7
use JhFlexiTime\DateTime\DateTime;
8
use JhFlexiTime\Entity\UserSettings;
9
use JhFlexiTime\Repository\UserSettingsRepositoryInterface;
10
use JhUser\Entity\User;
11
use Zend\Http\Request;
12
use Zend\Http\Response;
13
use Zend\Mvc\MvcEvent;
14
use Zend\Mvc\Router\RouteMatch;
15
use Zend\Mvc\Router\Http\TreeRouteStack as HttpRouter;
16
use JhFlexiTimeTest\Util\ServiceManagerFactory;
17
use JhFlexiTime\Entity\Booking;
18
use Zend\Stdlib\Parameters;
19
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
20
21
/**
22
 * Class BookingRestControllerTest
23
 * @package JhFlexiTimeTest\Controller
24
 * @author Aydin Hassan <[email protected]>
25
 */
26
class BookingRestControllerTest extends AbstractHttpControllerTestCase
27
{
28
29
    protected $controller;
30
    protected $routeMatch;
31
    protected $event;
32
    protected $request;
33
    protected $response;
34
    protected $user;
35
    protected $bookingService;
36
    protected $timeCalculatorService;
37
38
    /**
39
     * @var UserSettingsRepositoryInterface
40
     */
41
    protected $userSettingsRepository;
42
43
    /**
44
     * @var \JhUser\Repository\UserRepositoryInterface
45
     */
46
    protected $userRepository;
47
48
    public function setUp()
49
    {
50
51
        $this->userRepository
52
            = $this->getMock('JhUser\Repository\UserRepositoryInterface');
53
        $this->userSettingsRepository
54
            = $this->getMock('JhFlexiTime\Repository\UserSettingsRepositoryInterface');
55
56
        $this->controller = new BookingRestController(
57
            $this->getBookingService(),
58
            $this->getTimeCalculatorService(),
59
            $this->userRepository,
60
            $this->userSettingsRepository
61
        );
62
63
        $this->request      = new Request();
64
        $this->routeMatch   = new RouteMatch([]);
65
        $this->event        = new MvcEvent();
66
67
        $serviceManager     = ServiceManagerFactory::getServiceManager();
68
        $config             = $serviceManager->get('Config');
69
        $routerConfig       = isset($config['router']) ? $config['router'] : [];
70
        $router             = HttpRouter::factory($routerConfig);
71
        $this->event->setRouter($router);
72
        $this->event->setRouteMatch($this->routeMatch);
73
        $this->controller->setEvent($this->event);
74
75
        $this->mockAuth();
76
    }
77
78
    public function mockAuth()
79
    {
80
        $ZfcUserMock = $this->getMock('ZfcUser\Entity\UserInterface');
81
82
        $ZfcUserMock->expects($this->any())
83
            ->method('getId')
84
            ->will($this->returnValue('1'));
85
86
        $authMock = $this->getMock('ZfcUser\Controller\Plugin\ZfcUserAuthentication');
87
88
        $authMock->expects($this->any())
89
            ->method('hasIdentity')
90
            -> will($this->returnValue(true));
91
92
        $authMock->expects($this->any())
93
            ->method('getIdentity')
94
            ->will($this->returnValue($ZfcUserMock));
95
96
        $this->controller->getPluginManager()
97
            ->setService('zfcUserAuthentication', $authMock);
98
99
        $this->user = $ZfcUserMock;
100
    }
101
102
    public function configureMockBookingService($method, array $params, $return)
103
    {
104
        $expects = $this->bookingService->expects($this->once())
105
            ->method($method)
106
            ->will($this->returnValue($return));
107
108
        call_user_func_array([$expects, "with"], $params);
109
    }
110
111
    public function configureMockTimeCalculatorService($method, array $params, $return)
112
    {
113
        $expects = $this->timeCalculatorService->expects($this->once())
114
            ->method($method)
115
            ->will($this->returnValue($return));
116
117
        call_user_func_array([$expects, "with"], $params);
118
    }
119
120
    public function getBookingService()
121
    {
122
        $mock = $this->getMockBuilder('JhFlexiTime\Service\BookingService')
123
            ->disableOriginalConstructor()
124
            ->getMock();
125
126
        $this->bookingService = $mock;
127
128
        return $mock;
129
    }
130
131
    public function getTimeCalculatorService()
132
    {
133
        $mock = $this->getMockBuilder('JhFlexiTime\Service\TimeCalculatorService')
134
            ->disableOriginalConstructor()
135
            ->getMock();
136
137
        $this->timeCalculatorService = $mock;
138
139
        return $mock;
140
    }
141
142
    public function getMockBooking()
143
    {
144
        $booking = new Booking();
145
146
        return $booking
147
            ->setDate(new DateTime("25 March 2014"))
148
            ->setUser($this->user)
149
            ->setNotes("ALL THE TIME");
150
    }
151
152
    public function testGetListCanBeAccessed()
153
    {
154
        $booking    = $this->getMockBooking();
155
        $date       = new DateTime("25 March 2014");
156
        $startDate  = new DateTime("21 April 2014");
157
158
        $this->controller->setDate($date);
159
        $this->configureMockBookingService('getUserBookingsForMonth', [$this->user, $date], [$booking]);
160
        $this->configureMockBookingService('getPagination', [$date], []);
161
        $this->configureMockTimeCalculatorService('getTotals', [$this->user, $startDate, $date], ['some-total', 20]);
162
163
        $userSettings = new UserSettings;
164
        $userSettings->setFlexStartDate($startDate);
165
166
        $this->userSettingsRepository
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<JhFlexiTime\Repos...ngsRepositoryInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
167
            ->expects($this->once())
168
            ->method('findOneByUser')
169
            ->with($this->user)
170
            ->will($this->returnValue($userSettings));
171
172
        $result   = $this->controller->dispatch($this->request);
173
        $response = $this->controller->getResponse();
174
175
        $this->assertEquals(200, $response->getStatusCode());
176
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
177
        $this->assertTrue(isset($result->bookings));
178
        $this->assertTrue(isset($result->pagination));
179
        $this->assertTrue(isset($result->date));
180
181
        $expectedTime = [
182
            'records' => [$booking],
183
            'totals'  => ['some-total', 20],
184
            'user'    => $this->user,
185
        ];
186
        $this->assertEquals($expectedTime, $result->getVariable('bookings'));
187
        $this->assertEquals([], $result->getVariable('pagination'));
188
        $this->assertSame($date, $result->getVariable('date'));
189
    }
190
191
    public function testGetListCanRetrieveOtherUserRecordsIfHasAuthorization()
192
    {
193
        $booking    = $this->getMockBooking();
194
        $date       = new DateTime("25 March 2014");
195
        $startDate  = new DateTime("21 April 2014");
196
        $this->user = new User;
197
        $this->user->setId(100);
198
199
        $this->request->setQuery(new Parameters(['user' => 100]));
200
        $this->controller->setDate($date);
201
        $this->configureMockBookingService('getUserBookingsForMonth', [$this->user, $date], [$booking]);
202
        $this->configureMockBookingService('getPagination', [$date], []);
203
        $this->configureMockTimeCalculatorService('getTotals', [$this->user, $startDate, $date], ['some-total', 20]);
204
205
        $authMock = $this->getMockBuilder('ZfcRbac\Mvc\Controller\Plugin\IsGranted')
206
            ->disableOriginalConstructor()
207
            ->getMock();
208
209
        $authMock
210
            ->expects($this->once())
211
            ->method('__invoke')
212
            ->with('flexi-time.readOthers')
213
            ->will($this->returnValue(true));
214
215
        $this->controller->getPluginManager()
216
            ->setService('isGranted', $authMock);
217
218
        $userSettings = new UserSettings;
219
        $userSettings->setFlexStartDate($startDate);
220
221
        $this->userRepository
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<JhUser\Repository\UserRepositoryInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
222
            ->expects($this->once())
223
            ->method('find')
224
            ->with(100)
225
            ->will($this->returnValue($this->user));
226
227
        $this->userSettingsRepository
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<JhFlexiTime\Repos...ngsRepositoryInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
228
            ->expects($this->once())
229
            ->method('findOneByUser')
230
            ->with($this->user)
231
            ->will($this->returnValue($userSettings));
232
233
        $result   = $this->controller->dispatch($this->request);
234
        $response = $this->controller->getResponse();
235
236
        $this->assertEquals(200, $response->getStatusCode());
237
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
238
        $this->assertTrue(isset($result->bookings));
239
        $this->assertTrue(isset($result->pagination));
240
        $this->assertTrue(isset($result->date));
241
242
        $expectedTime = [
243
            'records' => [$booking],
244
            'totals'  => ['some-total', 20],
245
            'user'    => $this->user,
246
        ];
247
        $this->assertEquals($expectedTime, $result->getVariable('bookings'));
248
        $this->assertEquals([], $result->getVariable('pagination'));
249
        $this->assertSame($date, $result->getVariable('date'));
250
    }
251
252
    public function testGetListWithOtherUserReturnsErrorIfUserNotExists()
253
    {
254
        $booking    = $this->getMockBooking();
0 ignored issues
show
Unused Code introduced by
$booking is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
255
        $date       = new DateTime("25 March 2014");
256
        $startDate  = new DateTime("21 April 2014");
257
        $this->user = new User;
258
        $this->user->setId(100);
259
260
        $this->request->setQuery(new Parameters(['user' => 100]));
261
        $this->controller->setDate($date);
262
        $authMock = $this->getMockBuilder('ZfcRbac\Mvc\Controller\Plugin\IsGranted')
263
            ->disableOriginalConstructor()
264
            ->getMock();
265
266
        $authMock
267
            ->expects($this->once())
268
            ->method('__invoke')
269
            ->with('flexi-time.readOthers')
270
            ->will($this->returnValue(true));
271
272
        $this->controller->getPluginManager()
273
            ->setService('isGranted', $authMock);
274
275
        $userSettings = new UserSettings;
276
        $userSettings->setFlexStartDate($startDate);
277
278
        $result   = $this->controller->dispatch($this->request);
279
        $response = $this->controller->getResponse();
280
281
        $this->assertEquals(200, $response->getStatusCode());
282
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
283
        $this->assertTrue(isset($result->success));
284
        $this->assertTrue(isset($result->message));
285
286
        $this->assertFalse($result->getVariable('success'));
287
        $this->assertEquals('User does not exist', $result->getVariable('message'));
288
    }
289
290
    public function testGetCanBeAccessed()
291
    {
292
        $id         = "123456789-5";
293
        $booking    = $this->getMockBooking();
294
        $this->bookingService->expects($this->once())
295
            ->method('getBookingByUserAndDate')
296
            ->with('5', $this->isInstanceOf('JhFlexiTime\DateTime\DateTime'))
297
            ->will($this->returnValue($booking));
298
299
        $this->routeMatch->setParam('id', $id);
300
301
        $result   = $this->controller->dispatch($this->request);
302
        $response = $this->controller->getResponse();
303
304
        $this->assertEquals(200, $response->getStatusCode());
305
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
306
        $this->assertSame($booking, $result->getVariable('booking'));
307
    }
308
309
    public function testCreateCanBeAccessed()
310
    {
311
        $startDate  = new DateTime("21 April 2014");
312
        $booking    = $this->getMockBooking();
313
        $this->configureMockBookingService('create', [], $booking);
314
        $this->configureMockTimeCalculatorService(
315
            'getTotals',
316
            [$this->user, $startDate, $booking->getDate()],
317
            ['some-total', 20]
318
        );
319
320
        $this->configureMockTimeCalculatorService(
321
            'getWeekTotals',
322
            [$this->user, $booking->getDate()],
323
            ['some-total', 20]
324
        );
325
326
        $userSettings = new UserSettings;
327
        $userSettings->setFlexStartDate($startDate);
328
329
        $this->userSettingsRepository
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<JhFlexiTime\Repos...ngsRepositoryInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
330
            ->expects($this->once())
331
            ->method('findOneByUser')
332
            ->with($this->user)
333
            ->will($this->returnValue($userSettings));
334
335
        $this->request->setMethod('POST');
336
        $this->request->getPost()->set('date', '25-03-2014');
337
        $this->request->getPost()->set('startTime', '09:00');
338
339
        $result   = $this->controller->dispatch($this->request);
340
        $response = $this->controller->getResponse();
341
342
        $this->assertEquals(200, $response->getStatusCode());
343
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
344
        $this->assertTrue(isset($result->success));
345
        $this->assertTrue(isset($result->booking));
346
        $this->assertTrue(isset($result->monthTotals));
347
348
        $this->assertSame($booking, $result->booking);
349
        $this->assertTrue($result->success);
350
        $this->assertEquals($result->monthTotals, ['some-total', 20]);
351
    }
352
353
    public function testCreateCanBeAccessedButFail()
354
    {
355
        $return = ['messages' => ['data' => 'INVALID YO']];
356
        $data = ['date' => '25-03-2014', 'startTime' => '09:00'];
357
        $this->configureMockBookingService('create', [$data], $return);
358
359
        $this->request->setMethod('POST');
360
        $this->request->getPost()->set('date', '25-03-2014');
361
        $this->request->getPost()->set('startTime', '09:00');
362
363
        $result   = $this->controller->dispatch($this->request);
364
        $response = $this->controller->getResponse();
365
366
        $this->assertEquals(200, $response->getStatusCode());
367
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
368
        $this->assertTrue(isset($result->messages));
369
        $this->assertTrue(isset($result->success));
370
371
        $this->assertSame($result->messages, ['data' => 'INVALID YO']);
372
        $this->assertFalse($result->success);
373
    }
374
375
    public function testUpdateCanBeAccessed()
376
    {
377
        $id         = "123456789-5";
378
        $booking    = $this->getMockBooking();
379
        $data       = ['date' => '25-03-2014', 'startTime' => '09:00'];
380
        $startDate  = new DateTime("21 April 2014");
381
382
        $this->bookingService->expects($this->once())
383
            ->method('update')
384
            ->with('5', $this->isInstanceOf('JhFlexiTime\DateTime\DateTime'), $data)
385
            ->will($this->returnValue($booking));
386
387
        $this->configureMockTimeCalculatorService(
388
            'getTotals',
389
            [$this->user, $startDate, $booking->getDate()],
390
            ['some-total', 20]
391
        );
392
393
        $this->configureMockTimeCalculatorService(
394
            'getWeekTotals',
395
            [$this->user, $booking->getDate()],
396
            ['some-total', 20]
397
        );
398
399
        $userSettings = new UserSettings;
400
        $userSettings->setFlexStartDate($startDate);
401
402
        $this->userSettingsRepository
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<JhFlexiTime\Repos...ngsRepositoryInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
403
            ->expects($this->once())
404
            ->method('findOneByUser')
405
            ->with($this->user)
406
            ->will($this->returnValue($userSettings));
407
408
        $this->routeMatch->setParam('id', $id);
409
        $this->request->setMethod('PUT');
410
        $this->request->setContent(http_build_query($data));
411
412
        $result   = $this->controller->dispatch($this->request);
413
        $response = $this->controller->getResponse();
414
415
        $this->assertEquals(200, $response->getStatusCode());
416
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
417
        $this->assertTrue(isset($result->success));
418
        $this->assertTrue(isset($result->booking));
419
        $this->assertTrue(isset($result->monthTotals));
420
        $this->assertTrue(isset($result->weekTotals));
421
422
        $this->assertSame($booking, $result->booking);
423
        $this->assertTrue($result->success);
424
        $this->assertEquals($result->monthTotals, ['some-total', 20]);
425
    }
426
427
    public function testUpdateCanBeAccessedButFail()
428
    {
429
        $id     = "123456789-5";
430
        $return = ['messages' => ['data' => 'INVALID YO']];
431
        $data   = ['date' => '25-03-2014', 'startTime' => '09:00'];
432
433
        $this->bookingService->expects($this->once())
434
            ->method('update')
435
            ->with('5', $this->isInstanceOf('JhFlexiTime\DateTime\DateTime'), $data)
436
            ->will($this->returnValue($return));
437
438
        $this->routeMatch->setParam('id', $id);
439
        $this->request->setMethod('PUT');
440
        $this->request->setContent(http_build_query($data));
441
442
        $result   = $this->controller->dispatch($this->request);
443
        $response = $this->controller->getResponse();
444
445
        $this->assertEquals(200, $response->getStatusCode());
446
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
447
        $this->assertTrue(isset($result->messages));
448
        $this->assertTrue(isset($result->success));
449
450
        $this->assertSame($result->messages, ['data' => 'INVALID YO']);
451
        $this->assertFalse($result->success);
452
    }
453
454
    public function testDeleteCanBeAccessed()
455
    {
456
        $id         = "123456789-5";
457
        $booking    = $this->getMockBooking();
458
        $startDate  = new DateTime("21 April 2014");
459
460
        $this->bookingService->expects($this->once())
461
            ->method('delete')
462
            ->with('5', $this->isInstanceOf('JhFlexiTime\DateTime\DateTime'))
463
            ->will($this->returnValue($booking));
464
465
        $this->configureMockTimeCalculatorService(
466
            'getTotals',
467
            [$this->user, $startDate, $booking->getDate()],
468
            ['some-total', 20]
469
        );
470
471
        $this->configureMockTimeCalculatorService(
472
            'getWeekTotals',
473
            [$this->user, $booking->getDate()],
474
            ['some-total', 20]
475
        );
476
477
        $userSettings = new UserSettings;
478
        $userSettings->setFlexStartDate($startDate);
479
480
        $this->userSettingsRepository
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<JhFlexiTime\Repos...ngsRepositoryInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
481
            ->expects($this->once())
482
            ->method('findOneByUser')
483
            ->with($this->user)
484
            ->will($this->returnValue($userSettings));
485
486
        $this->routeMatch->setParam('id', $id);
487
        $this->request->setMethod('DELETE');
488
489
        $result   = $this->controller->dispatch($this->request);
490
        $response = $this->controller->getResponse();
491
492
        $this->assertEquals(200, $response->getStatusCode());
493
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
494
        $this->assertTrue(isset($result->success));
495
        $this->assertTrue(isset($result->monthTotals));
496
        $this->assertTrue(isset($result->weekTotals));
497
498
        $this->assertTrue($result->success);
499
        $this->assertEquals($result->monthTotals, ['some-total', 20]);
500
    }
501
502
    public function testDeleteCanBeAccessedButFail()
503
    {
504
        $id     = "123456789-5";
505
        $return = ['messages' => ['data' => 'Invalid ID']];
506
        $this->bookingService->expects($this->once())
507
            ->method('delete')
508
            ->with('5', $this->isInstanceOf('JhFlexiTime\DateTime\DateTime'))
509
            ->will($this->returnValue($return));
510
511
512
        $this->routeMatch->setParam('id', $id);
513
        $this->request->setMethod('DELETE');
514
515
        $result   = $this->controller->dispatch($this->request);
516
        $response = $this->controller->getResponse();
517
518
        $this->assertEquals(200, $response->getStatusCode());
519
        $this->assertInstanceOf('Zend\View\Model\JsonModel', $result);
520
        $this->assertTrue(isset($result->success));
521
        $this->assertTrue(isset($result->messages));
522
523
        $this->assertFalse($result->success);
524
        $this->assertEquals($result->messages, ['data' => 'Invalid ID']);
525
    }
526
}
527