Issues (33)

src/Traits/DirectoryTrait.php (2 issues)

1
<?php
2
declare(strict_types=1);
3
4
namespace Utilities\Router\Traits;
5
6
/**
7
 * DirectoryTrait class
8
 *
9
 * @link    https://github.com/utilities-php/router
10
 * @author  Shahrad Elahi (https://github.com/shahradelahi)
11
 * @license https://github.com/utilities-php/router/blob/master/LICENSE (MIT License)
12
 */
13
trait DirectoryTrait
14
{
15
16
    /**
17
     * Directories.
18
     *
19
     * @var array
20
     */
21
    private array $directories = [];
22
23
    /**
24
     * Add directories to the autoloader
25
     *
26
     * @param array $directories e.g. ["key" => __dir__ . "/../key/"]
27
     * @return void
28
     */
29
    public function addDirectory(array $directories): void
30
    {
31
        foreach ($directories as $key => $directory) {
32
            if (!is_dir($directory)) {
33
                throw new \RuntimeException(
34
                    'The directory ' . $directory . ' does not exist'
35
                );
36
            }
37
38
            $this->directories[$key] = $directory;
39
        }
40
    }
41
42
    /**
43
     * Search for the directory
44
     *
45
     * @param array $request
46
     * @param bool $insensitive
47
     * @return void
48
     */
49
    private function findDirectory(array $request, bool $insensitive): void
50
    {
51
        if (($directory = $this->getDirectory($request['sector'], $insensitive)) !== false) {
0 ignored issues
show
The condition $directory = $this->getD...$insensitive) !== false is always false.
Loading history...
52
            if (!str_ends_with($directory, '/')) {
53
                $directory .= '/';
54
            }
55
56
            $filename = str_contains($request['method'], '.') ? $request['method'] : $request['method'] . '.php';
57
            $file = $directory . $filename;
58
59
            if (file_exists($file)) {
60
                $fileMime = mime_content_type($file);
61
62
                if ($fileMime != 'text/php') {
63
                    header('Content-Type: ' . $fileMime);
64
                }
65
66
                include_once $file;
67
                die(200);
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
68
            }
69
        }
70
    }
71
72
    /**
73
     * Get the directories
74
     *
75
     * @param ?string $key
76
     * @param bool $insensitive
77
     * @return string|false
78
     */
79
    private function getDirectory(?string $key, bool $insensitive): string|false
80
    {
81
        if (!is_string($key)) {
82
            return false;
83
        }
84
85
        if ($insensitive) {
86
            return array_change_key_case($this->directories)[strtolower($key)] ?? false;
87
        }
88
89
        return $this->directories[$key] ?? false;
90
    }
91
92
}