Bug 12362: Add 'TransferCancellation' as a transfer reason
[koha.git] / 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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use C4::Context;
21 use Koha::Database;
22
23 =head1 NAME
24
25 Koha::Objects::Limit::Library - Generic library limit handling class
26
27 =head1 SYNOPSIS
28
29     use base qw(Koha::Objects Koha::Object::Limit::Library);
30     my $objects = Koha::Objects->search_with_library_limits( $params, $attributes, $library_id );
31
32 =head1 DESCRIPTION
33
34 This class is provided as a generic way of handling library limits for Koha::Objects-based classes
35 in Koha.
36
37 This class must always be subclassed.
38
39 =head1 API
40
41 =head2 Class methods
42
43 =cut
44
45 =head3 search_with_library_limits
46
47 my $results = $objects->search_with_library_limits( $params, $attributes, $library_id );
48
49 Wrapper method for searching objects with library limits, respecting those
50 limits
51
52 =cut
53
54 sub search_with_library_limits {
55     my ( $self, $params, $attributes, $library_id ) = @_;
56
57     $library_id //= C4::Context->userenv->{branch}
58         if defined C4::Context->userenv;
59
60     return $self->search( $params, $attributes ) unless $library_id;
61
62     my $library_limits = $self->object_class()->_library_limits;
63     my $library_limits_table
64         = Koha::Database->new->schema->resultset( $library_limits->{class} )->result_source->name;
65     my $library_field = $library_limits->{library};
66
67     my $where = {
68         '-or' => [
69             "$library_limits_table.$library_field" => undef,
70             "$library_limits_table.$library_field" => $library_id,
71         ]
72     };
73
74     $params //= {};
75     $attributes //= {};
76     if ( exists $attributes->{join} ) {
77         if ( ref $attributes->{join} eq 'ARRAY' ) {
78             push @{ $attributes->{join} }, "$library_limits_table";
79         }
80         else {
81             $attributes->{join} = [ $attributes->{join}, "$library_limits_table" ];
82         }
83     }
84     else {
85         $attributes->{join} = $library_limits_table;
86     }
87
88     return $self->search( { %$params, %$where, }, $attributes );
89 }
90
91 1;