factor out ArrayStream, update new stream types to respect peek
[catagits/HTML-Zoom.git] / lib / HTML / Zoom / FilterStream.pm
1 package HTML::Zoom::FilterStream;
2
3 use strict;
4 use warnings FATAL => 'all';
5 use base qw(HTML::Zoom::StreamBase);
6
7 sub new {
8   my ($class, $args) = @_;
9   bless(
10     {
11       _stream => $args->{stream},
12       _match => $args->{match},
13       _filter => $args->{filter},
14       _zconfig => $args->{zconfig},
15     },
16     $class
17   );
18 }
19
20 sub _next {
21   my ($self) = @_;
22
23   # if our main stream is already gone then we can short-circuit
24   # straight out - there's no way for an alternate stream to be there
25
26   return unless $self->{_stream};
27
28   # if we have an alternate stream (provided by a filter call resulting
29   # from a match on the main stream) then we want to read from that until
30   # it's gone - we're still effectively "in the match" but this is the
31   # point at which that fact is abstracted away from downstream consumers
32
33   if (my $alt = $self->{_alt_stream}) {
34
35     if (my ($evt) = $alt->next) {
36       return $evt;
37     }
38
39     # once the alternate stream is exhausted we can throw it away so future
40     # requests fall straight through to the main stream
41
42     delete $self->{_alt_stream};
43   }
44
45   # if there's no alternate stream currently, process the main stream
46
47   while (my ($evt) = $self->{_stream}->next) {
48
49     # don't match this event? return it immediately
50
51     return $evt unless $evt->{type} eq 'OPEN' and $self->{_match}->($evt);
52
53     # run our filter routine against the current event
54
55     my ($res) = $self->{_filter}->($evt, $self->{_stream});
56
57     # if the result is just an event, we can return that now
58
59     return $res if ref($res) eq 'HASH';
60
61     # if no result at all, jump back to the top of the loop to get the
62     # next event and try again - the filter has eaten this one
63
64     next unless defined $res;
65
66     # ARRAY means a pair of [ $evt, $new_stream ]
67
68     if (ref($res) eq 'ARRAY') {
69       $self->{_alt_stream} = $res->[1];
70       return $res->[0];
71     }
72
73     # the filter returned a stream - if it contains something return the
74     # first entry and stash it as the new alternate stream
75
76     if (my ($new_evt) = $res->next) {
77       $self->{_alt_stream} = $res;
78       return $new_evt;
79     }
80
81     # we got a new alternate stream but it turned out to be empty
82     # - this will happens for e.g. with an in place close (<foo />) that's
83     # being removed. In that case, we fall off to loop back round and try
84     # the next event from our main stream
85   }
86
87   # main stream exhausted so throw it away so we hit the short circuit
88   # at the top and return nothing to indicate to our caller we're done
89
90   delete $self->{_stream};
91   return;
92 }
93
94 1;