Completed
Push — master ( 60ebca...664783 )
by Narcotic
21:04
created

FileControllerTest   B

Complexity

Total Complexity 15

Size/Duplication

Total Lines 828
Duplicated Lines 6.28 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 15
lcom 1
cbo 6
dl 52
loc 828
rs 7.2258
c 4
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 10 1
A testFindAllEmptyCollection() 14 14 1
A testPostNewFile() 19 19 1
A testPutNewFile() 19 19 1
B testDeleteFile() 0 29 1
B testUpdateFileContent() 0 31 1
B testPostFileContentMimeDetectionAndContent() 0 42 1
B testGetFileCollectionSchemaInformation() 0 27 1
A testPutNewFileViaForm() 0 75 1
A testIllegalMimeTypeModificationHandling() 0 48 1
B testPostAndUpdateFile() 0 154 1
A testPutNewFileViaFormHashToLong() 0 59 1
B testPutNewJsonFileViaForm() 0 31 1
B assertIsFileSchema() 0 134 1
A updateFileContent() 0 22 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
2
/**
3
 * functional test for /file
4
 */
5
6
namespace Graviton\FileBundle\Tests\Controller;
7
8
use Graviton\TestBundle\Test\RestTestCase;
9
use Symfony\Component\HttpFoundation\File\UploadedFile;
10
use Symfony\Component\HttpFoundation\Response;
11
12
/**
13
 * Basic functional test for /file
14
 *
15
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
16
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
17
 * @link     http://swisscom.ch
18
 */
