1package Badger::Data::Facet::Text::Whitespace;
2
3use Badger::Data::Facet::Class
4    version   => 0.01,
5    type      => 'text',
6    args      => 'whitespace',
7    constant  => {
8        PRESERVE => 0,
9        FOLD     => 1,
10        COLLAPSE => 2,
11    };
12
13our $ACTION = {
14    preserve => PRESERVE,
15    fold     => FOLD,
16    collapse => COLLAPSE,
17};
18
19
20sub init {
21    my ($self, $config) = @_;
22
23    $self->SUPER::init($config)
24        || return;
25
26    # option must have an entry in $ACCEPT which we store in $self->{ action }
27    return $self->error_msg( whitespace => $self->{ whitespace }, join(', ', keys %$ACTION) )
28        unless defined ($self->{ action } = $ACTION->{ $self->{ whitespace } });
29
30    return $self;
31}
32
33
34sub validate {
35    my ($self, $text, $type) = @_;
36    my $action = $self->{ action }      # do nothing for PRESERVE
37        || return $text;
38
39    for ($$text) {
40        s/[\r\n\t]/ /g;
41        if ($action == COLLAPSE) {
42            s/ +/ /g;
43            s/^ +//;
44            s/ +$//;
45        }
46    }
47
48    return $text;
49}
50
51
521;
53
54__END__
55
56=head1 NAME
57
58Badger::Data::Facet::Text::Whitespace - validation facet for whitespace
59
60=head1 DESCRIPTION
61
62This module implements a validation facets for munging whitespace on text
63values.
64
65=head1 METHODS
66
67This module implement the following methods in addition to those inherited
68from the L<Badger::Data::Facet::Text>, L<Badger::Data::Facet> and
69L<Badger::Base> base classes.
70
71=head2 validate($text_ref, $type)
72
73This method performs whitespace handling on the text passed by reference as
74the first argument.
75
76If the pre-defined C<action> is C<preserve> then the text will be unmodified.
77
78If the C<action> is C<fold> then all whitespace characters in the text
79(carriage returns, newlines, tabs) will be converted to spaces.
80
81If the C<action> is C<collapse> then all whitespace characters will first be
82converted to spaces as per C<fold>.  Any leading and trailing whitespace is
83then removed and any sequences of multiple spaces are collapsed to a single
84space.
85
86=head1 AUTHOR
87
88Andy Wardley L<http://wardley.org/>
89
90=head1 COPYRIGHT
91
92Copyright (C) 2001-2012 Andy Wardley.  All Rights Reserved.
93
94This module is free software; you can redistribute it and/or
95modify it under the same terms as Perl itself.
96
97=head1 SEE ALSO
98
99L<Badger::Base>,
100L<Badger::Data::Facet>,
101L<Badger::Data::Facet::Text>.
102
103=cut
104
105# Local Variables:
106# mode: perl
107# perl-indent-level: 4
108# indent-tabs-mode: nil
109# End:
110#
111# vim: expandtab shiftwidth=4:
112