Completed
Push — master ( fb5c6c...3561cd )
by Tom
04:39
created

VerifyOrDie::filename()   C

Complexity

Conditions 8
Paths 16

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
rs 6.6037
cc 8
eloc 11
nc 16
nop 2
1
<?php
2
/**
3
 * this file is part of magerun
4
 *
5
 * @author Tom Klingenberg <https://github.com/ktomk>
6
 */
7
8
namespace N98\Util;
9
10
use InvalidArgumentException;
11
use RuntimeException;
12
13
/**
14
 * Class VerifyOrDie
15
 *
16
 * @package N98\Util
17
 */
18
class VerifyOrDie
19
{
20
    /**
21
     * Portable basename
22
     *
23
     * @param string $basename
24
     * @param string $message [optional]
0 ignored issues
show
Documentation introduced by
Should the type for parameter $message not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
25
     * @return string
26
     */
27
    public static function filename($basename, $message = null)
28
    {
29
        static::argumentType('basename', 'string', $basename);
30
        null === $message || static::argumentType('message', 'string', $message);
31
32
        # a filename must at least contain a single character
33
        if (!strlen($basename)) {
34
            self::violation($message ?: 'Filename is zero-length string');
35
        }
36
37
        # no control characters, no posix forbidden ones, no windows forbidden ones and no spaces - and not empty
38
        $pattern = '~^[^\x00-\x1F\x7F/<>:"\\|?* ]+$~';
39
        if (!preg_match($pattern, $basename)) {
40
            self::violation($message ?: sprintf("Filename %s is not portable", var_export($basename, true)));
41
        }
42
43
        if ('-' === $basename[0]) {
44
            self::violation($message ?: sprintf("Filename %s starts with a dash", var_export($basename, true)));
45
        }
46
47
        return $basename;
48
    }
49
50
    /**
51
     * @param string $name
52
     * @param string $internalType
53
     * @param mixed $subject
54
     */
55
    public static function argumentType($name, $internalType, $subject)
56
    {
57
        $actual = gettype($subject);
58
        if ($actual !== $internalType) {
59
            throw new InvalidArgumentException(
60
                sprintf('Parameter %s must be of type %s, %s given', $name, $internalType, $actual)
61
            );
62
        }
63
    }
64
65
    /**
66
     * @param string $message
67
     */
68
    private static function violation($message)
69
    {
70
        throw new RuntimeException($message);
71
    }
72
}
73