19
class FileControllerTest extends RestTestCase
20
{
21
    /**
22
     * @const complete content type string expected on a resource
23
     */
24
    const CONTENT_TYPE = 'application/json; charset=UTF-8; profile=http://localhost/schema/file/item';
25
26
    /**
27
     * @const corresponding vendorized schema mime type
28
     */
29
    const COLLECTION_TYPE = 'application/json; charset=UTF-8; profile=http://localhost/schema/file/collection';
30
31
    /**
32
     * setup client and load fixtures
33
     *
34
     * @return void
35
     */
36
    public function setUp()
37
    {
38
        $this->loadFixtures(
39
            array(
40
                'GravitonDyn\FileBundle\DataFixtures\MongoDB\LoadFileData'
41
            ),
42
            null,
43
            'doctrine_mongodb'
44
        );
45
    }
46
47
    /**
48
     * check for empty collections when no fixtures are loaded
49
     *
50
     * @return void
51
     */
52 View Code Duplication
    public function testFindAllEmptyCollection()
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...
53
    {
54
        // reset fixtures since we already have some from setUp
55
        $this->loadFixtures(array(), null, 'doctrine_mongodb');
56
        $client = static::createRestClient();
57
        $client->request('GET', '/file/');
58
59
        $response = $client->getResponse();
60
        $results = $client->getResults();
61
62
        $this->assertResponseContentType(self::COLLECTION_TYPE, $response);
63
64
        $this->assertEquals(array(), $results);
65
    }
66
67
    /**
68
     * validate that we can post a new file
69
     *
70
     * @return void
71
     */
72
    public function testPostAndUpdateFile()
73
    {
74
        $fixtureData = file_get_contents(__DIR__.'/fixtures/test.txt');
75
        $fileHash = hash('sha256', $fixtureData);
76
        $fileHashCustom = 'some-custom-hash-for-testing';
77
78
        $client = static::createRestClient();
79
        $client->post(
80
            '/file/',
81
            $fixtureData,
82
            [],
83
            [],
84
            ['CONTENT_TYPE' => 'text/plain'],
85
            false
86
        );
87
        $this->assertEmpty($client->getResults());
88
        $response = $client->getResponse();
89
        $this->assertEquals(201, $response->getStatusCode());
90
91
        $fileLocation = $response->headers->get('Location');
92
93
        // update file contents to update mod date
94
        $client = static::createRestClient();
95
        $client->put(
96
            $fileLocation,
97
            $fixtureData,
98
            [],
99
            [],
100
            ['CONTENT_TYPE' => 'text/plain'],
101
            false
102
        );
103
        $this->assertEmpty($client->getResults(), $client->getResponse()->getContent());
104
        $response = $client->getResponse();
105
        $this->assertEquals(204, $response->getStatusCode());
106
107
        $client = static::createRestClient();
108
        $client->request('GET', $fileLocation);
109
        $data = $client->getResults();
110
111
        // check for valid format
112
        $this->assertNotFalse(\DateTime::createFromFormat(\DateTime::RFC3339, $data->metadata->createDate));
113
        $this->assertNotFalse(\DateTime::createFromFormat(\DateTime::RFC3339, $data->metadata->modificationDate));
114
        // Check valid hash encoding if no hash sent
115
        $this->assertEquals($fileHash, $data->metadata->hash);
116
117
        $data->links = [];
118
        $link = new \stdClass;
119
        $link->{'$ref'} = 'http://localhost/core/app/tablet';
120
        $data->links[] = $link;
121
122
        $filename = "test.txt";
123
        $data->metadata->filename = $filename;
124
        $data->metadata->hash = $fileHashCustom;
125
126
        $client = static::createRestClient();
127
        $client->put(sprintf('/file/%s', $data->id), $data);
128
129
        // re-fetch
130
        $client = static::createRestClient();
131
        $client->request('GET', sprintf('/file/%s', $data->id));
132
        $results = $client->getResults();
133
134
        $this->assertEquals($link->{'$ref'}, $results->links[0]->{'$ref'});
135
        $this->assertEquals($filename, $results->metadata->filename);
136
        $this->assertEquals($fileHashCustom, $data->metadata->hash);
137
138
        $client = static::createClient();
139
        $client->request('GET', sprintf('/file/%s', $data->id), [], [], ['HTTP_ACCEPT' => 'text/plain']);
140
141
        $results = $client->getResponse()->getContent();
142
143
        $this->assertEquals($fixtureData, $results);
144
145
        // change link and add second link
146
        $data->links[0]->{'$ref'} = 'http://localhost/core/app/admin';
147
        $link = new \stdClass;
148
        $link->{'$ref'} = 'http://localhost/core/app/web';
149
        $data->links[] = $link;
150
151
        // also add action command
152
        $command = new \stdClass();
153
        $command->command = 'print';
154
        $data->metadata->action = [$command];
155
156
        // also add additionalInformation
157
        $data->metadata->additionalInformation = 'someInfo';
158
159
        $client = static::createRestClient();
160
        $client->put(sprintf('/file/%s', $data->id), $data);
161
162
        // re-fetch
163
        $client = static::createRestClient();
164
        $client->request('GET', sprintf('/file/%s', $data->id));
165
        $results = $client->getResults();
166
167
        $this->assertEquals($data->links[0]->{'$ref'}, $results->links[0]->{'$ref'});
168
        $this->assertEquals($data->links[1]->{'$ref'}, $results->links[1]->{'$ref'});
169
170
        // check metadata
171
        $this->assertEquals(18, $data->metadata->size);
172
        $this->assertEquals('text/plain', $data->metadata->mime);
173
        $this->assertEquals('test.txt', $data->metadata->filename);
174
        $this->assertEquals('print', $data->metadata->action[0]->command);
175
        $this->assertEquals('someInfo', $data->metadata->additionalInformation);
176
        $this->assertNotNull($data->metadata->createDate);
177
        $this->assertNotNull($data->metadata->modificationDate);
178
179
        // remove a link
180
        unset($data->links[1]);
181
182
        $client = static::createRestClient();
183
        $client->put(sprintf('/file/%s', $data->id), $data);
184
        // re-fetch
185
        $client = static::createRestClient();
186
        $client->request('GET', sprintf('/file/%s', $data->id));
187
        $results = $client->getResults();
188
189
        $this->assertEquals($data->links[0]->{'$ref'}, $results->links[0]->{'$ref'});
190
        $this->assertCount(1, $results->links);
191
192
        // remove last link
193
        $data->links = [];
194
        $client = static::createRestClient();
195
        $client->put(sprintf('/file/%s', $data->id), $data);
196
197
        // re-fetch
198
        $client = static::createRestClient();
199
        $client->request('GET', sprintf('/file/%s', $data->id));
200
201
        $results = $client->getResults();
202
203
        $this->assertEmpty($results->links);
204
205
        // Let's update links but without sending file and still have file info
206
        $id = $data->id;
207
        $data = new \stdClass;
208
        $data->id = $id;
209
        $link = new \stdClass;
210
        $link->{'$ref'} = 'http://localhost/core/app/web';
211
        $data->links = [];
212
        $data->links[] = $link;
213
        $client = static::createRestClient();
214
        $client->put(sprintf('/file/%s', $id), $data);
215
        // re-fetch
216
        $client = static::createRestClient();
217
        $client->request('GET', sprintf('/file/%s', $data->id));
218
        $data = $client->getResults();
219
        // check metadata for kept file info
220
        $this->assertEquals(18, $data->metadata->size);
221
        $this->assertEquals('text/plain', $data->metadata->mime);
222
        $this->assertEquals('test.txt', $data->metadata->filename);
223
        $this->assertNotNull($data->metadata->createDate);
224
        $this->assertNotNull($data->metadata->modificationDate);
225
    }
226
227
    /**
228
     * validate that we can post a new file
229
     *
230
     * @return void
231
     */
232 View Code Duplication
    public function testPostNewFile()
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...
233
    {
234
        $client = static::createRestClient();
235
236
        $client->post(
237
            '/file',
238
            file_get_contents(__DIR__.'/fixtures/test.txt'),
239
            [],
240
            [],
241
            ['CONTENT_TYPE' => 'text/plain'],
242
            false
243
        );
244
245
        $response = $client->getResponse();
246
        $linkHeader = $response->headers->get('Link');
247
248
        $this->assertEquals(201, $response->getStatusCode());
249
        $this->assertRegExp('@/file/[a-z0-9]{32}>; rel="self"@', $linkHeader);
250
    }
251
252
    /**
253
     * validate that we can put a new file with a custom id
254
     *
255
     * @return void
256
     */
257 View Code Duplication
    public function testPutNewFile()
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...
258
    {
259
        $client = static::createRestClient();
260
261
        $client->put(
262
            '/file/testPutNewFile',
263
            file_get_contents(__DIR__ . '/fixtures/test.txt'),
264
            [],
265
            [],
266
            ['CONTENT_TYPE' => 'text/plain'],
267
            false
268
        );
269
270
        $response = $client->getResponse();
271
        $linkHeader = $response->headers->get('Link');
272
273
        $this->assertEquals(204, $response->getStatusCode());
274
        $this->assertContains('file/testPutNewFile>; rel="self"', $linkHeader);
275
    }
276
277
    /**
278
     * validate that we can delete a file
279
     *
280
     * @return void
281
     */
282
    public function testDeleteFile()
283
    {
284
        $fixtureData = file_get_contents(__DIR__.'/fixtures/test.txt');
285
        $client = static::createRestClient();
286
        $client->post(
287
            '/file/',
288
            $fixtureData,
289
            [],
290
            [],
291
            ['CONTENT_TYPE' => 'text/plain'],
292
            false
293
        );
294
        $response = $client->getResponse();
295
        $this->assertEquals(201, $response->getStatusCode());
296
297
        // re-fetch
298
        $client = static::createRestClient();
299
        $client->request('GET', $response->headers->get('Location'));
300
        $data = $client->getResults();
301
302
        $client = static::createRestClient();
303
        $client->request('DELETE', sprintf('/file/%s', $data->id));
304
305
        $client = static::createRestClient();
306
        $client->request('GET', sprintf('/file/%s', $data->id));
307
308
        $response = $client->getResponse();
309
        $this->assertEquals(404, $response->getStatusCode());
310
    }
311
312
    /**
313
     * validate that we can update the content from a file
314
     *
315
     * @return void
316
     */
317
    public function testUpdateFileContent()
318
    {
319
        $fixtureData = file_get_contents(__DIR__.'/fixtures/test.txt');
320
        $contentType = 'text/plain';
321
        $newData = "This is a new text!!!";
322
        $client = static::createRestClient();
323
        $client->post(
324
            '/file/',
325
            $fixtureData,
326
            [],
327
            [],
328
            ['CONTENT_TYPE' => $contentType],
329
            false
330
        );
331
        $response = $client->getResponse();
332
        $this->assertEquals(201, $response->getStatusCode());
333
334
        $linkHeader = $response->headers->get('Link');
335
        $this->assertRegExp('@/file/[a-z0-9]{32}>; rel="self"@', $linkHeader);
336
337
        // re-fetch
338
        $client = static::createRestClient();
339
        $client->request('GET', $response->headers->get('Location'));
340
        $retData = $client->getResults();
341
342
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
343
        $this->assertEquals(strlen($fixtureData), $retData->metadata->size);
344
        $this->assertEquals($contentType, $retData->metadata->mime);
345
346
        $this->updateFileContent($retData->id, $newData, $contentType);
347
    }
348
349
    /**
350
     * post a file without any mime type.. check if that mime type is correctly determined.
351
     * fetch content back and compare the contents of the file
352
     *
353
     * @return void
354
     */
355
    public function testPostFileContentMimeDetectionAndContent()
356
    {
357
        $testData = file_get_contents(__DIR__.'/resources/testpicture.jpg');
358
        $contentType = 'image/jpeg';
359
        $client = static::createRestClient();
360
361
        $client->post(
362
            '/file/',
363
            $testData,
364
            [],
365
            [],
366
            [],
367
            false
368
        );
369
        $response = $client->getResponse();
370
        $this->assertEquals(201, $response->getStatusCode());
371
372
        $linkHeader = $response->headers->get('Link');
373
        $this->assertRegExp('@/file/[a-z0-9]{32}>; rel="self"@', $linkHeader);
374
375
        // re-fetch
376
        $client = static::createRestClient();
377
        $client->request('GET', $response->headers->get('Location'));
378
        $retData = $client->getResults();
379
380
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
381
        $this->assertEquals($contentType, $retData->metadata->mime);
382
383
        /** we use the standard client as we don't want to have json forced */
384
        $client = static::createClient();
385
        $client->request(
386
            'GET',
387
            $response->headers->get('Location'),
388
            [],
389
            [],
390
            ['ACCEPT' => $contentType]
391
        );
392
393
        $response = $client->getInternalResponse();
394
395
        $this->assertTrue(($response->getContent() === $testData));
396
    }
397
398
    /**
399
     * here we PUT a file, then try to update the mimetype in the metadata
400
     * to 'something/other' and see if we can still GET it and receive the correct mime type
401
     * (meaning we were not able to modify the mime type)
402
     *
403
     * @return void
404
     */
405
    public function testIllegalMimeTypeModificationHandling()
406
    {
407
        $fileData = "This is a new text!!!";
408
        $contentType = 'text/plain';
409
410
        $client = static::createRestClient();
411
        $client->put(
412
            '/file/mimefile',
413
            $fileData,
414
            [],
415
            [],
416
            [],
417
            [],
0 ignored issues
show
Documentation introduced by
array() is of type array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
418
            false
0 ignored issues
show
Unused Code introduced by
The call to Client::put() has too many arguments starting with false.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
419
        );
420
        $response = $client->getResponse();
421
        $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());
422
423
        // GET the metadata
424
        $client = static::createRestClient();
425
        $client->request('GET', '/file/mimefile');
426
        $retData = $client->getResults();
427
428
        $this->assertEquals($retData->metadata->mime, $contentType);
429
430
        // change metadata and save
431
        $retData->metadata->mime = 'something/other';
432
433
        $client = static::createRestClient();
434
        $client->put('/file/mimefile', $retData);
435
436
        $client = static::createClient();
437
        $client->request(
438
            'GET',
439
            '/file/mimefile',
440
            [],
441
            [],
442
            ['ACCEPT' => '*/*']
443
        );
444
445
        $response = $client->getInternalResponse();
446
447
        // still the good one?
448
        $this->assertContains($contentType, $response->getHeader('content-type'));
449
450
        $client = static::createRestClient();
451
        $client->request('DELETE', '/file/mimefile');
452
    }
