44
55use File_MARCXML ;
66use Scriptotek \Marc \Collection ;
7+ use Scriptotek \Marc \Exceptions \RecordNotFound ;
78use Scriptotek \Marc \Exceptions \XmlException ;
89use Scriptotek \Marc \Factory ;
910use SimpleXMLElement ;
@@ -15,15 +16,30 @@ class XmlImporter
1516 /* var SimpleXMLElement */
1617 protected $ source ;
1718
19+ /**
20+ * XmlImporter constructor.
21+ *
22+ * @param string|SimpleXMLElement $data Filename, XML string or SimpleXMLElement object
23+ * @param string $ns URI or prefix of the namespace
24+ * @param bool $isPrefix TRUE if $ns is a prefix, FALSE if it's a URI; defaults to FALSE
25+ * @param string $factory (optional) Object factory, probably no need to set this outside testing.
26+ */
1827 public function __construct ($ data , $ ns = '' , $ isPrefix = false , $ factory = null )
1928 {
2029 $ this ->factory = isset ($ factory ) ? $ factory : new Factory ();
2130
31+ if (is_a ($ data , SimpleXMLElement::class)) {
32+ $ this ->source = $ data ;
33+ return ;
34+ }
35+
2236 if (strlen ($ data ) < 256 && file_exists ($ data )) {
2337 $ data = file_get_contents ($ data );
2438 }
2539
40+ // Store errors internally so that we can fetch them with libxml_get_errors() later
2641 libxml_use_internal_errors (true );
42+
2743 $ this ->source = simplexml_load_string ($ data , 'SimpleXMLElement ' , 0 , $ ns , $ isPrefix );
2844 if (false === $ this ->source ) {
2945 throw new XmlException (libxml_get_errors ());
@@ -69,6 +85,22 @@ public function getRecords()
6985 return [];
7086 }
7187
88+ public function getFirstRecord ()
89+ {
90+ $ records = $ this ->getRecords ();
91+ if (!count ($ records )) {
92+ throw new RecordNotFound ();
93+ }
94+
95+ $ record = $ records [0 ];
96+
97+ list ($ prefix , $ ns ) = $ this ->getMarcNamespace ($ record ->getNamespaces (true ));
98+
99+ $ parser = $ this ->factory ->make ('File_MARCXML ' , $ record , File_MARCXML::SOURCE_SIMPLEXMLELEMENT , $ ns );
100+
101+ return (new Collection ($ parser ))->$ this ->getFirstRecord ();
102+ }
103+
72104 public function getCollection ()
73105 {
74106 $ records = $ this ->getRecords ();
@@ -77,6 +109,7 @@ public function getCollection()
77109 }
78110
79111 list ($ prefix , $ ns ) = $ this ->getMarcNamespace ($ records [0 ]->getNamespaces (true ));
112+
80113 $ pprefix = empty ($ prefix ) ? '' : "$ prefix: " ;
81114
82115 $ records = array_map (function (SimpleXMLElement $ record ) {
0 commit comments