Skip to content

Commit

Permalink
Function preg_replace could return null in case of an error (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
xmorave2 authored Jan 2, 2024
1 parent 36563c6 commit 9291757
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ All notable changes to this project will be documented in this file, in reverse

## Fixed

- Nothing.
- Throw exception when preg_replace in XML serialization returns null in case of invalid utf-8 string passed

## 1.0.2 - 2022-11-25

Expand Down
7 changes: 6 additions & 1 deletion src/Serialization/MarcXml.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ public static function fromString(string $marc): array
*
* @param array $record Record data
*
* @throws \Exception
* @return string
*/
public static function toString(array $record): string
Expand Down Expand Up @@ -230,11 +231,15 @@ public static function toString(array $record): string
$xml->endDocument();

// Strip illegal characters from XML:
return preg_replace(
$xmlString = preg_replace(
'/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',
'',
$xml->outputMemory(true)
);
if ($xmlString === null) {
throw new \Exception('Error processing XML');
}
return $xmlString;
}

/**
Expand Down
19 changes: 19 additions & 0 deletions tests/Serialization/MarcXmlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@

namespace VuFindTest\Marc\Serialization;

use VuFind\Marc\MarcReader;

/**
* MarcXml Test Class
*
Expand All @@ -40,6 +42,8 @@
*/
class MarcXmlTest extends \PHPUnit\Framework\TestCase
{
use \VuFind\Marc\Test\Feature\FixtureTrait;

/**
* Test rewind
*
Expand All @@ -63,4 +67,19 @@ public function testGetNextRecordWithoutFile()
$class = new \VuFind\Marc\Serialization\MarcXml();
$class->getNextRecord();
}

/**
* Test bad record
*
* @return void
* @throws \Exception
*/
public function testToStringException()
{
$xmlFile = $this->getFixture('marc/bad.mrc');
$reader = new MarcReader($xmlFile);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Error processing XML');
$xml = $reader->toFormat('MARCXML');
}
}
1 change: 1 addition & 0 deletions tests/fixtures/marc/bad.mrc

Large diffs are not rendered by default.

0 comments on commit 9291757

Please sign in to comment.