Protocol::Yadis::Document::Service::Element - Protocol::Yadis::Document::Service element object


Protocol-Yadis documentation Contained in the Protocol-Yadis distribution.

Index


Code Index:

NAME

Top

Protocol::Yadis::Document::Service::Element - Protocol::Yadis::Document::Service element object

SYNOPSIS

Top

    my $e = Protocol::Yadis::Document::Service::Element->new;

    $e->name('Type');
    $e->attrs([a => 'b', c => 'd']);
    $e->content('foo');

    # <Type a="b" c="d">foo</Type>

DESCRIPTION

Top

This is an element object for Protocol::Yadis::Document::Service.

ATTRIBUTES

Top

name

Element name.

content

Element content.

METHODS

Top

new

Creates a new Protocol::Yadis::Document::Service::Element instance.

attrs

Sets/gets element attributes.

attr

Sets/gets element attribute.

to_string

String representation.

AUTHOR

Top

Viacheslav Tykhanovskyi, vti@cpan.org.

COPYRIGHT

Top


Protocol-Yadis documentation Contained in the Protocol-Yadis distribution.

package Protocol::Yadis::Document::Service::Element;

use strict;
use warnings;

use overload '""' => sub { shift->to_string }, fallback => 1;

sub new {
    my $class = shift;

    my $self = {@_};
    bless $self, $class;

    $self->{name}    ||= '';
    $self->{content} ||= '';
    $self->{attrs}   ||= [];

    return $self;
}

sub name    { defined $_[1] ? $_[0]->{name}    = $_[1] : $_[0]->{name} }
sub content { defined $_[1] ? $_[0]->{content} = $_[1] : $_[0]->{content} }
sub attrs   { defined $_[1] ? $_[0]->{attrs}   = $_[1] : $_[0]->{attrs} }

sub attr {
    my $self  = shift;
    my $name  = shift;
    my $value = shift;

    my $attrs = $self->attrs;

    my $i = 0;
    for (; $i < @$attrs; $i += 2) {
        last if $attrs->[$i] eq $name;
    }

    if ($value) {
        if ($i >= @$attrs) {
            push @$attrs, ($name => $value);
        }
        else {
            $attrs->[$i + 1] = $value;
        }
        return $self;
    }

    return if $i >= @$attrs;

    return $attrs->[$i + 1];
}

sub to_string {
    my $self = shift;

    my $name = $self->name;
    return unless $name;

    my $attrs = '';
    for (my $i = 0; $i < @{$self->attrs}; $i += 2) {
        $attrs .= ' ';
        $attrs .= $self->attrs->[$i] . '="' . $self->attrs->[$i + 1] . '"';
    }
    my $content = $self->content;

    return "<$name$attrs>$content</$name>";
}

1;
__END__