Skip to content

Commit c29c3b3

Browse files
committed
Add mapSubfields helper method on Field
1 parent 1f1ce3d commit c29c3b3

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/Fields/Field.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ public function __get($key)
5353
}
5454
}
5555

56+
public function __toString()
57+
{
58+
return $this->field->__toString();
59+
}
60+
5661
/**
5762
* @param string|string[] $codes
5863
* @return array
@@ -93,6 +98,10 @@ protected function toString($codes, $glue = ' ')
9398
*/
9499
public function sf($code, $default = null)
95100
{
101+
102+
// In PHP, ("a" == 0) will evaluate to TRUE, so it's actually very important that we ensure type here!
103+
$code = (string) $code;
104+
96105
$subfield = $this->getSubfield($code);
97106
if (!$subfield) {
98107
return $default;
@@ -101,6 +110,25 @@ public function sf($code, $default = null)
101110
return trim($subfield->getData());
102111
}
103112

113+
public function mapSubFields($map, $includeNullValues = false)
114+
{
115+
$o = [];
116+
foreach ($map as $code => $prop) {
117+
$value = $this->sf($code);
118+
119+
foreach ($this->getSubfields() as $q) {
120+
if ($q->getCode() == $code) {
121+
$value = $q->getData();
122+
}
123+
}
124+
125+
if (!is_null($value) || $includeNullValues) {
126+
$o[$prop] = $value;
127+
}
128+
}
129+
return $o;
130+
}
131+
104132
public static function makeFieldObject(Record $record, $tag, $pcre=false)
105133
{
106134
$field = $record->getField($tag, $pcre);

tests/FieldsTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,27 @@ public function testIsbn()
2727
);
2828
}
2929

30+
public function testMapSubfields()
31+
{
32+
$record = Record::fromString('<?xml version="1.0" encoding="UTF-8" ?>
33+
<record xmlns="http://www.loc.gov/MARC21/slim">
34+
<leader>99999cam a2299999 u 4500</leader>
35+
<datafield tag="700" ind1="1" ind2=" ">
36+
<subfield code="a">Levy, Silvio</subfield>
37+
<subfield code="0">(NO-TrBIB)x90579165</subfield>
38+
</datafield>
39+
</record>');
40+
41+
$this->assertEquals([
42+
'name' => 'Levy, Silvio',
43+
'identifier' => '(NO-TrBIB)x90579165',
44+
], $record->getField('700')->mapSubfields([
45+
'a' => 'name',
46+
'b' => 'numeration',
47+
'0' => 'identifier',
48+
]));
49+
}
50+
3051
public function test020withoutA()
3152
{
3253
$source = '<?xml version="1.0" encoding="UTF-8" ?>

0 commit comments

Comments
 (0)