| 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 7.2.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 |
namespace League\Csv\Plugin; |
| 14 |
|
| 15 |
use InvalidArgumentException; |
| 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 |
* |
| 23 |
*/ |
| 24 |
class ColumnConsistencyValidator |
| 25 |
{ |
| 26 |
/** |
| 27 |
* The number of column per row |
| 28 |
* |
| 29 |
* @var int |
| 30 |
*/ |
| 31 |
private $columns_count = -1; |
| 32 |
|
| 33 |
/** |
| 34 |
* should the class detect the column count based the inserted row |
| 35 |
* |
| 36 |
* @var bool |
| 37 |
*/ |
| 38 |
private $detect_columns_count = false; |
| 39 |
|
| 40 |
/** |
| 41 |
* Set Inserted row column count |
| 42 |
* |
| 43 |
* @param int $value |
| 44 |
* |
| 45 |
* @throws InvalidArgumentException If $value is lesser than -1 |
| 46 |
* |
| 47 |
*/ |
| 48 |
public function setColumnsCount($value) |
| 49 |
{ |
| 50 |
if (false === filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => -1]])) { |
| 51 |
throw new InvalidArgumentException('the column count must an integer greater or equals to -1'); |
| 52 |
} |
| 53 |
$this->detect_columns_count = false; |
| 54 |
$this->columns_count = $value; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Column count getter |
| 59 |
* |
| 60 |
* @return int |
| 61 |
*/ |
| 62 |
public function getColumnsCount() |
| 63 |
{ |
| 64 |
return $this->columns_count; |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* The method will set the $columns_count property according to the next inserted row |
| 69 |
* and therefore will also validate the next line whatever length it has no matter |
| 70 |
* the current $columns_count property value. |
| 71 |
* |
| 72 |
*/ |
| 73 |
public function autodetectColumnsCount() |
| 74 |
{ |
| 75 |
$this->detect_columns_count = true; |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Is the submitted row valid |
| 80 |
* |
| 81 |
* @param array $row |
| 82 |
* |
| 83 |
* @return bool |
| 84 |
*/ |
| 85 |
public function __invoke(array $row) |
| 86 |
{ |
| 87 |
if ($this->detect_columns_count) { |
| 88 |
$this->columns_count = count($row); |
| 89 |
$this->detect_columns_count = false; |
| 90 |
|
| 91 |
return true; |
| 92 |
} elseif (-1 == $this->columns_count) { |
| 93 |
return true; |
| 94 |
} |
| 95 |
|
| 96 |
return count($row) == $this->columns_count; |
| 97 |
} |
| 98 |
} |
| 99 |
|