Completed
Push — master ( 75298d...3aa483 )
by
unknown
02:10
created

ColumnNameSanitizer::sanitizeArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\QueryBuilder;
4
5
use Spatie\QueryBuilder\Exceptions\InvalidColumnName;
6
7
class ColumnNameSanitizer
8
{
9
    /**
10
     * Based on maximum column name length.
11
     */
12
    public const MAX_COLUMN_NAME_LENGTH = 64;
13
14
    /**
15
     * Column names are alphanumeric strings that can contain
16
     * underscores (`_`) but can't start with a number.
17
     */
18
    private const VALID_COLUMN_NAME_REGEX = "/^(?![0-9])[A-Za-z0-9_-]*$/";
19
20
    public static function sanitize(string $column): string
21
    {
22
        if (strlen($column) > self::MAX_COLUMN_NAME_LENGTH) {
23
            throw InvalidColumnName::columnNameTooLong($column, self::MAX_COLUMN_NAME_LENGTH);
24
        }
25
26
        if (! preg_match(self::VALID_COLUMN_NAME_REGEX, $column)) {
27
            throw InvalidColumnName::invalidCharacters($column);
28
        }
29
30
        return $column;
31
    }
32
33
    public static function sanitizeArray(array $columns): array
34
    {
35
        return array_map([self::class, 'sanitize'], $columns);
36
    }
37
}
38