Bug 9021 [QA Followup] - Switch to Koha::Object(s)
[koha.git] / Koha / Indexer / RecordWriter.pm
1 # This file is part of Koha.
2 #
3 # Copyright (C) 2013 Tamil s.a.r.l.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 package Koha::Indexer::RecordWriter;
19 use Moose;
20
21 with 'MooseX::RW::Writer::File';
22
23
24 use Carp;
25 use MARC::Batch;
26 use MARC::Record;
27 use MARC::File::XML;
28
29
30 # Is XML Stream a valid marcxml
31 # By default no => no <collection> </collection>
32 has valid => (
33     is => 'rw',
34     isa => 'Bool',
35     default => 0,
36 );
37
38
39 sub begin {
40     my $self = shift;
41     if ( $self->valid ) {
42         my $fh = $self->fh;
43         print $fh '<?xml version="1.0" encoding="UTF-8"?>', "\n", '<collection>', "\n";
44     }
45 }
46
47
48 sub end {
49     my $self = shift;
50     my $fh = $self->fh;
51     if ( $self->valid ) {
52         print $fh '</collection>', "\n";
53     }
54     $fh->flush();
55 }
56
57
58
59 #
60 # Sent record is rather a MARC::Record object or an marcxml string
61 #
62 sub write {
63     my ($self, $record) = @_;
64
65     $self->count( $self->count + 1 );
66
67     my $fh  = $self->fh;
68     my $xml = ref($record) eq 'MARC::Record'
69               ? $record->as_xml_record() : $record;
70     $xml =~ s/<\?xml version="1.0" encoding="UTF-8"\?>\n//g if $self->valid;
71     print $fh $xml;
72 }
73
74 __PACKAGE__->meta->make_immutable;
75
76 1;