few extra utility routines
[catagits/HTML-Zoom.git] / lib / HTML / Zoom / StreamUtils.pm
CommitLineData
d80786d0 1package HTML::Zoom::StreamUtils;
2
3use strict;
4use warnings FATAL => 'all';
5use base qw(HTML::Zoom::SubObject);
6
bf5a23d0 7use Scalar::Util ();
8
d80786d0 9use HTML::Zoom::CodeStream;
10use HTML::Zoom::FilterStream;
11
12sub stream_from_code {
13 my ($self, $code) = @_;
14 HTML::Zoom::CodeStream->new({
15 code => $code,
16 zconfig => $self->_zconfig,
17 })
18}
19
20sub 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
29sub stream_concat {
30 shift->stream_from_array(@_)->flatten;
31}
32
33sub 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);
bf5a23d0 47 } elsif (blessed($proto) && $proto->can('as_stream')) {
48 return $proto->as_stream;
d80786d0 49 }
50 die "Don't know how to turn $proto (ref $ref) into a stream";
51}
52
53sub 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
bf5a23d0 63sub stream_to_array {
64 my $stream = $_[1];
65 my @array;
66 while (my ($evt) = $stream->next) { push @array, $evt }
67 return @array;
68}
69
d80786d0 701;