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