few extra utility routines
[catagits/HTML-Zoom.git] / lib / HTML / Zoom / StreamUtils.pm
1 package HTML::Zoom::StreamUtils;
2
3 use strict;
4 use warnings FATAL => 'all';
5 use base qw(HTML::Zoom::SubObject);
6
7 use Scalar::Util ();
8
9 use HTML::Zoom::CodeStream;
10 use HTML::Zoom::FilterStream;
11
12 sub stream_from_code {
13   my ($self, $code) = @_;
14   HTML::Zoom::CodeStream->new({
15     code => $code,
16     zconfig => $self->_zconfig,
17   })
18 }
19
20 sub stream_from_array {
21   my $self = shift;
22   my @array = @_;
23   $self->stream_from_code(sub {
24     return unless @array;
25     return shift @array;
26   });
27 }
28
29 sub stream_concat {
30   shift->stream_from_array(@_)->flatten;
31 }
32
33 sub stream_from_proto {
34   my ($self, $proto) = @_;
35   my $ref = ref $proto;
36   if (not $ref) {
37     return $self->stream_from_array({
38       type => 'TEXT',
39       raw => $self->_zconfig->parser->html_escape($proto)
40     });
41   } elsif ($ref eq 'ARRAY') {
42     return $self->stream_from_array(@$proto);
43   } elsif ($ref eq 'CODE') {
44     return $proto->();
45   } elsif ($ref eq 'SCALAR') {
46     return $self->_zconfig->parser->html_to_stream($$proto);
47   } elsif (blessed($proto) && $proto->can('as_stream')) {
48     return $proto->as_stream;
49   }
50   die "Don't know how to turn $proto (ref $ref) into a stream";
51 }
52
53 sub wrap_with_filter {
54   my ($self, $stream, $match, $filter) = @_;
55   HTML::Zoom::FilterStream->new({
56     stream => $stream,
57     match => $match,
58     filter => $filter,
59     zconfig => $self->_zconfig,
60   })
61 }
62
63 sub stream_to_array {
64   my $stream = $_[1];
65   my @array;
66   while (my ($evt) = $stream->next) { push @array, $evt }
67   return @array;
68 }
69
70 1;