ad/UploadHandlerTest.php$0   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 12
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 12
rs 10
c 1
b 0
f 0
wmc 2
1
<?php
2
3
namespace Jaxon\Upload\Tests\TestUpload;
4
5
use Jaxon\Jaxon;
6
use Jaxon\Exception\RequestException;
7
use Jaxon\Exception\SetupException;
8
use Nyholm\Psr7\Factory\Psr17Factory;
9
use Nyholm\Psr7\UploadedFile;
10
use Nyholm\Psr7Server\ServerRequestCreator;
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
use Psr\Http\Server\RequestHandlerInterface;
14
use PHPUnit\Framework\TestCase;
15
16
use function Jaxon\jaxon;
17
use function Jaxon\Upload\_register as _registerUpload;
18
use function copy;
19
use function filesize;
20
use function mkdir;
21
22
class UploadHandlerTest extends TestCase
23
{
24
    /**
25
     * @var string
26
     */
27
    protected $sNameWhite;
28
29
    /**
30
     * @var string
31
     */
32
    protected $sPathWhite;
33
34
    /**
35
     * @var int
36
     */
37
    protected $sSizeWhite;
38
39
    /**
40
     * @var string
41
     */
42
    protected $sNameBlue;
43
44
    /**
45
     * @var string
46
     */
47
    protected $sPathBlue;
48
49
    /**
50
     * @var int
51
     */
52
    protected $sSizeBlue;
53
54
    /**
55
     * @throws SetupException
56
     */
57
    public function setUp(): void
58
    {
59
        jaxon()->di()->getPluginManager()->registerPlugins();
60
        _registerUpload();
61
62
        jaxon()->setOption('core.response.send', false);
63
        jaxon()->setAppOption('upload.enabled', true);
64
        jaxon()->setAppOptions([
65
            'adapter' => 'local',
66
            'dir' => __DIR__ . '/../upload/dst',
67
            // 'options' => [],
68
        ], 'storage.stores.uploads');
69
70
        $tmpDir = __DIR__ . '/../upload/tmp';
71
        @mkdir($tmpDir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

71
        /** @scrutinizer ignore-unhandled */ @mkdir($tmpDir);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
72
73
        $sSrcWhite = __DIR__ . '/../upload/src/white.png';
74
        $this->sNameWhite = 'white.png';
75
        $this->sPathWhite = "$tmpDir/{$this->sNameWhite}";
76
        $this->sSizeWhite = filesize($sSrcWhite);
77
        // Copy the file to the temp dir.
78
        @copy($sSrcWhite, $this->sPathWhite);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for copy(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

78
        /** @scrutinizer ignore-unhandled */ @copy($sSrcWhite, $this->sPathWhite);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
79
80
        $sSrcBlue = __DIR__ . '/../upload/src/blue.png';
81
        $this->sNameBlue = 'blue.png';
82
        $this->sPathBlue = "$tmpDir/{$this->sNameBlue}";
83
        $this->sSizeBlue = filesize($sSrcBlue);
84
        // Copy the file to the temp dir.
85
        @copy($sSrcBlue, $this->sPathBlue);
86
87
        jaxon()->register(Jaxon::CALLABLE_CLASS, 'SampleUpload', __DIR__ . '/../src/sample.php');
88
        jaxon()->di()->getBootstrap()->onBoot();
89
    }
90
91
    /**
92
     * @throws SetupException
93
     */
94
    public function tearDown(): void
95
    {
96
        jaxon()->reset();
97
        parent::tearDown();
98
    }
99
100
    /**
101
     * @throws RequestException
102
     */
103
    public function testAjaxUpload()
104
    {
105
        jaxon()->setAppOption('upload.default.storage', 'uploads');
106
        // Send a request to the registered class
107
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
108
            return $c->g(ServerRequestCreator::class)
109
                ->fromGlobals()
110
                ->withParsedBody([
111
                    'jxncall' => json_encode([
112
                        'type' => 'class',
113
                        'name' => 'SampleUpload',
114
                        'method' => 'myMethod',
115
                        'args' => [],
116
                    ]),
117
                ])
118
                ->withUploadedFiles([
119
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
120
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
121
                ])
122
                ->withMethod('POST');
123
        });
124
125
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
126
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
127
        jaxon()->processRequest();
128
129
        // Uploaded files
130
        $aFiles = jaxon()->upload()->files();
131
        $this->assertCount(1, $aFiles);
132
        $this->assertCount(1, $aFiles['image']);
0 ignored issues
show
Bug introduced by
$aFiles['image'] of type Jaxon\Request\Upload\FileInterface is incompatible with the type Countable|iterable expected by parameter $haystack of PHPUnit\Framework\Assert::assertCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

132
        $this->assertCount(1, /** @scrutinizer ignore-type */ $aFiles['image']);
Loading history...
133
        $xFile = $aFiles['image'][0];
134
        $this->assertEquals('white', $xFile->name());
135
        $this->assertEquals($this->sNameWhite, $xFile->filename());
136
        $this->assertEquals('png', $xFile->type());
137
        $this->assertEquals('png', $xFile->extension());
138
    }
139
140
    /**
141
     * @throws RequestException
142
     */
143
    public function testAjaxUploadMultipleFiles()
144
    {
145
        jaxon()->setAppOption('upload.default.storage', 'uploads');
146
        // Send a request to the registered class
147
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
148
            return $c->g(ServerRequestCreator::class)
149
                ->fromGlobals()
150
                ->withParsedBody([
151
                    'jxncall' => json_encode([
152
                        'type' => 'class',
153
                        'name' => 'SampleUpload',
154
                        'method' => 'myMethod',
155
                        'args' => [],
156
                    ]),
157
                ])
158
                ->withUploadedFiles([
159
                    'image' => [
160
                        new UploadedFile($this->sPathWhite, $this->sSizeWhite,
161
                            UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
162
                        new UploadedFile($this->sPathBlue, $this->sSizeBlue,
163
                            UPLOAD_ERR_OK, $this->sNameBlue, 'png'),
164
                    ],
165
                ])
166
                ->withMethod('POST');
167
        });
168
169
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
170
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
171
        jaxon()->processRequest();
172
173
        // Uploaded files
174
        $aFiles = jaxon()->upload()->files();
175
        $this->assertCount(1, $aFiles);
176
        $this->assertCount(2, $aFiles['image']);
0 ignored issues
show
Bug introduced by
$aFiles['image'] of type Jaxon\Request\Upload\FileInterface is incompatible with the type Countable|iterable expected by parameter $haystack of PHPUnit\Framework\Assert::assertCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

176
        $this->assertCount(2, /** @scrutinizer ignore-type */ $aFiles['image']);
Loading history...
177
        $xFile = $aFiles['image'][0];
178
        $this->assertEquals('white', $xFile->name());
179
        $this->assertEquals($this->sNameWhite, $xFile->filename());
180
        $this->assertEquals('png', $xFile->type());
181
        $this->assertEquals('png', $xFile->extension());
182
        $xFile = $aFiles['image'][1];
183
        $this->assertEquals('blue', $xFile->name());
184
        $this->assertEquals($this->sNameBlue, $xFile->filename());
185
        $this->assertEquals('png', $xFile->type());
186
        $this->assertEquals('png', $xFile->extension());
187
    }
