view lib/Benzin/Bugzilla/XmlWriter.pm @ 11:4eb9fdf4efa9

refactoring, non-working bookings
author cin
date Mon, 07 Sep 2015 19:18:21 +0300
parents 14a966369278
children 52b34ea50eff
line wrap: on
line source

package Benzin::Bugzilla::XmlWriter;

our %Transform = (
	'Benzin::Bugzilla::Bug'        => 'WriteBug',
	'Benzin::Bugzilla::BugComment' => 'WriteBugComment',
	'HASH'                         => 'WriteHash',
	'DateTime'                     => 'WriteTJ3DateTime',
	-plain                         => 'WriteValue',
	-default                       => 'WriteValue'
);

use IMPL::Const qw(:prop);
use IMPL::declare {
	require => {
		XMLWriter  => 'XML::Writer',
		Bug        => 'Benzin::Bugzilla::Bug',
		BugComment => 'Benzin::Bugzilla::BugComment',
	},
	base => [
		'IMPL::Transform' => sub { %Transform }
	],
	props => [
		_writer        => PROP_RW,
		timereports    => PROP_RW,
		timeresolution => PROP_RW
	]
};

use fields qw(_writer);

sub CTOR {
	my SELF $this = shift;

	$this->_writer( XMLWriter->new(@_) );
}

sub WriteBugList {
	my SELF $this = shift;
	my $bugs = shift || [];
	my $writer = $this->_writer;

	$writer->xmlDecl("UTF-8");
	$writer->startTag("bugzilla");

	foreach my $bug (@$bugs) {
		$writer->startTag("bug");
		$this->WriteBug($bug);
		$writer->endTag();
	}

	$writer->endTag();

}

sub WriteBug {
	my SELF $this = shift;
	my $value     = shift;
	my $writer    = $this->_writer;

	foreach my $field ( @{ Bug->BUG_FIELDS } ) {
		next unless $value->{$field};
		$this->WriteElement( $field, $value->{$field} );
	}
	$this->WriteElement( 'time',
		$value->GetTimeReports( $this->timeresolution ) )
	  if $this->timereports;
}

sub WriteBugComment {
	my SELF $this = shift;
	my $value     = shift;
	my $writer    = $this->_writer;

	foreach my $field ( @{ BugComment->COMMENT_FIELDS } ) {
		next unless $value->{$field};
		$this->WriteElement( $field, $value->{$field} );
	}
}

sub WriteHash {
	my SELF $this = shift;
	my $value = shift;

	while ( my ( $k, $v ) = each %$value ) {
		$this->WriteElement( $k, $v );
	}
}

sub WriteElement {
	my SELF $this = shift;
	my ( $name, $data ) = @_;
	my $writer = $this->_writer;

	my @values =
	     ref($data)
	  && ref($data) eq 'ARRAY'
	  ? @{$data}
	  : $data;

	foreach my $v (@values) {
		$writer->startTag($name);
		$this->Transform($v);
		$writer->endTag;
	}
}

sub WriteValue {
	my SELF $this = shift;
	my $value = shift;

	$this->_writer->characters($value) if defined $value;
}

sub WriteTJ3DateTime {
	my SELF $this = shift;
    my $value = shift;

    $this->_writer->characters($value->strftime('%F-%T')) if defined $value;
}

1;