Completed
Push — feature/service-wrapper-for-sw... ( 555800...5fd474 )
by Samuel
09:29
created

testLikeSearchOnIdentifierField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 21
rs 9.3143
c 1
b 0
f 1
cc 1
eloc 11
nc 1
nop 0
1
<?php
2
/**
3
 * functional test for /hans/showcase
4
 */
5
6
namespace Graviton\CoreBundle\Tests\Controller;
7
8
use Graviton\TestBundle\Test\RestTestCase;
9
use Symfony\Component\HttpFoundation\Response;
10
11
/**
12
 * Functional test for /hans/showcase
13
 *
14
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
15
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
16
 * @link     http://swisscom.ch
17
 */
18
class ShowcaseControllerTest extends RestTestCase
19
{
20
    /**
21
     * @const complete content type string expected on a resouce
22
     */
23
    const CONTENT_TYPE = 'application/json; charset=UTF-8; profile=http://localhost/schema/hans/showcase/item';
24
25
    /**
26
     * @const corresponding vendorized schema mime type
27
     */
28
    const COLLECTION_TYPE = 'application/json; charset=UTF-8; profile=http://localhost/schema/hans/showcase/collection';
29
30
    /**
31
     * suppress setup client and load fixtures of parent class
32
     *
33
     * @return void
34
     */
35
    public function setUp()
36
    {
37
    }
38
39
    /**
40
     * checks empty objects
41
     *
42
     * @return void
43
     */
44
    public function testGetEmptyObject()
45
    {
46
        $showCase = (object) [
47
            'anotherInt'            => 100,
48
            'aBoolean'              => true,
49
            'testField'             => ['en' => 'test'],
50
            'someOtherField'        => ['en' => 'other'],
51
            'contactCode'           => [
52
                'someDate'          => '2015-06-07T06:30:00+0000',
53
                'text'              => ['en' => 'text'],
54
            ],
55
            'contact'               => [
56
                'type'      => 'type',
57
                'value'     => 'value',
58
                'protocol'  => 'protocol',
59
                'uri'       => 'protocol:value',
60
            ],
61
62
            'nestedApps'            => [],
63
            'unstructuredObject'    => (object) [],
64
        ];
65
66
        $client = static::createRestClient();
67
        $client->post('/hans/showcase/', $showCase);
68
        $this->assertEquals(Response::HTTP_CREATED, $client->getResponse()->getStatusCode());
69
        $this->assertNull($client->getResults());
70
71
        $url = $client->getResponse()->headers->get('Location');
72
        $this->assertNotNull($url);
73
74
        $client = static::createRestClient();
75
        $client->request('GET', $url);
76
        $this->assertEquals(Response::HTTP_OK, $client->getResponse()->getStatusCode());
77
78
        $created = $client->getResults();
79
        $this->assertEquals($showCase->nestedApps, $created->nestedApps);
80
        $this->assertEquals($showCase->unstructuredObject, $created->unstructuredObject);
81
    }
82
83
    /**
84
     * see how our missing fields are explained to us
85
     *
86
     * @return void
87
     */
88
    public function testMissingFields()
89
    {
90
        $document = json_decode(
91
            file_get_contents(dirname(__FILE__).'/../resources/showcase-incomplete.json'),
92
            true
93
        );
94
95
        $client = static::createRestClient();
96
        $client->post('/hans/showcase', $document);
97
98
        $expectedErrors = [];
99
        $expectedError = new \stdClass();
100
        $expectedError->propertyPath = 'children[someOtherField]';
101
        $expectedError->message = 'This value is not valid.';
102
        $expectedErrors[] = $expectedError;
103
        $notNullError = new \stdClass();
104
        $notNullError->propertyPath = 'data.aBoolean';
105
        $notNullError->message = 'The value "" is not a valid boolean.';
106
        $expectedErrors[] = $notNullError;
107
108
        $this->assertJsonStringEqualsJsonString(
109
            json_encode($expectedErrors),
110
            json_encode($client->getResults())
111
        );
112
    }
113
114
    /**
115
     * see how our empty fields are explained to us
116
     *
117
     * @return void
118
     */
119
    public function testEmptyAllFields()
120
    {
121
        $document = [
122
            'anotherInt'  => 6555488894525,
123
            'testField'   => ['en' => 'a test string'],
124
            'aBoolean'    => '',
125
            'contactCode' => [
126
                'text'     => ['en' => 'Some Text'],
127
                'someDate' => '1984-05-01T00:00:00+0000',
128
            ],
129
            'contact'     => [
130
                'type'      => '',
131
                'value'     => '',
132
                'protocol'  => '',
133
            ],
134
        ];
135
136
        $client = static::createRestClient();
137
        $client->post('/hans/showcase', $document);
138
139
        $this->assertEquals(
140
            Response::HTTP_BAD_REQUEST,
141
            $client->getResponse()->getStatusCode()
142
        );
143
        $this->assertEquals(
144
            [
145
                (object) [
146
                    'propertyPath'  => 'children[someOtherField]',
147
                    'message'       => 'This value is not valid.',
148
                ],
149
                (object) [
150
                    'propertyPath'  => 'data.aBoolean',
151
                    'message'       => 'The value "" is not a valid boolean.',
152
                ],
153
                (object) [
154
                    'propertyPath'  => 'data.contact.type',
155
                    'message'       => 'This value should not be blank.',
156
                ],
157
                (object) [
158
                    'propertyPath'  => 'data.contact.protocol',
159
                    'message'       => 'This value should not be blank.',
160
                ],
161
                (object) [
162
                    'propertyPath'  => 'data.contact.value',
163
                    'message'       => 'This value should not be blank.',
164
                ],
165
            ],
166
            $client->getResults()
167
        );
168
    }
169
170
    /**
171
     * see how our empty fields are explained to us
172
     *
173
     * @return void
174
     */
175
    public function testEmptyFields()
176
    {
177
        $document = [
178
            'anotherInt'  => 6555488894525,
179
            'testField'   => ['en' => 'a test string'],
180
            'aBoolean'    => true,
181
            'contactCode' => [
182
                'text'     => ['en' => 'Some Text'],
183
                'someDate' => '1984-05-01T00:00:00+0000',
184
            ],
185
            'contact'     => [
186
                'type'      => 'abc',
187
                'value'     => '',
188
                'protocol'  => '',
189
            ],
190
        ];
191
192
        $client = static::createRestClient();
193
        $client->post('/hans/showcase', $document);
194
195
        $this->assertEquals(
196
            Response::HTTP_BAD_REQUEST,
197
            $client->getResponse()->getStatusCode()
198
        );
199
        $this->assertEquals(
200
            [
201
                (object) [
202
                    'propertyPath'  => 'children[someOtherField]',
203
                    'message'       => 'This value is not valid.',
204
                ],
205
                (object) [
206
                    'propertyPath'  => 'data.contact.protocol',
207
                    'message'       => 'This value should not be blank.',
208
                ],
209
                (object) [
210
                    'propertyPath'  => 'data.contact.value',
211
                    'message'       => 'This value should not be blank.',
212
                ],
213
            ],
214
            $client->getResults()
215
        );
216
    }
217
218
    /**
219
     * insert various formats to see if all works as expected
220
     *
221
     * @dataProvider postCreationDataProvider
222
     *
223
     * @param string $filename filename
224
     *
225
     * @return void
226
     */
227
    public function testPost($filename)
228
    {
229
        // showcase contains some datetime fields that we need rendered as UTC in the case of this test
230
        ini_set('date.timezone', 'UTC');
231
        $document = json_decode(
232
            file_get_contents($filename),
233
            false
234
        );
235
236
        $client = static::createRestClient();
237
        $client->post('/hans/showcase/', $document);
238
        $response = $client->getResponse();
239
240
        $this->assertEquals(Response::HTTP_CREATED, $response->getStatusCode());
241
242
        $client = static::createRestClient();
243
        $client->request('GET', $response->headers->get('Location'));
244
245
        $result = $client->getResults();
246
247
        // unset id as we cannot compare and don't care
248
        $this->assertNotNull($result->id);
249
        unset($result->id);
250
251
        $this->assertJsonStringEqualsJsonString(
252
            json_encode($document),
253
            json_encode($result)
254
        );
255
    }
256
257
    /**
258
     * Provides test sets for the testPost() test.
259
     *
260
     * @return array
261
     */
262
    public function postCreationDataProvider()
263
    {
264
        $basePath = dirname(__FILE__).'/../resources/';
265
266
        return array(
267
            'minimal' => array($basePath.'showcase-minimal.json'),
268
            'complete' => array($basePath.'showcase-complete.json')
269
        );
270
    }
271
272
    /**
273
     * test if we can save & retrieve extrefs inside 'free form objects'
274
     *
275
     * @return void
276
     */
277
    public function testFreeFormExtRefs()
278
    {
279
        $minimalExample = $this->postCreationDataProvider()['minimal'][0];
280
281
        $document = json_decode(
282
            file_get_contents($minimalExample),
283
            false
284
        );
285
286
        $document->id = 'dynextreftest';
287
288
        // insert some refs!
289
        $document->unstructuredObject = new \stdClass();
290
        $document->unstructuredObject->testRef = new \stdClass();
291
        $document->unstructuredObject->testRef->{'$ref'} = 'http://localhost/hans/showcase/500';
292
293
        // let's go more deep..
294
        $document->unstructuredObject->go = new \stdClass();
295
        $document->unstructuredObject->go->more = new \stdClass();
296
        $document->unstructuredObject->go->more->deep = new \stdClass();
297
        $document->unstructuredObject->go->more->deep->{'$ref'} = 'http://localhost/hans/showcase/500';
298
299
        // array?
300
        $document->unstructuredObject->refArray = [];
301
        $document->unstructuredObject->refArray[0] = new \stdClass();
302
        $document->unstructuredObject->refArray[0]->{'$ref'} = 'http://localhost/core/app/dude';
303
        $document->unstructuredObject->refArray[1] = new \stdClass();
304
        $document->unstructuredObject->refArray[1]->{'$ref'} = 'http://localhost/core/app/dude2';
305
306
        $client = static::createRestClient();
307
        $client->put('/hans/showcase/'.$document->id, $document);
308
309
        $this->assertEquals(204, $client->getResponse()->getStatusCode());
310
311
        $client = static::createRestClient();
312
        $client->request('GET', '/hans/showcase/'.$document->id);
313
314
        // all still the same?
315
        $this->assertEquals($document, $client->getResults());
316
    }
317
318
    /**
319
     * are extra fields denied?
320
     *
321
     * @return void
322
     */
323
    public function testExtraFieldPost()
324
    {
325
        ini_set('date.timezone', 'UTC');
326
        $document = json_decode(
327
            file_get_contents(dirname(__FILE__).'/../resources/showcase-minimal.json'),
328
            false
329
        );
330
        $document->extraFields = "nice field";
331
332
        $client = static::createRestClient();
333
        $client->post('/hans/showcase', $document);
334
        $this->assertEquals(400, $client->getResponse()->getStatusCode());
335
336
        $expectedErrors = [];
337
        $expectedErrors[0] = new \stdClass();
338
        $expectedErrors[0]->propertyPath = "";
339
        $expectedErrors[0]->message = "This form should not contain extra fields.";
340
341
        $this->assertJsonStringEqualsJsonString(
342
            json_encode($expectedErrors),
343
            json_encode($client->getResults())
344
        );
345
    }
346
347
    /**
348
     * Test RQL select statement
349
     *
350
     * @return void
351
     */
352
    public function testRqlSelect()
353
    {
354
        $this->loadFixtures(
355
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
356
            null,
357
            'doctrine_mongodb'
358
        );
359
360
        $filtred = json_decode(
361
            file_get_contents(dirname(__FILE__).'/../resources/showcase-rql-select-filtred.json'),
362
            false
363
        );
364
365
        $fields = [
366
            'someFloatyDouble',
367
            'contact.uri',
368
            'contactCode.text.en',
369
            'unstructuredObject.booleanField',
370
            'unstructuredObject.hashField.someField',
371
            'unstructuredObject.nestedArrayField.anotherField',
372
            'nestedCustomers.$ref'
373
        ];
374
        $rqlSelect = 'select('.implode(',', array_map([$this, 'encodeRqlString'], $fields)).')';
375
376
        $client = static::createRestClient();
377
        $client->request('GET', '/hans/showcase/?'.$rqlSelect);
378
        $this->assertEquals($filtred, $client->getResults());
379
380
381
        foreach ([
382
                     '500' => $filtred[0],
383
                     '600' => $filtred[1],
384
                 ] as $id => $item) {
385
            $client = static::createRestClient();
386
            $client->request('GET', '/hans/showcase/'.$id.'?'.$rqlSelect);
387
            $this->assertEquals($item, $client->getResults());
388
        }
389
    }
390
391
    /**
392
     * Test to see if we can do like() searches on identifier fields
393
     *
394
     * @return void
395
     */
396
    public function testLikeSearchOnIdentifierField()
397
    {
398
        // Load fixtures
399
        $this->loadFixtures(
400
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
401
            null,
402
            'doctrine_mongodb'
403
        );
404
405
        $client = static::createRestClient();
406
        $client->request('GET', '/hans/showcase/?like(id,5*)');
407
408
        // we should only get 1 ;-)
409
        $this->assertEquals(1, count($client->getResults()));
410
411
        $client = static::createRestClient();
412
        $client->request('GET', '/hans/showcase/?like(id,*0)');
413
414
        // this should get both
415
        $this->assertEquals(2, count($client->getResults()));
416
    }
417
418
    /**
419
     * Test PATCH for deep nested attribute
420
     *
421
     * @return void
422
     */
423 View Code Duplication
    public function testPatchDeepNestedProperty()
424
    {
425
        // Load fixtures
426
        $this->loadFixtures(
427
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
428
            null,
429
            'doctrine_mongodb'
430
        );
431
432
        // Apply PATCH request
433
        $client = static::createRestClient();
434
        $patchJson = json_encode(
435
            [
436
                [
437
                    'op' => 'replace',
438
                    'path' => '/unstructuredObject/hashField/anotherField',
439
                    'value' => 'changed nested hash field with patch'
440
                ]
441
            ]
442
        );
443
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
444
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
445
446
        // Get changed showcase
447
        $client = static::createRestClient();
448
        $client->request('GET', '/hans/showcase/500');
449
450
        $result = $client->getResults();
451
        $this->assertEquals(
452
            'changed nested hash field with patch',
453
            $result->unstructuredObject->hashField->anotherField
454
        );
455
    }
456
457
    /**
458
     * Test success PATCH method - response headers contains link to resource
459
     *
460
     * @return void
461
     */
462
    public function testPatchSuccessResponseHeaderContainsResourceLink()
463
    {
464
        // Load fixtures
465
        $this->loadFixtures(
466
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
467
            null,
468
            'doctrine_mongodb'
469
        );
470
471
        // Apply PATCH request
472
        $client = static::createRestClient();
473
        $patchJson = json_encode(
474
            [
475
                [
476
                    'op' => 'replace',
477
                    'path' => '/testField/en',
478
                    'value' => 'changed value'
479
                ]
480
            ]
481
        );
482
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
483
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
484
485
        $this->assertEquals(
486
            '/hans/showcase/500',
487
            $client->getResponse()->headers->get('Content-Location')
488
        );
489
    }
490
491
    /**
492
     * Test PATCH method - remove/change ID not allowed
493
     *
494
     * @return void
495
     */
496
    public function testPatchRemoveAndChangeIdNotAllowed()
497
    {
498
        // Load fixtures
499
        $this->loadFixtures(
500
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
501
            null,
502
            'doctrine_mongodb'
503
        );
504
505
        // Apply PATCH request
506
        $client = static::createRestClient();
507
        $patchJson = json_encode(
508
            [
509
                [
510
                    'op' => 'remove',
511
                    'path' => '/id'
512
                ]
513
            ]
514
        );
515
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
516
        $this->assertEquals(400, $client->getResponse()->getStatusCode());
517
    }
518
519
    /**
520
     * Test PATCH: add property to free object structure
521
     *
522
     * @return void
523
     */
524 View Code Duplication
    public function testPatchAddPropertyToFreeObject()
525
    {
526
        // Load fixtures
527
        $this->loadFixtures(
528
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
529
            null,
530
            'doctrine_mongodb'
531
        );
532
533
        // Apply PATCH request
534
        $client = static::createRestClient();
535
        $patchJson = json_encode(
536
            [
537
                [
538
                    'op' => 'add',
539
                    'path' => '/unstructuredObject/hashField/newAddedField',
540
                    'value' => 'new field value'
541
                ]
542
            ]
543
        );
544
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
545
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
546
547
        // Get changed showcase
548
        $client = static::createRestClient();
549
        $client->request('GET', '/hans/showcase/500');
550
551
        $result = $client->getResults();
552
        $this->assertEquals(
553
            'new field value',
554
            $result->unstructuredObject->hashField->newAddedField
555
        );
556
    }
557
558
    /**
559
     * Test PATCH for $ref attribute
560
     *
561
     * @return void
562
     * @incomplete
563
     */
564 View Code Duplication
    public function testApplyPatchForRefAttribute()
565
    {
566
        // Load fixtures
567
        $this->loadFixtures(
568
            [
569
                'GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'
570
            ],
571
            null,
572
            'doctrine_mongodb'
573
        );
574
575
        // Apply PATCH request
576
        $client = static::createRestClient();
577
        $patchJson = json_encode(
578
            [
579
                [
580
                    'op' => 'replace',
581
                    'path' => '/nestedApps/0/$ref',
582
                    'value' => 'http://localhost/core/app/admin'
583
                ]
584
            ]
585
        );
586
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
587
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
588
589
        // Check patched result
590
        $client = static::createRestClient();
591
        $client->request('GET', '/hans/showcase/500');
592
593
        $result = $client->getResults();
594
        $this->assertEquals(
595
            'http://localhost/core/app/admin',
596
            $result->nestedApps[0]->{'$ref'}
597
        );
598
    }
599
600
    /**
601
     * Test PATCH: apply patch which results to invalid Showcase schema
602
     *
603
     * @return void
604
     */
605
    public function testPatchToInvalidShowcase()
606
    {
607
        // Load fixtures
608
        $this->loadFixtures(
609
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
610
            null,
611
            'doctrine_mongodb'
612
        );
613
614
        // Apply PATCH request, remove required field
615
        $client = static::createRestClient();
616
        $patchJson = json_encode(
617
            [
618
                [
619
                    'op' => 'remove',
620
                    'path' => '/anotherInt'
621
                ]
622
            ]
623
        );
624
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
625
        $this->assertEquals(400, $client->getResponse()->getStatusCode());
626
627
        // Check that Showcase has not been changed
628
        $client = static::createRestClient();
629
        $client->request('GET', '/hans/showcase/500');
630
631
        $result = $client->getResults();
632
        $this->assertObjectHasAttribute('anotherInt', $result);
633
    }
634
635
    /**
636
     * Test PATCH: remove element from array
637
     *
638
     * @return void
639
     */
640 View Code Duplication
    public function testRemoveFromArrayPatch()
641
    {
642
        // Load fixtures
643
        $this->loadFixtures(
644
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
645
            null,
646
            'doctrine_mongodb'
647
        );
648
649
        // Apply PATCH request, remove nested app, initially there are 2 apps
650
        $client = static::createRestClient();
651
        $patchJson = json_encode(
652
            [
653
                [
654
                    'op' => 'remove',
655
                    'path' => '/nestedApps/0'
656
                ]
657
            ]
658
        );
659
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
660
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
661
662
        // Check patched result
663
        $client = static::createRestClient();
664
        $client->request('GET', '/hans/showcase/500');
665
666
        $result = $client->getResults();
667
        $this->assertEquals(1, count($result->nestedApps));
668
        $this->assertEquals('http://localhost/core/app/admin', $result->nestedApps[0]->{'$ref'});
669
    }
670
671
    /**
672
     * Test PATCH: add new element to array
673
     *
674
     * @return void
675
     */
676
    public function testAddElementToSpecificIndexInArrayPatch()
677
    {
678
        // Load fixtures
679
        $this->loadFixtures(
680
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
681
            null,
682
            'doctrine_mongodb'
683
        );
684
685
        // Apply PATCH request, add new element
686
        $client = static::createRestClient();
687
        $newElement = ['name' => 'element three'];
688
        $patchJson = json_encode(
689
            [
690
                [
691
                    'op' => 'add',
692
                    'path' => '/nestedArray/1',
693
                    'value' => $newElement
694
                ]
695
            ]
696
        );
697
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
698
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
699
700
        // Check patched result
701
        $client = static::createRestClient();
702
        $client->request('GET', '/hans/showcase/500');
703
704
        $result = $client->getResults();
705
        $this->assertEquals(3, count($result->nestedArray));
706
        $this->assertJsonStringEqualsJsonString(
707
            json_encode($newElement),
708
            json_encode($result->nestedArray[1])
709
        );
710
    }
711
712
    /**
713
     * Test PATCH: add complex object App to array
714
     *
715
     * @group ref
716
     * @return void
717
     */
718 View Code Duplication
    public function testPatchAddComplexObjectToSpecificIndexInArray()
719
    {
720
        // Load fixtures
721
        $this->loadFixtures(
722
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
723
            null,
724
            'doctrine_mongodb'
725
        );
726
727
        // Apply PATCH request, add new element
728
        $client = static::createRestClient();
729
        $newApp = ['ref' => 'http://localhost/core/app/admin'];
730
        $patchJson = json_encode(
731
            [
732
                [
733
                    'op' => 'add',
734
                    'path' => '/nestedApps/0',
735
                    'value' => $newApp
736
                ]
737
            ]
738
        );
739
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
740
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
741
742
        // Check patched result
743
        $client = static::createRestClient();
744
        $client->request('GET', '/hans/showcase/500');
745
746
        $result = $client->getResults();
747
        $this->assertEquals(3, count($result->nestedApps));
748
        $this->assertEquals(
749
            'http://localhost/core/app/admin',
750
            $result->nestedApps[0]->{'$ref'}
751
        );
752
    }
753
754
    /**
755
     * Test PATCH: add complex object App to array
756
     *
757
     * @group ref
758
     * @return void
759
     */
760 View Code Duplication
    public function testPatchAddComplexObjectToTheEndOfArray()
761
    {
762
        // Load fixtures
763
        $this->loadFixtures(
764
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
765
            null,
766
            'doctrine_mongodb'
767
        );
768
769
        // Apply PATCH request, add new element
770
        $client = static::createRestClient();
771
        $newApp = ['ref' => 'http://localhost/core/app/test'];
772
        $patchJson = json_encode(
773
            [
774
                [
775
                    'op' => 'add',
776
                    'path' => '/nestedApps/-',
777
                    'value' => $newApp
778
                ]
779
            ]
780
        );
781
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
782
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
783
784
        // Check patched result
785
        $client = static::createRestClient();
786
        $client->request('GET', '/hans/showcase/500');
787
788
        $result = $client->getResults();
789
        $this->assertEquals(3, count($result->nestedApps));
790
        $this->assertEquals(
791
            'http://localhost/core/app/test',
792
            $result->nestedApps[2]->{'$ref'}
793
        );
794
    }
795
796
    /**
797
     * Test PATCH: test operation to undefined index
798
     *
799
     * @group ref
800
     * @return void
801
     */
802
    public function testPatchTestOperationToUndefinedIndexThrowsException()
803
    {
804
        // Load fixtures
805
        $this->loadFixtures(
806
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
807
            null,
808
            'doctrine_mongodb'
809
        );
810
811
        // Apply PATCH request, add new element
812
        $client = static::createRestClient();
813
        $newApp = ['ref' => 'http://localhost/core/app/test'];
814
        $patchJson = json_encode(
815
            [
816
                [
817
                    'op' => 'test',
818
                    'path' => '/nestedApps/9',
819
                    'value' => $newApp
820
                ]
821
            ]
822
        );
823
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
824
        $this->assertEquals(400, $client->getResponse()->getStatusCode());
825
    }
826
827
    /**
828
     * Test PATCH: add complex object App to array
829
     *
830
     * @group ref
831
     * @return void
832
     */
833
    public function testPatchAddElementToUndefinedIndexResponseAsBadRequest()
834
    {
835
        // Load fixtures
836
        $this->loadFixtures(
837
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
838
            null,
839
            'doctrine_mongodb'
840
        );
841
842
        // Apply PATCH request, add new element
843
        $client = static::createRestClient();
844
        $newApp = ['ref' => 'http://localhost/core/app/admin'];
845
        $patchJson = json_encode(
846
            [
847
                [
848
                    'op' => 'add',
849
                    'path' => '/nestedApps/9',
850
                    'value' => $newApp
851
                ]
852
            ]
853
        );
854
        $client->request('PATCH', '/hans/showcase/500', array(), array(), array(), $patchJson);
855
        $this->assertEquals(400, $client->getResponse()->getStatusCode());
856
857
        // Check that patched document not changed
858
        $client = static::createRestClient();
859
        $client->request('GET', '/hans/showcase/500');
860
861
        $result = $client->getResults();
862
        $this->assertEquals(2, count($result->nestedApps));
863
    }
864
865
    /**
866
     * Encode string value in RQL
867
     *
868
     * @param string $value String value
869
     * @return string
870
     */
871 View Code Duplication
    private function encodeRqlString($value)
872
    {
873
        return strtr(
874
            rawurlencode($value),
875
            [
876
                '-' => '%2D',
877
                '_' => '%5F',
878
                '.' => '%2E',
879
                '~' => '%7E',
880
            ]
881
        );
882
    }
883
884
    /**
885
     * Trigger a 301 Status code
886
     *
887
     * @param string $url         requested url
888
     * @param string $redirectUrl redirected url
889
     * @dataProvider rqlDataProvider
890
     * @return void
891
     */
892 View Code Duplication
    public function testTrigger301($url, $redirectUrl)
893
    {
894
        $client = static::createRestClient();
895
        $client->request('GET', $url);
896
        $this->assertEquals(301, $client->getResponse()->getStatusCode());
897
        $this->assertEquals($redirectUrl, $client->getResponse()->headers->get('Location'));
898
    }
899
900
    /**
901
     * Provides urls for the testTrigger301() test.
902
     *
903
     * @return array
904
     */
905
    public function rqlDataProvider()
906
    {
907
        return [
908
            'rql' => ['url' => '/hans/showcase?id=blah' , 'redirect_url' => 'http://localhost/hans/showcase/?id=blah'],
909
            'noRql' => ['url' => '/hans/showcase' , 'redirect_url' => 'http://localhost/hans/showcase/']
910
        ];
911
    }
912
913
    /**
914
     * test finding of showcases by ref
915
     *
916
     * @dataProvider findByExtrefProvider
917
     *
918
     * @param string  $field which reference to search in
919
     * @param mixed   $url   ref to search for
920
     * @param integer $count number of results to expect
921
     *
922
     * @return void
923
     */
924
    public function testFindByExtref($field, $url, $count)
925
    {
926
        $this->loadFixtures(
927
            ['GravitonDyn\ShowCaseBundle\DataFixtures\MongoDB\LoadShowCaseData'],
928
            null,
929
            'doctrine_mongodb'
930
        );
931
932
        $url = sprintf(
933
            '/hans/showcase/?%s=%s',
934
            $this->encodeRqlString($field),
935
            $this->encodeRqlString($url)
936
        );
937
938
        $client = static::createRestClient();
939
        $client->request('GET', $url);
940
        $this->assertEquals(Response::HTTP_OK, $client->getResponse()->getStatusCode());
941
        $this->assertCount($count, $client->getResults());
942
    }
943
944
    /**
945
     * @return array
946
     */
947 View Code Duplication
    public function findByExtrefProvider()
948
    {
949
        return [
950
            'find a linked record when searching for "tablet" ref by array field' => [
951
                'nestedApps.0.$ref',
952
                'http://localhost/core/app/tablet',
953
                1
954
            ],
955
            'find a linked record when searching for "admin" ref by array field' => [
956
                'nestedApps.0.$ref',
957
                'http://localhost/core/app/admin',
958
                1
959
            ],
960
            'find nothing when searching for inextistant (and unlinked) ref by array field' => [
961
                'nestedApps.0.$ref',
962
                'http://localhost/core/app/inexistant',
963
                0
964
            ],
965
            'return nothing when searching with incomplete ref by array field' => [
966
                'nestedApps.0.$ref',
967
                'http://localhost/core/app',
968
                0
969
            ],
970
        ];
971
    }
972
}
973