| 1 | |||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | package Jifty::DBI::Filter::Truncate; | ||
| 6 | use base qw/Jifty::DBI::Filter/; | ||
| 7 | use Encode (); | ||
| 8 | |||
| 9 | sub encode { | ||
| 10 | my $self = shift; | ||
| 11 | |||
| 12 | my $value_ref = $self->value_ref; | ||
| 13 | return undef unless ( defined($$value_ref) ); | ||
| 14 | |||
| 15 | my $column = $self->column(); | ||
| 16 | |||
| 17 | my $truncate_to; | ||
| 18 | if ( $column->max_length && !$column->is_numeric ) { | ||
| 19 | $truncate_to = $column->max_length; | ||
| 20 | } elsif ( $column->type && $column->type =~ /char\((\d+)\)/ ) { | ||
| 21 | $truncate_to = $1; | ||
| 22 | } | ||
| 23 | |||
| 24 | return unless ($truncate_to); # don't need to truncate | ||
| 25 | |||
| 26 | my $utf8 = Encode::is_utf8($$value_ref); | ||
| 27 | { | ||
| 28 | use bytes; | ||
| 29 | $$value_ref = substr( $$value_ref, 0, $truncate_to ); | ||
| 30 | } | ||
| 31 | if ($utf8) { | ||
| 32 | |||
| 33 | # return utf8 flag back, but use Encode::FB_QUIET because | ||
| 34 | # we could broke tail char | ||
| 35 | $$value_ref = Encode::decode_utf8( $$value_ref, Encode::FB_QUIET ); | ||
| 36 | } | ||
| 37 | } | ||
| 38 | |||
| 39 | 1; |