188
189
    /**
190
     * @throws RequestException
191
     */
192
    public function testAjaxUploadMultipleNames()
193
    {
194
        jaxon()->setAppOption('upload.default.storage', 'uploads');
195
        // Send a request to the registered class
196
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
197
            return $c->g(ServerRequestCreator::class)
198
                ->fromGlobals()
199
                ->withParsedBody([
200
                    'jxncall' => json_encode([
201
                        'type' => 'class',
202
                        'name' => 'SampleUpload',
203
                        'method' => 'myMethod',
204
                        'args' => [],
205
                    ]),
206
                ])
207
                ->withUploadedFiles([
208
                    'white' => [
209
                        new UploadedFile($this->sPathWhite, $this->sSizeWhite,
210
                            UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
211
                    ],
212
                    'blue' => [
213
                        new UploadedFile($this->sPathBlue, $this->sSizeBlue,
214
                            UPLOAD_ERR_OK, $this->sNameBlue, 'png'),
215
                    ],
216
                ])
217
                ->withMethod('POST');
218
        });
219
220
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
221
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
222
        jaxon()->processRequest();
223
224
        // Uploaded files
225
        $aFiles = jaxon()->upload()->files();
226
        $this->assertCount(2, $aFiles);
227
        $this->assertCount(1, $aFiles['white']);
