bb10f11e0dd24e8923350f7913c09778a6281115
[srvgit] / Koha / Objects / Limit / Library.pm
1 package Koha::Objects::Limit::Library;
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 along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18 use Modern::Perl;
19
20 use Koha::Database;
21
22 =head1 NAME
23
24 Koha::Objects::Limit::Library - Generic library limit handling class
25
26 =head1 SYNOPSIS
27
28     use base qw(Koha::Objects Koha::Object::Limit::Library);
29     my $objects = Koha::Objects->search_with_library_limits( $params, $attributes, $library_id );
30
31 =head1 DESCRIPTION
32
33 This class is provided as a generic way of handling library limits for Koha::Objects-based classes
34 in Koha.
35
36 This class must always be subclassed.
37
38 =head1 API
39
40 =head2 Class methods
41
42 =cut
43
44 =head3 search_with_library_limits
45
46 my $results = $objects->search_with_library_limits( $params, $attributes, $library_id );
47
48 Wrapper method for searching objects with library limits, respecting those
49 limits
50
51 =cut
52
53 sub search_with_library_limits {
54     my ( $self, $params, $attributes, $library_id ) = @_;
55
56     return $self->search( $params, $attributes ) unless $library_id;
57
58     my $library_limits = $self->object_class()->_library_limits;
59     my $library_limits_table
60         = Koha::Database->new->schema->resultset( $library_limits->{class} )->result_source->name;
61     my $library_field = $library_limits->{library};
62
63     my $where = {
64         '-or' => [
65             "$library_limits_table.$library_field" => undef,
66             "$library_limits_table.$library_field" => $library_id,
67         ]
68     };
69
70     $attributes //= {};
71     if ( exists $attributes->{join} ) {
72         if ( ref $attributes->{join} eq 'ARRAY' ) {
73             push @{ $attributes->{join} }, "$library_limits_table";
74         }
75         else {
76             $attributes->{join} = [ $attributes->{join}, "$library_limits_table" ];
77         }
78     }
79     else {
80         $attributes->{join} = $library_limits_table;
81     }
82
83     return $self->search( { %$params, %$where, }, $attributes );
84 }
85
86 1;