Completed
Push — master ( c2f224...2bc1cd )
by Oscar
03:33
created

Helpers::fixPath()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 11
rs 9.4286
cc 2
eloc 7
nc 1
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
8
/**
9
 * Helper functions.
10
 */
11
class Helpers
12
{
13
    /**
14
     * helper function to fix paths '//' or '/./' or '/foo/../' in a path.
15
     *
16
     * @param string $path Path to resolve
17
     *
18
     * @return string
19
     */
20
    public static function fixPath($path)
21
    {
22
        $path = str_replace('\\', '/', $path); //windows paths
23
        $replace = ['#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'];
24
25
        do {
26
            $path = preg_replace($replace, '/', $path, -1, $n);
27
        } while ($n > 0);
28
29
        return $path;
30
    }
31
32
    /**
33
     * Join several pieces into a path.
34
     * 
35
     * @param string
36
     *               ...
37
     * 
38
     * @return string
39
     */
40
    public static function joinPath()
41
    {
42
        return self::fixPath(implode('/', func_get_args()));
43
    }
44
45
    /**
46
     * Check whether a request is or not ajax.
47
     * 
48
     * @param RequestInterface $request
49
     * 
50
     * @return bool
51
     */
52
    public static function isAjax(RequestInterface $request)
53
    {
54
        return strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest';
55
    }
56
57
    /**
58
     * Check whether a response is a redirection
59
     * 
60
     * @param ResponseInterface $response
61
     * 
62
     * @return bool
63
     */
64
    public static function isRedirect(ResponseInterface $response)
65
    {
66
        return in_array($response->getStatusCode(), [302, 301]);
67
    }
68
}
69