Completed
Push — master ( 12bc5d...f69768 )
by Oscar
58:41
created

FileTrait::getFilename()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 19
rs 8.8571
cc 6
eloc 10
nc 16
nop 2
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
    use BasePathTrait;
13
14
    /**
15
     * @var string
16
     */
17
    private $directory;
18
19
    /**
20
     * @var bool
21
     */
22
    private $appendQuery;
23
24
    /**
25
     * Set the storage directory of the file.
26
     *
27
     * @param string $directory
28
     */
29
    public function __construct($directory)
30
    {
31
        $this->directory = $directory;
32
    }
33
34
    /**
35
     * Set whether use or not the uri query to generate the filenames.
36
     * 
37
     * @param bool $appendQuery
38
     * 
39
     * @return self
40
     */
41
    public function appendQuery($appendQuery = true)
42
    {
43
        $this->appendQuery = $appendQuery;
44
45
        return $this;
46
    }
47
48
    /**
49
     * Returns the filename of the response file.
50
     *
51
     * @param RequestInterface $request
52
     * @param string           $indexExt
53
     *
54
     * @return string
55
     */
56
    private function getFilename(RequestInterface $request, $indexExt = 'html')
57
    {
58
        $path = $this->getPath($request->getUri()->getPath());
59
60
        $parts = pathinfo($path);
61
        $path = isset($parts['dirname']) ? $parts['dirname'] : '';
62
        $filename = isset($parts['basename']) ? $parts['basename'] : '';
63
64
        //if it's a directory, append the index file
65
        if (empty($parts['extension'])) {
66
            $filename .= "/index.{$indexExt}";
67
        }
68
69
        if ($this->appendQuery && $request->getUri()->getQuery()) {
70
            $filename .= '?'.urlencode($request->getUri()->getQuery());
71
        }
72
73
        return Helpers::joinPath($this->directory, $path, $filename);
74
    }
75
}
76