0 ignored issues
show
Bug introduced by
$aFiles['white'] of type Jaxon\Request\Upload\FileInterface is incompatible with the type Countable|iterable expected by parameter $haystack of PHPUnit\Framework\Assert::assertCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

227
        $this->assertCount(1, /** @scrutinizer ignore-type */ $aFiles['white']);
Loading history...
228
        $this->assertCount(1, $aFiles['blue']);
229
        $xFile = $aFiles['white'][0];
230
        $this->assertEquals('white', $xFile->name());
231
        $this->assertEquals($this->sNameWhite, $xFile->filename());
232
        $this->assertEquals('png', $xFile->type());
233
        $this->assertEquals('png', $xFile->extension());
234
        $xFile = $aFiles['blue'][0];
235
        $this->assertEquals('blue', $xFile->name());
236
        $this->assertEquals($this->sNameBlue, $xFile->filename());
237
        $this->assertEquals('png', $xFile->type());
238
        $this->assertEquals('png', $xFile->extension());
239
    }
240
241
    /**
242
     * @throws RequestException
243
     */
244
    public function testAjaxUploadNameSanitizer()
245
    {
246
        jaxon()->setAppOption('upload.default.storage', 'uploads');
247
        jaxon()->upload()->sanitizer(function($sFilename, $sVarName) {
248
            return $sVarName === 'image' ? 'img_' . $sFilename : $sFilename;
249
        });
250
        // Send a request to the registered class
251
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
252
            return $c->g(ServerRequestCreator::class)
253
                ->fromGlobals()
254
                ->withParsedBody([
255
                    'jxncall' => json_encode([
256
                        'type' => 'class',
257
                        'name' => 'SampleUpload',
258
                        'method' => 'myMethod',
259
                        'args' => [],
260
                    ]),
261
                ])
262
                ->withUploadedFiles([
263
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
264
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
265
                ])
266
                ->withMethod('POST');
267
        });
268
269
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
270
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
271
        jaxon()->processRequest();
272
273
        // Uploaded files
274
        $aFiles = jaxon()->upload()->files();
275
        $this->assertCount(1, $aFiles);
276
        $this->assertCount(1, $aFiles['image']);
0 ignored issues
show
Bug introduced by
$aFiles['image'] of type Jaxon\Request\Upload\FileInterface is incompatible with the type Countable|iterable expected by parameter $haystack of PHPUnit\Framework\Assert::assertCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

276
        $this->assertCount(1, /** @scrutinizer ignore-type */ $aFiles['image']);
Loading history...
277
        $xFile = $aFiles['image'][0];
278
        $this->assertEquals('img_white', $xFile->name());
279
        $this->assertEquals('png', $xFile->type());
280
        $this->assertEquals('png', $xFile->extension());
281
        $this->assertEquals($this->sNameWhite, $xFile->filename());
282
    }
283
284
    /**
285
     * @throws RequestException
286
     */
287
    public function testUploadFileTypeValidationOk()
288
    {
289
        jaxon()->setAppOption('upload.default.storage', 'uploads');
290
        jaxon()->setAppOption('upload.default.types', ['png']);
291
        // Send a request to the registered class
292
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
293
            return $c->g(ServerRequestCreator::class)
294
                ->fromGlobals()
295
                ->withParsedBody([
296
                    'jxncall' => json_encode([
297
                        'type' => 'class',
298
                        'name' => 'SampleUpload',
299
                        'method' => 'myMethod',
300
                        'args' => [],
301
                    ]),
302
                ])
303
                ->withUploadedFiles([
304
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
305
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
306
                ])
307
                ->withMethod('POST');
308
        });
309
310
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
311
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
312
        jaxon()->processRequest();
313
314
        // Return the file name for the next test
315
        $aFiles = jaxon()->upload()->files();
316
        $this->assertCount(1, $aFiles);
317
        $this->assertCount(1, $aFiles['image']);