453
454
    /**
455
     * test getting collection schema
456
     *
457
     * @return void
458
     */
459
    public function testGetFileCollectionSchemaInformation()
460
    {
461
        $client = static::createRestClient();
462
463
        $client->request('GET', '/schema/file/collection');
464
465
        $response = $client->getResponse();
466
        $results = $client->getResults();
467
468
        $this->assertResponseContentType('application/schema+json', $response);
469
        $this->assertEquals(200, $response->getStatusCode());
470
471
        $this->assertEquals('Array of file objects', $results->title);
472
        $this->assertEquals('array', $results->type);
473
        $this->assertIsFileSchema($results->items);
474
475
        $this->assertCorsHeaders('GET, POST, PUT, PATCH, DELETE, OPTIONS', $response);
476
        $this->assertContains(
477
            'Link',
478
            explode(',', $response->headers->get('Access-Control-Expose-Headers'))
479
        );
480
481
        $this->assertContains(
482
            '<http://localhost/schema/file/collection>; rel="self"',
483
            explode(',', $response->headers->get('Link'))
484
        );
485
    }
486
487
    /**
488
     * test behavior when data sent was multipart/form-data
489
     *
490
     * @return void
491
     */
492
    public function testPutNewFileViaForm()
493
    {
494
        copy(__DIR__ . '/fixtures/test.txt', sys_get_temp_dir() . '/test.txt');
495
        $file = sys_get_temp_dir() . '/test.txt';
496
        $uploadedFile = new UploadedFile($file, 'test.txt', 'text/plain', 15);
497
498
        $jsonData = '{
499
          "id": "myPersonalFile",
500
          "links": [
501
            {
502
              "$ref": "http://localhost/testcase/readonly/101",
503
              "type": "owner"
504
            },
505
            {
506
              "$ref": "http://localhost/testcase/readonly/102",
507
              "type": "module"
508
            }
509
          ],
510
          "metadata": {
511
            "hash": "fix,Not,allowEd,%&ç*2$a-here-demo-test-hash",
512
            "action":[{"command":"print"},{"command":"archive"}],
513
            "additionalInformation": "someInfo",
514
            "additionalProperties": [
515
                {"name": "testName", "value": "testValue"},
516
                {"name": "testName2", "value": "testValue2"}
517
            ],
518
            "filename": "customFileName"
519
          }
520
        }';
