Bug 17170: Add the ability to create 'saved searches' for use as filters when searchi...
[koha-ffzg.git] / Koha / SearchFilter.pm
1 package Koha::SearchFilter;
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with Koha; if not, see <http://www.gnu.org/licenses>.
16
17 use Modern::Perl;
18 use JSON qw( encode_json decode_json );
19
20 use Koha::Database;
21
22 use base qw(Koha::Object);
23
24 =head1 NAME
25
26 Koha::SearchFilter - Koha Search filter object class
27
28 =head1 API
29
30 =head2 Class methods
31
32 =head3 to_api_mapping
33
34 =cut
35
36 sub to_api_mapping {
37     return {
38         id                  => 'search_filter_id',
39         query               => 'filter_query',
40         limits              => 'filter_limits',
41     };
42 }
43
44 =head3 expand_filter
45
46     my ($expanded_limit, $query_limit) = $filter->expand_filter;
47
48     Returns the filter as an arrayref of limit queries, and the query parts combined
49     into a string suitable to be passed to QueryBuilder
50
51 =cut
52
53 sub expand_filter {
54     my $self = shift;
55
56     my $query_part = $self->query;
57     my $limits_part = $self->limits;
58
59     my $limits = decode_json($limits_part)->{limits};
60
61     my $query = decode_json($query_part);
62     my $operators = $query->{operators};
63     my $operands = $query->{operands};
64     my $indexes = $query->{indexes};
65
66     my $query_limit;
67     for( my $i = 0; $i < scalar @$operands; $i++ ){
68         next unless @$operands[$i];
69         my $index = @$indexes[$i] ? @$indexes[$i] . "=" : "";
70         my $query = "(" . @$operands[$i] . ")";
71         my $operator = "";
72         $operator = @$operators[$i-1] ? " " . @$operators[$i-1] . " " : scalar @$operands > $i ? " AND " : "" if $i > 0;
73         my $limit = $operator . $index . $query;
74         $query_limit .= $limit;
75     }
76
77     return ($limits, $query_limit);
78 }
79
80 =head2 Internal methods
81
82 =head3 _type
83
84 =cut
85
86 sub _type {
87     return 'SearchFilter';
88 }
89
90 1;