1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of coisa/http. |
5
|
|
|
* |
6
|
|
|
* (c) Felipe Sayão Lobato Abreu <[email protected]> |
7
|
|
|
* |
8
|
|
|
* This source file is subject to the license that is bundled |
9
|
|
|
* with this source code in the file LICENSE. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace CoiSA\Http\Middleware; |
15
|
|
|
|
16
|
|
|
use CoiSA\Http\Message\UploadedFile\FilterInterface; |
17
|
|
|
use Psr\Http\Message\ResponseInterface; |
18
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
19
|
|
|
use Psr\Http\Message\UploadedFileInterface; |
20
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
21
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Class MoveUploadedFilesMiddleware |
25
|
|
|
* |
26
|
|
|
* @package CoiSA\Http\Middleware |
27
|
|
|
*/ |
28
|
|
|
final class MoveUploadedFilesMiddleware implements MiddlewareInterface |
29
|
|
|
{ |
30
|
|
|
/** |
31
|
|
|
* @var string |
32
|
|
|
*/ |
33
|
|
|
private $targetPath; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var null|FilterInterface |
37
|
|
|
*/ |
38
|
|
|
private $filter; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* MoveUploadedFilesMiddleware constructor. |
42
|
|
|
* |
43
|
|
|
* @param string $targetPath |
44
|
|
|
* @param null|FilterInterface $filter |
45
|
|
|
*/ |
46
|
2 |
|
public function __construct(string $targetPath, FilterInterface $filter = null) |
47
|
|
|
{ |
48
|
2 |
|
$this->targetPath = $targetPath; |
49
|
2 |
|
$this->filter = $filter; |
50
|
|
|
|
51
|
2 |
|
if (!\is_dir($this->targetPath)) { |
52
|
|
|
throw new \UnexpectedValueException(\sprintf( |
53
|
|
|
'The given target path `%s` is not a directory', |
54
|
|
|
$this->targetPath |
55
|
|
|
)); |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
if (!\is_writable($this->targetPath)) { |
59
|
|
|
throw new \RuntimeException(\sprintf( |
60
|
|
|
'The target directory `%s` does not exists or is not writable', |
61
|
|
|
$this->targetPath |
62
|
|
|
)); |
63
|
|
|
} |
64
|
2 |
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* {@inheritdoc} |
68
|
|
|
*/ |
69
|
1 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
70
|
|
|
{ |
71
|
|
|
/** @var UploadedFileInterface[] $uploadedFiles */ |
72
|
1 |
|
$uploadedFiles = $request->getUploadedFiles(); |
73
|
|
|
|
74
|
1 |
|
if ($this->filter) { |
75
|
|
|
$uploadedFiles = $this->filter->filter(...$uploadedFiles); |
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
if (!empty($uploadedFiles)) { |
79
|
|
|
foreach ($uploadedFiles as $uploadedFile) { |
80
|
|
|
$uploadedFile->moveTo($this->targetPath); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
1 |
|
return $handler->handle($request); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|