DateTime-Format-Builder

 view release on metacpan or  search on metacpan

lib/DateTime/Format/Builder/Parser/Regex.pm  view on Meta::CPAN

package DateTime::Format::Builder::Parser::Regex;

use strict;
use warnings;

our $VERSION = '0.83';

use Params::Validate qw( validate ARRAYREF SCALARREF HASHREF CODEREF );

use parent 'DateTime::Format::Builder::Parser::generic';

__PACKAGE__->valid_params(

    # How to match
    params => {
        type => ARRAYREF,    # mapping $1,$2,... to new args
    },
    regex => {
        type      => SCALARREF,
        callbacks => {
            'is a regex' => sub { ref(shift) eq 'Regexp' }
        }
    },

    # How to create
    extra => {
        type     => HASHREF,
        optional => 1,
    },
    constructor => {
        type      => CODEREF | ARRAYREF,
        optional  => 1,
        callbacks => {
            'array has 2 elements' => sub {
                ref( $_[0] ) eq 'ARRAY' ? ( @{ $_[0] } == 2 ) : 1;
            }
        }
    },
);

sub do_match {
    my $self    = shift;
    my $date    = shift;
    my @matches = $date =~ $self->{regex};
    return @matches ? \@matches : undef;
}

sub post_match {
    my $self = shift;
    my ( $date, $matches, $p ) = @_;

    # Fill %p from match
    @{$p}{ @{ $self->{params} } } = @$matches;
    return;
}

sub make {
    my $self = shift;
    my ( $date, $dt, $p ) = @_;
    my @args = ( %$p, %{ $self->{extra} } );
    if ( my $cons = $self->{constructor} ) {
        if ( ref $cons eq 'ARRAY' ) {
            my ( $class, $method ) = @$cons;
            return $class->$method(@args);
        }
        elsif ( ref $cons eq 'CODE' ) {
            return $self->$cons(@args);
        }
    }
    else {
        return DateTime->new(@args);
    }
}

sub create_parser {
    my ( $self, %args ) = @_;
    $args{extra} ||= {};
    unless ( ref $self ) {
        $self = $self->new(%args);
    }

    # Create our parser
    return $self->generic_parser(
        (
            map { exists $args{$_} ? ( $_ => $args{$_} ) : () }
                qw(
                on_match on_fail preprocess postprocess
                )
        ),
        label => $args{label},
    );
}



( run in 0.729 second using v1.01-cache-2.11-cpan-39bf76dae61 )