521
522
        $client = static::createRestClient();
523
        $client->put(
524
            '/file/myPersonalFile',
525
            [],
526
            [
527
                'metadata' => $jsonData,
528
            ],
529
            [
530
                'upload' => $uploadedFile,
531
            ],
532
            [],
533
            false
534
        );
535
536
        $response = $client->getResponse();
537
538
        $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());
539
        $this->assertNotContains('location', $response->headers->all());
540
541
        $response = $this->updateFileContent('myPersonalFile', "This is a new text!!!");
542
543
        $metaData = json_decode($jsonData, true);
544
        $returnData = json_decode($response->getContent(), true);
545
546
        $this->assertEquals($metaData['links'], $returnData['links']);
547
        $this->assertEquals($metaData['metadata']['action'], $returnData['metadata']['action']);
548
        $this->assertEquals(
549
            $metaData['metadata']['additionalInformation'],
550
            $returnData['metadata']['additionalInformation']
551
        );
552
        $this->assertEquals(
553
            $metaData['metadata']['additionalProperties'],
554
            $returnData['metadata']['additionalProperties']
555
        );
556
        $this->assertCount(2, $returnData['metadata']['additionalProperties']);
557
        $this->assertEquals($metaData['metadata']['filename'], $returnData['metadata']['filename']);
