1 | <?php |
||
18 | class Value |
||
19 | { |
||
20 | /** @var bool */ |
||
21 | private $inQuotes = false; |
||
22 | /** @var bool */ |
||
23 | private $wasQuoted = false; |
||
24 | /** @var ValueParserInterface[] */ |
||
25 | private $valueParsers = []; |
||
26 | /** @var string */ |
||
27 | private $content = ''; |
||
28 | /** @var bool */ |
||
29 | private $isNull = false; |
||
30 | /** @var bool */ |
||
31 | private $hasContent = false; |
||
32 | |||
33 | /** |
||
34 | * Value constructor. |
||
35 | * |
||
36 | * @param array $valueParsers |
||
37 | */ |
||
38 | 15 | public function __construct(array $valueParsers = []) |
|
43 | |||
44 | /** |
||
45 | * @param bool $quoted |
||
46 | * |
||
47 | * @return static |
||
48 | */ |
||
49 | 12 | public function setInQuotes($quoted) |
|
50 | { |
||
51 | 12 | $this->inQuotes = $quoted; |
|
52 | 12 | if ($quoted) { |
|
53 | 12 | $this->wasQuoted = true; |
|
54 | } |
||
55 | 12 | return $this; |
|
56 | } |
||
57 | |||
58 | /** |
||
59 | * @param string $content |
||
60 | * |
||
61 | * @return static |
||
62 | */ |
||
63 | 14 | public function addContent($content) |
|
64 | { |
||
65 | 14 | if (!$this->inQuotes && $this->wasQuoted) { |
|
66 | 2 | throw new RuntimeException( |
|
67 | 2 | "Invalid CSV: Attempting to add a string to a field that was in quotes: " . $this->content . $content |
|
68 | ); |
||
69 | } |
||
70 | 14 | $this->content .= $content; |
|
71 | 14 | $this->isNull = false; |
|
72 | 14 | $this->hasContent = true; |
|
73 | 14 | return $this; |
|
74 | } |
||
75 | |||
76 | /** |
||
77 | * Indicated that this value is null |
||
78 | */ |
||
79 | 6 | public function setIsNull() |
|
84 | |||
85 | /** |
||
86 | * @return mixed |
||
87 | */ |
||
88 | 12 | public function getValue() |
|
89 | { |
||
90 | 12 | if ($this->wasQuoted) { |
|
91 | 10 | return $this->content; |
|
92 | 8 | } elseif ($this->isNull) { |
|
93 | 6 | return null; |
|
94 | } else { |
||
95 | 8 | foreach ($this->valueParsers as $valueParser) { |
|
96 | 1 | if ($valueParser->canParseValue($this->content)) { |
|
97 | 1 | return $valueParser->parseValue($this->content); |
|
98 | } |
||
99 | } |
||
100 | } |
||
101 | |||
102 | 8 | return $this->content; |
|
103 | } |
||
104 | |||
105 | /** |
||
106 | * Reset the state |
||
107 | */ |
||
108 | 15 | public function reset() |
|
116 | |||
117 | /** |
||
118 | * @return bool |
||
119 | */ |
||
120 | 13 | public function isInQuotes() |
|
124 | |||
125 | /** |
||
126 | * @return bool |
||
127 | */ |
||
128 | 6 | public function wasQuoted() |
|
132 | |||
133 | /** |
||
134 | * @return bool |
||
135 | */ |
||
136 | 13 | public function isEmpty() |
|
140 | } |
||
141 |