Completed
Push — master ( 2163dc...cc0315 )
by Vitaly
02:03
created

global.php ➔ src()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 2
Metric Value
cc 4
eloc 15
c 4
b 0
f 2
nc 6
nop 2
dl 0
loc 24
rs 8.6845
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 8 and the first side effect is on line 42.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Created by Vitaly Iegorov <[email protected]>.
4
 * on 26.04.16 at 10:43
5
 */
6
7
// Define this module identifier
8
define('STATIC_RESOURCE_HANDLER', 'resourcer');
9
10
/**
11
 * Static resource path builder.
12
 * @param string $path Relative static resource module path
13
 * @param null|string|\samson\core\iModule Module entity for path building, if not passed current module is used
14
 * @return string Static resource path
15
 */
16
function src($path, $module = null)
17
{
18
    // Define module
19
    switch (gettype($module)) {
20
        case 'string': // Find module by identifier
21
            $module = m($module);
22
            break;
23
        case 'object': // Do nothing
24
            break;
25
        default: // Get current module
26
            $module = m();
27
    }
28
29
    $fullPath = rtrim($module->path(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.ltrim($path, DIRECTORY_SEPARATOR);
30
31
    $realPath = realpath($fullPath);
32
33
    // Output link to static resource handler with relative path to project root
34
    if ($realPath) {
35
        echo '/'.STATIC_RESOURCE_HANDLER.'/?p='.str_replace(dirname(getcwd()), '', $realPath);
36
    } else {
37
        throw new \samsonphp\resource\exception\ResourceNotFound($fullPath);
38
    }
39
}
40
41
/** Collection of supported mime types */
42
$mimeTypes = array(
43
    'css' => 'text/css',
44
    'woff' => 'application/x-font-woff',
45
    'woff2' => 'application/x-font-woff2',
46
    'otf' => 'application/octet-stream',
47
    'ttf' => 'application/octet-stream',
48
    'eot' => 'application/vnd.ms-fontobject',
49
    'js' => 'application/x-javascript',
50
    'htm' => 'text/html;charset=utf-8',
51
    'htc' => 'text/x-component',
52
    'jpeg' => 'image/jpeg',
53
    'png' => 'image/png',
54
    'jpg' => 'image/jpg',
55
    'gif' => 'image/gif',
56
    'txt' => 'text/plain',
57
    'pdf' => 'application/pdf',
58
    'rtf' => 'application/rtf',
59
    'doc' => 'application/msword',
60
    'xls' => 'application/msexcel',
61
    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
62
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
63
    'svg' => 'image/svg+xml',
64
    'mp4' => 'video/mp4',
65
    'ogg' => 'video/ogg'
66
);
67
68
// Perform custom simple URL parsing to match needed URL for static resource serving
69
$url = array_key_exists('REQUEST_URI', $_SERVER) ? $_SERVER['REQUEST_URI'] : '';
70
71
// Get URL path from URL and split with "/"
72
$url = array_values(array_filter(explode('/', parse_url($url, PHP_URL_PATH))));
73
74
// Special hook to avoid further framework loading if this is static resource request
75
if (array_key_exists(0, $url) && $url[0] === STATIC_RESOURCE_HANDLER) {
76
    // Get full path to static resource
77
    $filename = realpath('../' . $_GET['p']);
78
79
    if (file_exists($filename)) {
80
        // Receive current ETag for resource(if present)
81
        $clientETag = array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER) ? $_SERVER['HTTP_IF_NONE_MATCH'] : '';
82
83
        // Generate ETag for resource
84
        $serverETag = filemtime($filename);
85
86
        // Set old cache headers
87
        header('Cache-Control:max-age=1800');
88
89
        // Always set new ETag header independently on further actions
90
        header('ETag:' . $serverETag);
91
92
        // Get file extension
93
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
94
95
        // If server and client ETags are equal
96
        if ($clientETag === $serverETag) {
97
            header('HTTP/1.1 304 Not Modified');
98
        } elseif (array_key_exists($extension, $mimeTypes)) {
99
            // Set mime type
100
            header('Content-type: ' . $mimeTypes[$extension]);
101
102
            // Output resource
103
            echo file_get_contents($filename);
104
        } else { // File type is not supported
105
            header('HTTP/1.0 404 Not Found');
106
        }
107
    } else { // File not found
108
        header('HTTP/1.0 404 Not Found');
109
    }
110
111
    // Avoid further request processing
112
    die();
113
}
114