558
        $this->assertEquals('fix-Not-allowEd------2-a-here-demo-test-hash', $returnData['metadata']['hash']);
559
560
        // clean up
561
        $client = $this->createClient();
562
        $client->request(
563
            'DELETE',
564
            '/file/myPersonalFile'
565
        );
566
    }
567
568
    /**
569
     * test behavior when data sent was multipart/form-data
570
     *
571
     * @return void
572
     */
573
    public function testPutNewFileViaFormHashToLong()
574
    {
575
        copy(__DIR__ . '/fixtures/test.txt', sys_get_temp_dir() . '/test.txt');
576
        $file = sys_get_temp_dir() . '/test.txt';
577
        $uploadedFile = new UploadedFile($file, 'test.txt', 'text/plain', 15);
578
579
        $fixtureData = file_get_contents(__DIR__.'/fixtures/test.txt');
580
        $correctHash = hash('sha256', $fixtureData);
581
582
        // Max 64 length, should not contain the extra bitsasd
583
        $toLongHashExtra = $correctHash . '-some-extra-bits ';
584
585
        $jsonData = '{
586
          "id": "myPersonalFile2",
587
          "metadata": {
588
            "hash": "'.$toLongHashExtra.'",
589
            "action":[{"command":"archive"}],
590
            "filename": "customFileName"
591
          }
592
        }';
593
594
        $client = static::createRestClient();
595
        $client->put(
596
            '/file/myPersonalFile2',
597
            [],
598
            [
599
                'metadata' => $jsonData,
600
            ],
601
            [
602
                'upload' => $uploadedFile,
603
            ],
604
            [],
605
            false
606
        );
607
608
        $response = $client->getResponse();
609
610
        $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());
611
        $this->assertNotContains('location', $response->headers->all());
612
613
        $response = $this->updateFileContent('myPersonalFile2', "This is a new text!!!");
614
615
        $metaData = json_decode($jsonData, true);
616
        $returnData = json_decode($response->getContent(), true);
