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