summaryrefslogtreecommitdiffstats
path: root/src/Plugin/ColumnConsistencyValidator.php
blob: dde9feacb81281a5c0e83b8c0a7ab3384a60343e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
/**
* This file is part of the League.csv library
*
* @license http://opensource.org/licenses/MIT
* @link https://github.com/thephpleague/csv/
* @version 7.2.0
* @package League.csv
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\Csv\Plugin;

use InvalidArgumentException;

/**
 *  A class to manage column consistency on data insertion into a CSV
 *
 * @package League.csv
 * @since  7.0.0
 *
 */
class ColumnConsistencyValidator
{
    /**
     * The number of column per row
     *
     * @var int
     */
    private $columns_count = -1;

    /**
     * should the class detect the column count based the inserted row
     *
     * @var bool
     */
    private $detect_columns_count = false;

    /**
     * Set Inserted row column count
     *
     * @param int $value
     *
     * @throws InvalidArgumentException If $value is lesser than -1
     *
     */
    public function setColumnsCount($value)
    {
        if (false === filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => -1]])) {
            throw new InvalidArgumentException('the column count must an integer greater or equals to -1');
        }
        $this->detect_columns_count = false;
        $this->columns_count = $value;
    }

    /**
     * Column count getter
     *
     * @return int
     */
    public function getColumnsCount()
    {
        return $this->columns_count;
    }

    /**
     * The method will set the $columns_count property according to the next inserted row
     * and therefore will also validate the next line whatever length it has no matter
     * the current $columns_count property value.
     *
     */
    public function autodetectColumnsCount()
    {
        $this->detect_columns_count = true;
    }

    /**
     * Is the submitted row valid
     *
     * @param array $row
     *
     * @return bool
     */
    public function __invoke(array $row)
    {
        if ($this->detect_columns_count) {
            $this->columns_count = count($row);
            $this->detect_columns_count = false;

            return true;
        } elseif (-1 == $this->columns_count) {
            return true;
        }

        return count($row) == $this->columns_count;
    }
}