617
618
        $this->assertEquals($metaData['metadata']['filename'], $returnData['metadata']['filename']);
619
620
        // Should NOT be equal as hash was to long and was chopped.
621
        $this->assertNotEquals($metaData['metadata']['hash'], $returnData['metadata']['hash']);
622
        // But it should be equal to to first part of the hash
623
        $this->assertEquals($correctHash, $returnData['metadata']['hash']);
624
625
        // clean up
626
        $client = $this->createClient();
627
        $client->request(
628
            'DELETE',
629
            '/file/myPersonalFile2'
630
        );
631
    }
632
633
634
635
    /**
636
    /**
637
     * test behavior when data sent was multipart/form-data
638
     *
639
     * @return void
640
     */
641
    public function testPutNewJsonFileViaForm()
642
    {
643
        $fileId = 'simple-json-content';
644
        $newContent = '{
645
          "id": "myPersonalFile",
646
          "someArrayData": [
647
            {
648
              "field1": "fieldDataValue"
649
            }
650
          ],
651
          "UnknownData": {
652
            "testField": "filed"
653
          }
654
        }';
655
656
        $this->updateFileContent($fileId, $newContent);
657
658
        $client = $this->createClient([], ['CONTENT_TYPE' => 'text/plain']);
659
        $client->request('GET', sprintf('/file/%s', $fileId));
660
661
        $retData = $client->getResponse()->getContent();
662
663
        $this->assertEquals($retData, $newContent);
664
665
        // clean up
666
        $client = $this->createClient();
667
        $client->request(
668
            'DELETE',
669
            '/file/'.$fileId
670
        );
671
    }
672
673
    /**
674
     * check if a schema is of the file type
675
     *
676
     * @param \stdClass $schema schema from service to validate
677
     *
678
     * @return void
679
     */
680
    private function assertIsFileSchema(\stdClass $schema)
681
    {
682
        $this->assertEquals('File', $schema->title);
683
        $this->assertEquals('File storage service', $schema->description);
684
        $this->assertEquals('object', $schema->type);
685
686
        $this->assertEquals('string', $schema->properties->id->type);
687
        $this->assertEquals('ID', $schema->properties->id->title);
688
        $this->assertEquals('Unique identifier', $schema->properties->id->description);
689
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->id);
690
691
        // Metadata
692
        $this->assertEquals('object', $schema->properties->metadata->type);
693
        $this->assertEquals('Metadata', $schema->properties->metadata->title);
694
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->metadata);
695
696
        // Metadata size
697
        $this->assertEquals('integer', $schema->properties->metadata->properties->size->type);
698
        $this->assertEquals('File size', $schema->properties->metadata->properties->size->title);
699
        $this->assertEquals('Size of file.', $schema->properties->metadata->properties->size->description);
700
701
        // Metadata mime
702
        $this->assertContains('string', $schema->properties->metadata->properties->mime->type);
703
        $this->assertEquals('MIME Type', $schema->properties->metadata->properties->mime->title);
704
        $this->assertEquals('MIME-Type of file.', $schema->properties->metadata->properties->mime->description);
705
706
        // Metadata createDate
707
        $this->assertEquals(['string', 'null'], $schema->properties->metadata->properties->createDate->type);
708
        $this->assertEquals('date-time', $schema->properties->metadata->properties->createDate->format);
709
        $this->assertEquals('Creation date', $schema->properties->metadata->properties->createDate->title);
710
        $this->assertEquals(
711
            'Timestamp of file upload.',
712
            $schema->properties->metadata->properties->createDate->description
713
        );
714
715
        // Metadata modificationDate
716
        $this->assertEquals(['string', 'null'], $schema->properties->metadata->properties->modificationDate->type);
717
        $this->assertEquals('date-time', $schema->properties->metadata->properties->modificationDate->format);
718
        $this->assertEquals('Modification date', $schema->properties->metadata->properties->modificationDate->title);
719
        $this->assertEquals(
720
            'Timestamp of the last file change.',
721
            $schema->properties->metadata->properties->modificationDate->description
722
        );
723
724
        // Metadata filename
725
        $this->assertContains('string', $schema->properties->metadata->properties->filename->type);
726
        $this->assertEquals('File name', $schema->properties->metadata->properties->filename->title);
727
        $this->assertEquals(
728
            'Name of the file as it should get displayed to the user.',
729
            $schema->properties->metadata->properties->filename->description
730
        );
