MT#12273 '_forcearray' attr for Data::HAL's asjson

The Data::HAL respresentation of a GET collection page provides a 'link' and 'embedded' field of the page's items. In the case the page contains a single item only, the current Data::HAL implementation does not create arrays. This is less consistent and complicates test cases at least.

Change-Id: I3ad0f2f0bf8945c2c4b6743bd2b904a14353118f
changes/27/1527/1
Rene Krenn 11 years ago
parent 9cbf237d64
commit e5670fb52f

@ -10,7 +10,8 @@ use failures qw(Data::HAL::InvalidJSON);
use HTTP::Headers::Util qw(join_header_words);
use JSON qw();
use Moo; # has
use Safe::Isa qw($_isa);
#use Safe::Isa qw($_isa);
use Safe::Isa qw($_can $_isa);
use Scalar::Util qw(reftype);
use Types::Standard qw(ArrayRef Bool HashRef InstanceOf Str);
@ -31,12 +32,34 @@ has('relation', is => 'rw', isa => InstanceOf['Data::HAL::URI'], coerce => $uri_
has('_nsmap', is => 'rw', isa => InstanceOf['Data::HAL::URI::NamespaceMap']);
has('_recursing', is => 'ro', isa => Bool);
has('_forcearray', is => 'rw', isa => Bool, default => 0); #array of embedded items, even if only one
sub BUILD {
my ($self) = @_;
$self->_expand_curies unless $self->_recursing;
return;
}
#for links array containig undef elements
#around 'BUILDARGS' => sub {
# my $orig = shift;
# my $class = shift;
# my $params;
# if ((scalar @_) == 1) {
# ($params) = @_;
# } else {
# $params = { @_ };
# }
# if (reftype $params eq reftype {} && exists $params->{links}) {
# my @links = ();
# foreach my $l (@{ $params->{links} }) {
# push(@links,$l) if defined $l;
# }
# $params->{links} = \@links;
# }
# $class->$orig($params);
#};
sub from_json {
my ($self, $json, $relation) = @_;
my $nested = clone JSON::from_json($json);
@ -152,7 +175,11 @@ sub _to_nested {
push @{ $hal->{"_$prop"}{$r} }, $attr, $nested;
}
} else {
$hal->{"_$prop"}{$r} = $nested;
if ($p->$_can('_forcearray') and $p->_forcearray) {
$hal->{"_$prop"}{$r} = [ $nested ];
} else {
$hal->{"_$prop"}{$r} = $nested;
}
}
}
}

@ -8,7 +8,7 @@ use Log::Any qw($log);
use MIME::Type qw();
use Moo; # has
use Safe::Isa qw($_can $_isa);
use Types::Standard qw(InstanceOf Str);
use Types::Standard qw(InstanceOf Str Bool);
our $VERSION = '1.000';
@ -32,6 +32,8 @@ has('profile', is => 'rw', isa => InstanceOf['Data::HAL::URI'], coerce => $u
has('title', is => 'rw', isa => Str);
has('hreflang', is => 'rw', isa => Str);
has('_forcearray', is => 'rw', isa => Bool, default => 0); #array of link items, even if only one
sub BUILD {
my ($self) = @_;
if ($self->deprecation) {
@ -51,6 +53,7 @@ sub _to_nested {
}
}
my $r = delete $hal->{relation};
delete $hal->{_forcearray};
return($hal, $r);
}

Loading…
Cancel
Save