Skip to content

Commit

Permalink
Add support for serializing prefixnames when serializer namespaces ar…
Browse files Browse the repository at this point in the history
…e set (#53).
  • Loading branch information
kasei committed Apr 9, 2016
1 parent 2279b6d commit a165b4a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
27 changes: 24 additions & 3 deletions lib/AtteanX/Serializer/SPARQL.pm
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,11 @@ L<IO::Handle> object C<< $fh >>.
my $newline = 1;
my $semicolon = 0;
my $need_space = 0;
my $ns = $self->namespaces;
my $parser = Attean->get_parser('SPARQLLex')->new();

my $last;

while (my $t = $iter->next()) {
my $type = $t->type;

Expand Down Expand Up @@ -124,10 +128,27 @@ L<IO::Handle> object C<< $fh >>.
$io->print($t->value);
$need_space++;
} elsif ($type == IRI) {
my $value = $t->value;
my $ser = '<' . $value . '>';
if ($ns) {
NSLOOP: foreach my $p ($ns->list_prefixes) {
my $prefix = $ns->namespace_uri($p)->as_string;
if (substr($value, 0, length($prefix)) eq $prefix) {
# now verify that the prefixname is valid SPARQL syntax by re-parsing it
my $pname = join(':', $p, substr($value, length($prefix)));
my $b = $pname;
$b = encode('UTF-8', $b, Encode::FB_CROAK);
my ($pnt) = $parser->parse_list_from_bytes($b);
if (blessed($pnt) and $pnt->type == PREFIXNAME) {
$ser = $pname;
}
last NSLOOP;
}
}
}

# TODO: escape
$io->print('<');
$io->print($t->value);
$io->print('>');
$io->print($ser);
$need_space++;
} elsif ($type == PREFIXNAME) {
my $args = $t->args;
Expand Down
11 changes: 11 additions & 0 deletions t/serializer-sparql.t
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,17 @@ subtest 'Regressions' => sub {
}
};

subtest 'AbbreviatingSerializer' => sub {
my $map = URI::NamespaceMap->new( { foaf => iri('http://xmlns.com/foaf/0.1/') } );
my $a = Attean->get_parser('SPARQL')->parse('PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT * WHERE { <http://example.org/people/alice> a foaf:Person ; foaf:name ?name }');
my $s = Attean->get_serializer('SPARQL')->new( namespaces => $map );
my $i = $a->sparql_tokens;
my $bytes = $s->serialize_iter_to_bytes($i);
like($bytes, qr<http://example.org/people/alice>);
like($bytes, qr/foaf:Person/);
like($bytes, qr/foaf:name [?]name/);
};

done_testing();

sub warn_token_stream {
Expand Down

0 comments on commit a165b4a

Please sign in to comment.