Completed
Pull Request — master (#210)
by ignace nyamagana
06:26
created

ValidatorTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 1
dl 0
loc 63
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A filterControl() 0 8 2
A filterInteger() 0 8 2
A filterColumnNames() 0 12 3
1
<?php
2
/**
3
* This file is part of the League.csv library
4
*
5
* @license http://opensource.org/licenses/MIT
6
* @link https://github.com/thephpleague/csv/
7
* @version 9.0.0
8
* @package League.csv
9
*
10
* For the full copyright and license information, please view the LICENSE
11
* file that was distributed with this source code.
12
*/
13
declare(strict_types=1);
14
15
namespace League\Csv;
16
17
/**
18
 *  An abstract class to enable basic CSV manipulation
19
 *
20
 * @package  League.csv
21
 * @since    9.0.0
22
 * @author   Ignace Nyamagana Butera <[email protected]>
23
 * @internal Use to validate incoming data
24
 */
25
trait ValidatorTrait
26
{
27
    /**
28
     * Filter Csv control character
29
     *
30
     * @param string $char Csv control character
31
     * @param string $type Csv control character type
32
     *
33
     * @throws InvalidArgumentException If the Csv control character is not one character only.
34
     *
35
     * @return string
36
     */
37 6
    protected function filterControl(string $char, string $type)
38
    {
39 6
        if (1 == strlen($char)) {
40 6
            return $char;
41
        }
42
43 6
        throw new InvalidArgumentException(sprintf('The %s must be a single character', $type));
44
    }
45
46
    /**
47
     * Validate an integer
48
     *
49
     * @param int    $value
50
     * @param int    $min_value
51
     * @param string $error_message
52
     *
53
     * @throws InvalidArgumentException If the value is invalid
54
     *
55
     * @return int
56
     */
57 80
    protected function filterInteger(int $value, int $min_value, string $error_message): int
58
    {
59 80
        if ($value < $min_value) {
60 10
            throw new InvalidArgumentException($error_message);
61
        }
62
63 72
        return $value;
64
    }
65
66
    /**
67
     * Validates the array to be used by the fetchAssoc method
68
     *
69
     * @param array $keys
70
     *
71
     * @throws InvalidArgumentException If the submitted array fails the assertion
72
     *
73
     * @return array
74
     */
75 36
    protected function filterColumnNames(array $keys): array
76
    {
77 36
        if (empty($keys)) {
78 2
            return $keys;
79
        }
80
81 34
        if ($keys !== array_unique(array_filter($keys, 'is_string'))) {
82 2
            throw new InvalidArgumentException('Use a flat array with unique string values');
83
        }
84
85 32
        return $keys;
86
    }
87
}
88