-
Notifications
You must be signed in to change notification settings - Fork 4
/
LineReader.php
112 lines (99 loc) · 2.37 KB
/
LineReader.php
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
/**
* Created by PhpStorm.
* User: jderay
* Date: 9/22/14
* Time: 9:48 PM
*/
namespace Giftcards\FixedWidth;
use Giftcards\FixedWidth\Spec\FieldSpec;
use Giftcards\FixedWidth\Spec\RecordSpec;
use Giftcards\FixedWidth\Spec\SpecNotFoundException;
use Giftcards\FixedWidth\Spec\ValueFormatter\ValueFormatterInterface;
class LineReader implements \ArrayAccess
{
protected $spec;
protected $line;
protected $formatter;
public function __construct(
LineInterface $line,
RecordSpec $spec,
ValueFormatterInterface $formatter
) {
$this->line = $line;
$this->spec = $spec;
$this->formatter = $formatter;
}
/**
* @param $fieldName
* @return mixed
*/
public function getField($fieldName)
{
$fieldSpec = $this->spec->getFieldSpec($fieldName);
return $this->formatter->formatFromFile($fieldSpec, $this->line->get($fieldSpec->getSlice()));
}
/**
* @return array
*/
public function getFields()
{
$fieldSpecs = $this->spec->getFieldSpecs();
$formatter = $this->formatter;
$line = $this->line;
return array_map(function(FieldSpec $fieldSpec) use ($line, $formatter)
{
return $formatter->formatFromFile($fieldSpec, $line->get($fieldSpec->getSlice()));
}, $fieldSpecs);
}
/**
* @return RecordSpec
*/
public function getSpec()
{
return $this->spec;
}
/**
* @return Line
*/
public function getLine()
{
return $this->line;
}
/**
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
try {
$this->spec->getFieldSpec($offset);
return true;
} catch(SpecNotFoundException $e) {
return false;
}
}
/**
* @param mixed $offset
* @return array|mixed
*/
public function offsetGet($offset)
{
return $this->getField($offset);
}
/**
* @param mixed $offset
* @param mixed $value
*/
public function offsetSet($offset, $value)
{
throw new \BadMethodCallException('a line reader is read only.');
}
/**
* @param mixed $offset
*/
public function offsetUnset($offset)
{
throw new \BadMethodCallException('a line reader is read only.');
}
}