0 ignored issues
show
Bug introduced by
$aFiles['image'] of type Jaxon\Request\Upload\FileInterface is incompatible with the type Countable|iterable expected by parameter $haystack of PHPUnit\Framework\Assert::assertCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

317
        $this->assertCount(1, /** @scrutinizer ignore-type */ $aFiles['image']);
Loading history...
318
        $xFile = $aFiles['image'][0];
319
        $this->assertEquals('white', $xFile->name());
320
        $this->assertEquals($this->sNameWhite, $xFile->filename());
321
    }
322
323
    /**
324
     * @throws RequestException
325
     */
326
    public function testUploadFileTypeValidationError()
327
    {
328
        jaxon()->setAppOption('upload.default.storage', 'uploads');
329
        jaxon()->setAppOption('upload.default.types', ['jpg']);
330
        // Send a request to the registered class
331
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
332
            return $c->g(ServerRequestCreator::class)
333
                ->fromGlobals()
334
                ->withParsedBody([
335
                    'jxncall' => json_encode([
336
                        'type' => 'class',
337
                        'name' => 'SampleUpload',
338
                        'method' => 'myMethod',
339
                        'args' => [],
340
                    ]),
341
                ])
342
                ->withUploadedFiles([
343
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
344
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
345
                ])
346
                ->withMethod('POST');
347
        });
348
349
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
350
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
351
        $this->expectException(RequestException::class);
352
        jaxon()->processRequest();
353
    }
354
355
    /**
356
     * @throws RequestException
357
     */
358
    public function testUploadFileExtensionValidationOk()
359
    {
360
        jaxon()->setAppOption('upload.default.storage', 'uploads');
361
        jaxon()->setAppOption('upload.default.extensions', ['png']);
362
        // Send a request to the registered class
363
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
364
            return $c->g(ServerRequestCreator::class)
365
                ->fromGlobals()
366
                ->withParsedBody([
367
                    'jxncall' => json_encode([
368
                        'type' => 'class',
369
                        'name' => 'SampleUpload',
370
                        'method' => 'myMethod',
371
                        'args' => [],
372
                    ]),
373
                ])
374
                ->withUploadedFiles([
375
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
376
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
377
                ])
378
                ->withMethod('POST');
379
        });
380
381
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
382
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
383
        jaxon()->processRequest();
384
385
        // Return the file name for the next test
386
        $aFiles = jaxon()->upload()->files();
387
        $this->assertCount(1, $aFiles);
388
        $this->assertCount(1, $aFiles['image']);
0 ignored issues
show
Bug introduced by
$aFiles['image'] of type Jaxon\Request\Upload\FileInterface is incompatible with the type Countable|iterable expected by parameter $haystack of PHPUnit\Framework\Assert::assertCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

388
        $this->assertCount(1, /** @scrutinizer ignore-type */ $aFiles['image']);
Loading history...
389
        $xFile = $aFiles['image'][0];
390
        $this->assertEquals('white', $xFile->name());
391
        $this->assertEquals($this->sNameWhite, $xFile->filename());
392
    }
393
394
    /**
395
     * @throws RequestException
396
     */
397
    public function testUploadFileExtensionValidationError()
398
    {
399
        jaxon()->setAppOption('upload.default.storage', 'uploads');
400
        jaxon()->setAppOption('upload.default.extensions', ['jpg']);
401
        // Send a request to the registered class
402
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
403
            return $c->g(ServerRequestCreator::class)
404
                ->fromGlobals()
405
                ->withParsedBody([
406
                    'jxncall' => json_encode([
407
                        'type' => 'class',
408
                        'name' => 'SampleUpload',
409
                        'method' => 'myMethod',
410
                        'args' => [],
411
                    ]),
412
                ])
413
                ->withUploadedFiles([
414
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
415
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
416
                ])
417
                ->withMethod('POST');
418
        });
419
420
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
421
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
422
        $this->expectException(RequestException::class);
423
        jaxon()->processRequest();
424
    }
425
426
    /**
427
     * @throws RequestException
428
     */
429
    public function testUploadFileMaxSizeValidationOk()
