Completed
Push — master ( db44e7...3e1fbd )
by Tom
04:39
created

VerifyOrDie::violation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * this file is part of magerun
4
 *
5
 * @author Tom Klingenberg <https://github.com/ktomk>
6
 */
7
namespace N98\Util;
8
9
use InvalidArgumentException;
10
use RuntimeException;
11
12
/**
13
 * Class VerifyOrDie
14
 *
15
 * @package N98\Util
16
 */
17
class VerifyOrDie
18
{
19
    /**
20
     * Portable basename
21
     *
22
     * @param string $basename
23
     * @param string $message [optional]
24
     * @return string
25
     */
26
    public static function filename($basename, $message = null)
27
    {
28
        static::argumentType('basename', 'string', $basename);
29
        null === $message || static::argumentType('message', 'string', $message);
30
31
        # a filename must at least contain a single character
32
        if (!strlen($basename)) {
33
            self::violation($message ?: 'Filename is zero-length string');
34
        }
35
36
        # no control characters, no posix forbidden ones, no windows forbidden ones and no spaces - and not empty
37
        $pattern = '~^[^\x00-\x1F\x7F/<>:"\\|?* ]+$~';
38
        if (!preg_match($pattern, $basename)) {
39
            self::violation($message ?: sprintf("Filename %s is not portable", var_export($basename, true)));
40
        }
41
42
        if ('-' === $basename[0]) {
43
            self::violation($message ?: sprintf("Filename %s starts with a dash", var_export($basename, true)));
44
        }
45
46
        return $basename;
47
    }
48
49
    /**
50
     * @param string $name
51
     * @param string $internalType
52
     * @param mixed $subject
53
     */
54
    public static function argumentType($name, $internalType, $subject)
55
    {
56
        $actual = gettype($subject);
57
        if ($actual !== $internalType) {
58
            throw new InvalidArgumentException(
59
                sprintf('Parameter %s must be of type %s, %s given', $name, $internalType, $actual)
60
            );
61
        }
62
    }
63
64
    private static function violation($message)
65
    {
66
        throw new RuntimeException($message);
67
    }
68
}
69