731
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->metadata->properties->filename);
732
733
        // metadata action.command array
734
        $this->assertContains(
735
            'string',
736
            $schema->properties->metadata->properties->action->items->properties->command->type
737
        );
738
        $this->assertEquals(
739
            'Action command array',
740
            $schema->properties->metadata->properties->action->items->properties->command->title
741
        );
742
        $this->assertObjectNotHasAttribute(
743
            'readOnly',
744
            $schema->properties->metadata->properties->action->items->properties->command
745
        );
746
747
        // metadata additionalInformation
748
        $this->assertContains(
749
            'string',
750
            $schema->properties->metadata->properties->additionalInformation->type
751
        );
752
        $this->assertEquals(
753
            'Additional Information',
754
            $schema->properties->metadata->properties->additionalInformation->title
755
        );
756
        $this->assertObjectNotHasAttribute(
757
            'readOnly',
758
            $schema->properties->metadata->properties->additionalInformation
759
        );
760
761
        // metadata additionalProperties
762
        $additionalPropertiesSchema = $schema->properties->metadata->properties->additionalProperties;
763
        $this->assertEquals('array', $additionalPropertiesSchema->type);
764
        $this->assertEquals('object', $additionalPropertiesSchema->items->type);
765
        $this->assertEquals('string', $additionalPropertiesSchema->items->properties->name->type);
766
        $this->assertEquals('property name', $additionalPropertiesSchema->items->properties->name->title);
767
        $this->assertEquals('string', $additionalPropertiesSchema->items->properties->value->type);
768
        $this->assertEquals('property value', $additionalPropertiesSchema->items->properties->value->title);
769
770
        // Links
771
        $this->assertEquals('array', $schema->properties->links->type);
772
        $this->assertEquals('many', $schema->properties->links->format);
773
        $this->assertEquals('Links', $schema->properties->links->title);
774
        $this->assertEquals('@todo replace me', $schema->properties->links->description);
775
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->links);
776
777
778
        // Links items
779
        $this->assertEquals('object', $schema->properties->links->items->type);
780
        $this->assertEquals('Links', $schema->properties->links->items->title);
781
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->links->items);
782
783
784
        // Links item type
785
        $this->assertContains('string', $schema->properties->links->items->properties->type->type);
786
        $this->assertEquals('Type', $schema->properties->links->items->properties->type->title);
787
        $this->assertEquals('Type of the link.', $schema->properties->links->items->properties->type->description);
788
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->links->items->properties->type);
789
790
        // Links item $ref
791
        $this->assertEquals(['string', 'null'], $schema->properties->links->items->properties->{'$ref'}->type);
792
        $this->assertEquals('extref', $schema->properties->links->items->properties->{'$ref'}->format);
793
        $this->assertEquals('Link', $schema->properties->links->items->properties->{'$ref'}->title);
794
        $this->assertEquals(
795
            'Link to any document.',
796
            $schema->properties->links->items->properties->{'$ref'}->description
797
        );
798
        $this->assertEquals(
799
            ['*'],
800
            $schema->properties->links->items->properties->{'$ref'}->{'x-collection'}
801
        );
802
803
        $this->assertEquals(
804
            [
805
                'document.file.file.update',
806
                'document.file.file.create',
807
                'document.file.file.delete'
808
            ],
809
            $schema->{'x-events'}
810
        );
811
812
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->links->items->properties->{'$ref'});
813
    }
814
815
    /**
816
     * Verifies the update of a file content.
817
     *
818
     * @param string $fileId      identifier of the file to be updated
819
     * @param string $newContent  new content to be stored in the file
820
     * @param string $contentType Content-Type of the file
821
     *
822
     * @return null|Response
823
     */
824
    private function updateFileContent($fileId, $newContent, $contentType = 'text/plain')
825
    {
826
        $client = static::createRestClient();
827
        $client->put(
828
            sprintf('/file/%s', $fileId),
829
            $newContent,
830
            [],
831
            [],
832
            ['CONTENT_TYPE' => $contentType],
833
            false
834
        );
835
836
        $client = static::createRestClient();
837
        $client->request('GET', sprintf('/file/%s', $fileId));
838
839
        $retData = $client->getResults();
840
        $response = $client->getResponse();
841
        $this->assertEquals(200, $response->getStatusCode());
842
        $this->assertEquals($contentType, $retData->metadata->mime);
843
844
        return $response;
845
    }
846
}
847