430
    {
431
        jaxon()->setAppOption('upload.default.storage', 'uploads');
432
        jaxon()->setAppOption('upload.default.max-size', 30000);
433
        // Send a request to the registered class
434
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
435
            return $c->g(ServerRequestCreator::class)
436
                ->fromGlobals()
437
                ->withParsedBody([
438
                    'jxncall' => json_encode([
439
                        'type' => 'class',
440
                        'name' => 'SampleUpload',
441
                        'method' => 'myMethod',
442
                        'args' => [],
443
                    ]),
444
                ])
445
                ->withUploadedFiles([
446
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
447
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
448
                ])
449
                ->withMethod('POST');
450
        });
451
452
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
453
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
454
        jaxon()->processRequest();
455
456
        // Return the file name for the next test
457
        $aFiles = jaxon()->upload()->files();
458
        $this->assertCount(1, $aFiles);
459
        $this->assertCount(1, $aFiles['image']);
0 ignored issues
show
Bug introduced by
$aFiles['image'] of type Jaxon\Request\Upload\FileInterface is incompatible with the type Countable|iterable expected by parameter $haystack of PHPUnit\Framework\Assert::assertCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

459
        $this->assertCount(1, /** @scrutinizer ignore-type */ $aFiles['image']);
Loading history...
460
        $xFile = $aFiles['image'][0];
461
        $this->assertEquals('white', $xFile->name());
462
        $this->assertEquals($this->sNameWhite, $xFile->filename());
463
    }
464
465
    /**
466
     * @throws RequestException
467
     */
468
    public function testUploadFileMaxSizeValidationError()
469
    {
470
        jaxon()->setAppOption('upload.default.storage', 'uploads');
471
        jaxon()->setAppOption('upload.default.max-size', 25000);
472
        // Send a request to the registered class
473
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
474
            return $c->g(ServerRequestCreator::class)
475
                ->fromGlobals()
476
                ->withParsedBody([
477
                    'jxncall' => json_encode([
478
                        'type' => 'class',
479
                        'name' => 'SampleUpload',
480
                        'method' => 'myMethod',
481
                        'args' => [],
482
                    ]),
483
                ])
484
                ->withUploadedFiles([
485
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
486
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
487
                ])
488
                ->withMethod('POST');
489
        });
490
491
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
492
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
493
        $this->expectException(RequestException::class);
494
        jaxon()->processRequest();
495
    }
496
497
    /**
498
     * @throws RequestException
499
     */
500
    public function testUploadFileMinSizeValidationOk()
501
    {
502
        jaxon()->setAppOption('upload.default.storage', 'uploads');
503
        jaxon()->setAppOption('upload.default.min-size', 25000);
504
        // Send a request to the registered class
505
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
506
            return $c->g(ServerRequestCreator::class)
507
                ->fromGlobals()
508
                ->withParsedBody([
509
                    'jxncall' => json_encode([
510
                        'type' => 'class',
511
                        'name' => 'SampleUpload',
512
                        'method' => 'myMethod',
513
                        'args' => [],
514
                    ]),
515
                ])
516
                ->withUploadedFiles([
517
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
518
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
519
                ])
520
                ->withMethod('POST');
521
        });
522
523
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
524
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
525
        jaxon()->processRequest();
526
527
        // Return the file name for the next test
528
        $aFiles = jaxon()->upload()->files();
529
        $this->assertCount(1, $aFiles);
530
        $this->assertCount(1, $aFiles['image']);
0 ignored issues
show
Bug introduced by
$aFiles['image'] of type Jaxon\Request\Upload\FileInterface is incompatible with the type Countable|iterable expected by parameter $haystack of PHPUnit\Framework\Assert::assertCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

530
        $this->assertCount(1, /** @scrutinizer ignore-type */ $aFiles['image']);
Loading history...
531
        $xFile = $aFiles['image'][0];
532
        $this->assertEquals('white', $xFile->name());
533
        $this->assertEquals($this->sNameWhite, $xFile->filename());
534
    }
535
536
    /**
537
     * @throws RequestException
538
     */
539
    public function testUploadFileMinSizeValidationError()
