Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions src/RecordManager/Base/Utils/LineBasedMarcFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
use function assert;
use function count;
use function intval;
use function is_string;
use function strlen;

/**
Expand Down Expand Up @@ -105,6 +106,8 @@ public function getIllegalXmlCharacterCount(): int
*/
public function convertLineBasedMarcToXml(string $metadata): string
{
$this->badChars = 0;

$xml = simplexml_load_string(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n"
. '<collection><record></record></collection>'
Expand Down Expand Up @@ -138,6 +141,7 @@ public function convertLineBasedMarcToXml(string $metadata): string
$line = substr($line, 0, strlen($line) - 1);
}
}
$line = $this->stripIllegalChars($line);
if (!$line) {
continue;
}
Expand Down Expand Up @@ -186,7 +190,7 @@ public function convertLineBasedMarcToXml(string $metadata): string
while ($subs) {
$code = array_shift($subs);
$value = array_shift($subs);
if ('' === $value) {
if ('' === $code || '' === $value) {
continue;
}
$subfield = $field->addChild(
Expand All @@ -197,13 +201,31 @@ public function convertLineBasedMarcToXml(string $metadata): string
}
}
}
// Strip illegal characters from XML, and save a count for reference:
return preg_replace(
$result = $record->asXML();
return is_string($result) ? $result : '';
}

/**
* Strip illegal characters from XML.
*
* @param string $str String to clean up.
*
* @return string
*/
protected function stripIllegalChars(string $str): string
{
$badChars = 0;
$str = preg_replace(
'/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',
'',
$record->asXML(),
$str,
-1,
$this->badChars
$badChars
) ?? '';

// Increase the counter for reference:
$this->badChars += $badChars;

return $str;
}
}
Loading