1. Toby Inkster
  2. p5-rdf-shortcuts

Commits

Toby Inkster  committed 6033328

Serialiser

  • Participants
  • Parent commits bd4c710
  • Branches RDF-Shortcuts

Comments (0)

Files changed (1)

File lib/RDF/Shortcuts/Serialise.pm

View file
+package RDF::Shortcuts::Serialise;
+
+use 5.010;
+use common::sense;
+use constant { FALSE => 0, TRUE => 1 };
+use utf8;
+
+BEGIN {
+	$RDF::Shortcuts::Serialise::AUTHORITY = 'cpan:TOBYINK';
+	$RDF::Shortcuts::Serialise::VERSION   = '0.001';
+}
+
+use parent qw[Exporter];
+use Scalar::Util qw[blessed];
+
+our (@EXPORT, @EXPORT_OK, %EXPORT_TAGS);
+BEGIN
+{
+	@EXPORT    = qw[];
+	@EXPORT_OK = qw[serialise serialize rdf_serialise rdf_serialize rdf_string];
+}
+
+use RDF::Shortcuts::Parse qw(rdf_parse);
+use RDF::Trine;
+
+our $Has;
+BEGIN
+{
+	$Has = {};
+	foreach my $package (qw(RDF::TriN3 RDF::RDFa::Generator))
+	{
+		$@ = undef;
+		my $r = eval "use $package; ${package}->VERSION;";
+		$Has->{$package} = 1 unless $@;
+		if ($r && $Has->{$package})
+		{
+			$Has->{$package} = $r;
+		}
+	}
+}
+
+sub serialise
+{
+	my $model = shift;
+	my $fmt   = shift || 'RDFXML';
+	my %args  = @_;
+	my $s;
+	my $media;
+	
+	$args{'namespaces'} ||= $RDF::Shortcuts::Namespaces;
+
+	unless (blessed($model) && $model->isa('RDF::Trine::Model'))
+	{
+		$model = rdf_parse($model);
+	}
+
+	if ($fmt =~ /json/i)
+	{
+		$s = RDF::Trine::Serializer::RDFJSON->new;
+		$media = 'application/json';
+	}
+	elsif ($fmt =~ /(rdfa|html)/i && $Has->{'RDF::RDFa::Generator'})
+	{
+		$args{'style'} ||= 'HTML::Hidden';
+		$s = RDF::RDFa::Generator->new(%args);
+		$media = 'application/xhtml+xml';
+	}
+	elsif ($fmt =~ /xml/i)
+	{
+		$s = RDF::Trine::Serializer::RDFXML->new(namespaces=>$args{'namespaces'});
+		$media = 'application/rdf+xml';
+	}
+	elsif ($fmt =~ /canon/i)
+	{
+		$s = RDF::Trine::Serializer::NTriples::Canonical->new;
+		$media = 'text/plain';
+	}
+	elsif ($fmt =~ /n(otation)?\s*3/i && $Has->{'RDF::TriN3'})
+	{
+		$s = RDF::Trine::Serializer::Notation3->new(namespaces=>$args{'namespaces'});
+		$media = 'text/n3';
+	}
+	elsif ($fmt =~ /turtle/i or $fmt =~ /n(otation)?\s*3/i)
+	{
+		$s = RDF::Trine::Serializer::Turtle->new(namespaces=>$args{'namespaces'});
+		$media = 'text/turtle';
+	}
+	elsif ($fmt =~ /n\-?t/i)
+	{
+		$s = RDF::Trine::Serializer::NTriples->new;
+		$media = 'text/plain';
+	}
+	elsif ($fmt =~ /n\-?q/i)
+	{
+		$s = RDF::Trine::Serializer::NQuads->new;
+		$media = 'text/x-nquads';
+	}
+	else
+	{
+		$s = RDF::Trine::Serializer::RDFXML->new(namespaces=>$args{'namespaces'});
+		$media = 'application/rdf+xml';
+	}
+
+	if (ref $args{'media_type'})
+	{
+		${ $args{'media_type'} } = $media;
+	}
+	
+	return $s->serialize_model_to_string($model);
+}
+
+*serialize     = \&serialise;
+*rdf_serialise = \&serialise;
+*rdf_serialize = \&serialise;
+*rdf_string    = \&serialise;
+
+TRUE;#DAT
+
+__END__
+