Completed
Push — master ( e7f403...4be255 )
by ignace nyamagana
04:16 queued 02:19
created

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