|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Utils; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\RequestInterface; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Common methods used by middlewares that read/write files. |
|
9
|
|
|
*/ |
|
10
|
|
|
trait FileTrait |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var string |
|
14
|
|
|
*/ |
|
15
|
|
|
private $directory; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var bool |
|
19
|
|
|
*/ |
|
20
|
|
|
private $appendQuery; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Set the storage directory of the file. |
|
24
|
|
|
* |
|
25
|
|
|
* @param string $directory |
|
26
|
|
|
*/ |
|
27
|
|
|
public function __construct($directory) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->directory = $directory; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Set whether use or not the uri query to generate the filenames. |
|
34
|
|
|
* |
|
35
|
|
|
* @param bool $appendQuery |
|
36
|
|
|
* |
|
37
|
|
|
* @return self |
|
38
|
|
|
*/ |
|
39
|
|
|
public function appendQuery($appendQuery = true) |
|
40
|
|
|
{ |
|
41
|
|
|
$this->appendQuery = $appendQuery; |
|
42
|
|
|
|
|
43
|
|
|
return $this; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Returns the filename of the response file. |
|
48
|
|
|
* |
|
49
|
|
|
* @param RequestInterface $request |
|
50
|
|
|
* @param string $indexExt |
|
51
|
|
|
* |
|
52
|
|
|
* @return string |
|
53
|
|
|
*/ |
|
54
|
|
|
private function getFilename(RequestInterface $request, $indexExt = 'html') |
|
55
|
|
|
{ |
|
56
|
|
|
$path = urldecode($request->getUri()->getPath()); |
|
57
|
|
|
$parts = pathinfo($path); |
|
58
|
|
|
$path = isset($parts['dirname']) ? $parts['dirname'] : ''; |
|
59
|
|
|
$filename = isset($parts['basename']) ? $parts['basename'] : ''; |
|
60
|
|
|
|
|
61
|
|
|
//if it's a directory, append the index file |
|
62
|
|
|
if (empty($parts['extension'])) { |
|
63
|
|
|
$filename .= "/index.{$indexExt}"; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
if ($this->appendQuery && $request->getUri()->getQuery()) { |
|
67
|
|
|
$filename .= '?'.urlencode($request->getUri()->getQuery()); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return Helpers::joinPath($this->directory, $path, $filename); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|