Completed
Push — master ( be6e2d...e7f403 )
by ignace nyamagana
02:20
created

ColumnConsistency::autodetect()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
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\Plugin;
16
17
use League\Csv\ValidatorTrait;
18
19
/**
20
 *  A class to manage column consistency on data insertion into a CSV
21
 *
22
 * @package League.csv
23
 * @since   7.0.0
24
 * @author  Ignace Nyamagana Butera <[email protected]>
25
 *
26
 */
27
class ColumnConsistency
28
{
29
    use ValidatorTrait;
30
31
    /**
32
     * The number of column per record
33
     *
34
     * @var int
35
     */
36
    protected $columns_count = -1;
37
38
    /**
39
     * should the class detect the column count based on the inserted record
40
     *
41
     * @var bool
42
     */
43
    protected $detect_columns_count = false;
44
45
    /**
46
     * Set Inserted record column count
47
     *
48
     * @param int $value
49
     *
50
     * @return self
51
     */
52 4
    public function columnsCount(int $value): self
53
    {
54 4
        $clone = clone $this;
55 4
        $clone->columns_count = $this->filterMinRange($value, 0, 'The column count must be greater or equal to 0');
56 2
        $clone->detect_columns_count = false;
57
58 2
        return $clone;
59
    }
60
61
    /**
62
     * The method will set the $columns_count property
63
     * according to the next inserted record and therefore
64
     * will also validate it.
65
     *
66
     * @return self
67
     */
68 2
    public function autodetect(): self
69
    {
70 2
        $clone = clone $this;
71 2
        $clone->detect_columns_count = true;
72 2
        $clone->columns_count = -1;
73
74 2
        return $clone;
75
    }
76
77
    /**
78
     * Tell whether the submitted record is valid
79
     *
80
     * @param array $record
81
     *
82
     * @return bool
83
     */
84 4
    public function __invoke(array $record): bool
85
    {
86 4
        $count = count($record);
87 4
        if ($this->detect_columns_count) {
88 2
            $this->detect_columns_count = false;
89 2
            $this->columns_count = $count;
90
91 2
            return true;
92
        }
93
94 4
        return $count === $this->columns_count;
95
    }
96
}
97