Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.86% covered (success)
92.86%
13 / 14
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Guard
92.86% covered (success)
92.86%
13 / 14
50.00% covered (danger)
50.00%
1 / 2
8.02
0.00% covered (danger)
0.00%
0 / 1
 isSafePath
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 unslash
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
6.04
1<?php
2/**
3 * Jingga
4 *
5 * PHP Version 8.1
6 *
7 * @package   phpOMS\Security
8 * @copyright Dennis Eichhorn
9 * @license   OMS License 2.0
10 * @version   1.0.0
11 * @link      https://jingga.app
12 */
13declare(strict_types=1);
14
15namespace phpOMS\Security;
16
17use phpOMS\System\File\FileUtils;
18
19/**
20 * Php code security class.
21 *
22 * This can be used to guard against certain vulnerabilities
23 *
24 * @package phpOMS\Security
25 * @license OMS License 2.0
26 * @link    https://jingga.app
27 * @since   1.0.0
28 */
29final class Guard
30{
31    /**
32     * Base path for the application
33     *
34     * @var string
35     * @since 1.0.0
36     */
37    public static string $BASE_PATH = __DIR__ . '/../../';
38
39    /**
40     * Make sure a path is part of a base path
41     *
42     * This can be used to verify if a path goes outside of the allowed path bounds
43     *
44     * @param string $path Path to check
45     * @param string $base Base path
46     *
47     * @return bool
48     *
49     * @since 1.0.0
50     */
51    public static function isSafePath(string $path, string $base = '') : bool
52    {
53        return \str_starts_with(
54            FileUtils::absolute($path),
55            FileUtils::absolute(empty($base) ? self::$BASE_PATH : $base)
56        );
57    }
58
59    /**
60     * Remove slashes from a string or array
61     *
62     * @template T of string|array
63     *
64     * @param T $data Data to unslash
65     *
66     * @return (T is string ? string : array)
67     *
68     * @since 1.0.0
69     */
70    public static function unslash(string | array $data) : string|array
71    {
72        if (\is_array($data)) {
73            $result = [];
74            foreach ($data as $key => $value) {
75                $result[$key] = \is_string($value) || \is_array($value)
76                    ? self::unslash($value)
77                    : $value;
78            }
79
80            return $result;
81        } elseif (\is_string($data)) {
82            return \stripslashes($data);
83        }
84
85        return $data;
86    }
87}