540
    {
541
        jaxon()->setAppOption('upload.default.storage', 'uploads');
542
        jaxon()->setAppOption('upload.default.min-size', 30000);
543
        // Send a request to the registered class
544
        jaxon()->di()->set(ServerRequestInterface::class, function($c) {
545
            return $c->g(ServerRequestCreator::class)
546
                ->fromGlobals()
547
                ->withParsedBody([
548
                    'jxncall' => json_encode([
549
                        'type' => 'class',
550
                        'name' => 'SampleUpload',
551
                        'method' => 'myMethod',
552
                        'args' => [],
553
                    ]),
554
                ])
555
                ->withUploadedFiles([
556
                    'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
557
                        UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
558
                ])
559
                ->withMethod('POST');
560
        });
561
562
        $this->assertTrue(jaxon()->di()->getRequestHandler()->canProcessRequest());
563
        $this->assertTrue(jaxon()->di()->getUploadHandler()->canProcessRequest(jaxon()->di()->getRequest()));
564
        $this->expectException(RequestException::class);
565
        jaxon()->processRequest();
566
    }
567
568
    /**
569
     * @throws RequestException
570
     * @throws SetupException
571
     */
572
    public function testPsrAjaxUpload()
573
    {
574
        _registerUpload();
575
        jaxon()->setAppOption('upload.enabled', true);
576
        jaxon()->setAppOption('upload.default.storage', 'uploads');
577
        jaxon()->setAppOptions([
578
            'adapter' => 'local',
579
            'dir' => __DIR__ . '/../upload/dst',
580
            // 'options' => [],
581
        ], 'storage.uploads');
582
583
        // Send a request to the registered class
584
        $xRequest = jaxon()->di()->g(ServerRequestCreator::class)
585
            ->fromGlobals()
586
            ->withParsedBody([
587
                'jxncall' => json_encode([
588
                    'type' => 'class',
589
                    'name' => 'SampleUpload',
590
                    'method' => 'myMethod',
591
                    'args' => [],
592
                ]),
593
            ])
594
            ->withUploadedFiles([
595
                'image' => new UploadedFile($this->sPathWhite, $this->sSizeWhite,
596
                    UPLOAD_ERR_OK, $this->sNameWhite, 'png'),
597
            ])
598
            ->withMethod('POST');
599
600
        $xPsrConfigMiddleware = jaxon()->psr()->config(__DIR__ . '/../config/psr.php');
601
        $xPsrAjaxMiddleware = jaxon()->psr()->ajax();
602
        // PSR request handler that does nothing, useful to call the config middleware.
603
        $xEmptyRequestHandler = new class implements RequestHandlerInterface
604
        {
605
            private $xPsr17Factory;
606
607
            public function __construct()
608
            {
609
                $this->xPsr17Factory = new Psr17Factory();
610
            }
611
612
            public function handle(ServerRequestInterface $request): ResponseInterface
613
            {
614
                return $this->xPsr17Factory->createResponse();
615
            }
616
        };
617
        // Call the config middleware
618
        $xPsrConfigMiddleware->process($xRequest, $xEmptyRequestHandler);
619
        // Call the ajax middleware
620
        $xPsrResponse = $xPsrAjaxMiddleware->process($xRequest, $xEmptyRequestHandler);
621
622
        // Both responses must have the same content and content type
623
        $xJaxonResponse = jaxon()->getResponse();
624
        $this->assertEquals($xPsrResponse->getBody()->__toString(), $xJaxonResponse->getOutput());
625
        $this->assertEquals($xPsrResponse->getHeader('content-type')[0], $xJaxonResponse->getContentType());
626
627
        // Uploaded files
628
        $aFiles = jaxon()->upload()->files();
629
        $this->assertCount(1, $aFiles);
630
        $this->assertCount(1, $aFiles['image']);
0 ignored issues
show
Bug introduced by
$aFiles['image'] of type Jaxon\Request\Upload\FileInterface is incompatible with the type Countable|iterable expected by parameter $haystack of PHPUnit\Framework\Assert::assertCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

630
        $this->assertCount(1, /** @scrutinizer ignore-type */ $aFiles['image']);
Loading history...
631
        $xFile = $aFiles['image'][0];
632
        $this->assertEquals('white', $xFile->name());
633
        $this->assertEquals($this->sNameWhite, $xFile->filename());
634
        $this->assertEquals('png', $xFile->type());
635
        $this->assertEquals('png', $xFile->extension());
636
    }
637
}
638