HTML-Untemplate

 view release on metacpan or  search on metacpan

lib/HTML/Linear/Element.pm  view on Meta::CPAN

package HTML::Linear::Element;
# ABSTRACT: represent elements to populate HTML::Linear
use strict;
use utf8;
use warnings qw(all);

use Digest::SHA;
use Encode;
use List::Util qw(sum);
use Moo;
use MooX::Types::MooseLike::Base qw(:all);

use HTML::Linear::Path;

## no critic (ProtectPrivateSubs)

our $VERSION = '0.019'; # VERSION


has attributes  => (is => 'rw', isa => HashRef[Str], default => sub { {} });
has content     => (is => 'rw', isa => Str, default => sub { '' });
has depth       => (is => 'ro', isa => Int, required => 1);
has index       => (is => 'rw', isa => Int, default => sub { 0 });
has index_map   => (is => 'rw', isa => HashRef[Str], default => sub { {} });
has key         => (is => 'rw', isa => Str, default => sub { '' });
has path        => (is => 'ro', isa => ArrayRef[InstanceOf('HTML::Linear::Path')], required => 1);
has sha         => (is => 'ro', isa => InstanceOf('Digest::SHA'), default => sub { Digest::SHA->new(256) }, lazy => 1 );
has strict      => (is => 'ro', isa => Bool, default => sub { 0 });
has trim_at     => (is => 'rw', isa => Int, default => sub { 0 });

use overload '""' => \&as_string, fallback => 1;


sub BUILD {
    my ($self) = @_;
    $self->attributes({%{$self->path->[-1]->attributes}});
    return;
}


sub as_string {
    my ($self) = @_;
    return $self->key if $self->key;

    my $content = $self->content;
    Encode::_utf8_off($content);
    $self->sha->add($content);

    $self->sha->add($self->index);
    $self->sha->add(join ',', $self->path);

    return $self->key($self->sha->b64digest);
}


sub as_xpath {
    my ($self) = @_;
    my @xpath = map {
        $_->as_xpath . ($self->index_map->{$_->address} // '')
    } @{$self->path} [$self->trim_at .. $#{$self->path}];
    $self->trim_at and unshift @xpath, HTML::Linear::Path::_wrap(separator => '/');
    return wantarray
        ? @xpath
        : join '', @xpath;
}


sub as_hash {
    my ($self) = @_;
    my $hash = {};
    my $xpath = $self->as_xpath . HTML::Linear::Path::_wrap(separator => '/');

    for my $key (sort keys %{$self->attributes}) {
        $hash->{
            $xpath
            . HTML::Linear::Path::_wrap(sigil       => '@')
            . HTML::Linear::Path::_wrap(attribute   => $key)
        } = $self->attributes->{$key}
            if
                $self->strict
                or not HTML::Linear::Path::_isgroup($self->path->[-1]->tag, $key);
    }

    $hash->{
        $xpath
        . HTML::Linear::Path::_wrap(attribute => 'text()')



( run in 2.374 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )