Choice.pm 10.1 KB
Newer Older
1 2 3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
#
5 6
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
7 8 9

package Bugzilla::Field::Choice;

10 11
use 5.10.1;
use strict;
12
use warnings;
13

14
use parent qw(Bugzilla::Field::ChoiceInterface Bugzilla::Object);
15

16
use Bugzilla::Config qw(SetParam write_params);
17 18
use Bugzilla::Constants;
use Bugzilla::Error;
19 20
use Bugzilla::Field;
use Bugzilla::Util qw(trim detaint_natural);
21 22 23 24 25 26 27

use Scalar::Util qw(blessed);

##################
# Initialization #
##################

28 29
use constant IS_CONFIG => 1;

30 31 32 33
use constant DB_COLUMNS => qw(
    id
    value
    sortkey
34
    isactive
35
    visibility_value_id
36 37
);

38 39 40
use constant UPDATE_COLUMNS => qw(
    value
    sortkey
41
    isactive
42
    visibility_value_id
43 44
);

45 46 47
use constant NAME_FIELD => 'value';
use constant LIST_ORDER => 'sortkey, value';

48 49 50
use constant VALIDATORS => {
    value   => \&_check_value,
    sortkey => \&_check_sortkey,
51
    visibility_value_id => \&_check_visibility_value_id,
52
    isactive => \&_check_isactive,
53 54 55 56
};

use constant CLASS_MAP => {
    bug_status => 'Bugzilla::Status',
57
    classification => 'Bugzilla::Classification',
58
    component  => 'Bugzilla::Component',
59
    product    => 'Bugzilla::Product',
60 61
};

62 63 64 65 66 67 68
use constant DEFAULT_MAP => {
    op_sys       => 'defaultopsys',
    rep_platform => 'defaultplatform',
    priority     => 'defaultpriority',
    bug_severity => 'defaultseverity',
};

69 70 71 72 73 74 75 76 77 78 79 80 81 82
#################
# Class Factory #
#################

# Bugzilla::Field::Choice is actually an abstract base class. Every field
# type has its own dynamically-generated class for its values. This allows
# certain fields to have special types, like how bug_status's values
# are Bugzilla::Status objects.

sub type {
    my ($class, $field) = @_;
    my $field_obj = blessed $field ? $field : Bugzilla::Field->check($field);
    my $field_name = $field_obj->name;

83 84 85 86
    if (my $package = $class->CLASS_MAP->{$field_name}) {
        # Callers expect the module to be already loaded.
        eval "require $package";
        return $package;
87
    }
88 89 90 91

    # For generic classes, we use a lowercase class name, so as
    # not to interfere with any real subclasses we might make some day.
    my $package = "Bugzilla::Field::Choice::$field_name";
92
    Bugzilla->request_cache->{"field_$package"} = $field_obj;
93

94 95 96 97 98
    # This package only needs to be created once. We check if the DB_TABLE
    # glob for this package already exists, which tells us whether or not
    # we need to create the package (this works even under mod_perl, where
    # this package definition will persist across requests)).
    if (!defined *{"${package}::DB_TABLE"}) {
99 100
        eval <<EOC;
            package $package;
101
            use parent qw(Bugzilla::Field::Choice);
102 103 104 105 106
            use constant DB_TABLE => '$field_name';
EOC
    }

    return $package;
107 108
}

109 110 111 112 113 114 115
################
# Constructors #
################

# We just make new() enforce this, which should give developers 
# the understanding that you can't use Bugzilla::Field::Choice
# without calling type().
116 117
sub new {
    my $class = shift;
118 119 120 121
    if ($class eq 'Bugzilla::Field::Choice') {
        ThrowCodeError('field_choice_must_use_type');
    }
    $class->SUPER::new(@_);
122 123
}

124 125 126
#########################
# Database Manipulation #
#########################
127

128 129 130 131 132
# Our subclasses can take more arguments than we normally accept.
# So, we override create() to remove arguments that aren't valid
# columns. (Normally Bugzilla::Object dies if you pass arguments
# that aren't valid columns.)
sub create {
133 134
    my $class = shift;
    my ($params) = @_;
135
    foreach my $key (keys %$params) {
136
        if (!grep {$_ eq $key} $class->_get_db_columns) {
137 138 139 140
            delete $params->{$key};
        }
    }
    return $class->SUPER::create(@_);
141 142
}

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
sub update {
    my $self = shift;
    my $dbh = Bugzilla->dbh;
    my $fname = $self->field->name;

    $dbh->bz_start_transaction();

    my ($changes, $old_self) = $self->SUPER::update(@_);
    if (exists $changes->{value}) {
        my ($old, $new) = @{ $changes->{value} };
        if ($self->field->type == FIELD_TYPE_MULTI_SELECT) {
            $dbh->do("UPDATE bug_$fname SET value = ? WHERE value = ?",
                     undef, $new, $old);
        }
        else {
            $dbh->do("UPDATE bugs SET $fname = ? WHERE $fname = ?",
                     undef, $new, $old);
        }

        if ($old_self->is_default) {
            my $param = $self->DEFAULT_MAP->{$self->field->name};
            SetParam($param, $self->name);
            write_params();
        }
    }

    $dbh->bz_commit_transaction();
170
    return wantarray ? ($changes, $old_self) : $changes;
171 172
}

173 174 175 176
sub remove_from_db {
    my $self = shift;
    if ($self->is_default) {
        ThrowUserError('fieldvalue_is_default',
177
                       { field => $self->field, value => $self,
178 179 180 181 182
                         param_name => $self->DEFAULT_MAP->{$self->field->name},
                       });
    }
    if ($self->is_static) {
        ThrowUserError('fieldvalue_not_deletable', 
183
                       { field => $self->field, value => $self });
184 185 186
    }
    if ($self->bug_count) {
        ThrowUserError("fieldvalue_still_has_bugs",
187
                       { field => $self->field, value => $self });
188
    }
189
    $self->_check_if_controller(); # From ChoiceInterface.
190 191 192
    $self->SUPER::remove_from_db();
}

193 194 195 196
############
# Mutators #
############

197 198 199
sub set_is_active { $_[0]->set('isactive', $_[1]); }
sub set_name      { $_[0]->set('value', $_[1]);    }
sub set_sortkey   { $_[0]->set('sortkey', $_[1]);  }
200 201 202 203 204
sub set_visibility_value {
    my ($self, $value) = @_;
    $self->set('visibility_value_id', $value);
    delete $self->{visibility_value};
}
205

206 207 208 209
##############
# Validators #
##############

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
sub _check_isactive {
    my ($invocant, $value) = @_;
    $value = Bugzilla::Object::check_boolean($invocant, $value);
    if (!$value and ref $invocant) {
        if ($invocant->is_default) {
            my $field = $invocant->field;
            ThrowUserError('fieldvalue_is_default', 
                           { value => $invocant, field => $field,
                             param_name => $invocant->DEFAULT_MAP->{$field->name}
                           });
        }
        if ($invocant->is_static) {
            ThrowUserError('fieldvalue_not_deletable',
                           { value => $invocant, field => $invocant->field });
        }
    }
    return $value;
}

229 230 231 232 233 234
sub _check_value {
    my ($invocant, $value) = @_;

    my $field = $invocant->field;

    $value = trim($value);
235 236 237 238 239 240

    # Make sure people don't rename static values
    if (blessed($invocant) && $value ne $invocant->name 
        && $invocant->is_static) 
    {
        ThrowUserError('fieldvalue_not_editable',
241
                       { field => $field, old_value => $invocant });
242 243
    }

244 245 246 247 248
    ThrowUserError('fieldvalue_undefined') if !defined $value || $value eq "";
    ThrowUserError('fieldvalue_name_too_long', { value => $value })
        if length($value) > MAX_FIELD_VALUE_SIZE;

    my $exists = $invocant->type($field)->new({ name => $value });
249
    if ($exists && (!blessed($invocant) || $invocant->id != $exists->id)) {
250
        ThrowUserError('fieldvalue_already_exists', 
251
                       { field => $field, value => $exists });
252 253
    }

254
    return $value;
255 256
}

257 258 259 260 261 262
sub _check_sortkey {
    my ($invocant, $value) = @_;
    $value = trim($value);
    return 0 if !$value;
    # Store for the error message in case detaint_natural clears it.
    my $orig_value = $value;
263
    (detaint_natural($value) && $value <= MAX_SMALLINT)
264 265 266 267 268
        || ThrowUserError('fieldvalue_sortkey_invalid',
                          { sortkey => $orig_value,
                            field   => $invocant->field });
    return $value;
}
269

270 271 272 273 274 275 276 277 278
sub _check_visibility_value_id {
    my ($invocant, $value_id) = @_;
    $value_id = trim($value_id);
    my $field = $invocant->field->value_field;
    return undef if !$field || !$value_id;
    my $value_obj = Bugzilla::Field::Choice->type($field)
                    ->check({ id => $value_id });
    return $value_obj->id;
}
279 280 281 282 283 284 285 286 287 288 289 290 291

1;

__END__

=head1 NAME

Bugzilla::Field::Choice - A legal value for a <select>-type field.

=head1 SYNOPSIS

 my $field = new Bugzilla::Field({name => 'bug_status'});

292
 my $choice = new Bugzilla::Field::Choice->type($field)->new(1);
293

294 295 296
 my $choices = Bugzilla::Field::Choice->type($field)->new_from_list([1,2,3]);
 my $choices = Bugzilla::Field::Choice->type($field)->get_all();
 my $choices = Bugzilla::Field::Choice->type($field->match({ sortkey => 10 }); 
297 298 299 300

=head1 DESCRIPTION

This is an implementation of L<Bugzilla::Object>, but with a twist.
301 302 303 304 305 306 307
You can't call any class methods (such as C<new>, C<create>, etc.) 
directly on C<Bugzilla::Field::Choice> itself. Instead, you have to
call C<Bugzilla::Field::Choice-E<gt>type($field)> to get the class
you're going to instantiate, and then you call the methods on that.

We do that because each field has its own database table for its values, so
each value type needs its own class.
308

309
See the L</SYNOPSIS> for examples of how this works.
310

311 312 313
This class implements L<Bugzilla::Field::ChoiceInterface>, and so all
methods of that class are also available here.

314 315
=head1 METHODS

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
=head2 Class Factory

In object-oriented design, a "class factory" is a method that picks
and returns the right class for you, based on an argument that you pass.

=over

=item C<type>

Takes a single argument, which is either the name of a field from the
C<fielddefs> table, or a L<Bugzilla::Field> object representing a field.

Returns an appropriate subclass of C<Bugzilla::Field::Choice> that you
can now call class methods on (like C<new>, C<create>, C<match>, etc.)

B<NOTE>: YOU CANNOT CALL CLASS METHODS ON C<Bugzilla::Field::Choice>. You
must call C<type> to get a class you can call methods on.

=back

336
=head2 Mutators
337

338 339
This class implements mutators for all of the settable accessors in
L<Bugzilla::Field::ChoiceInterface>.
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359

=head1 B<Methods in need of POD>

=over

=item create

=item remove_from_db

=item set_is_active

=item set_sortkey

=item set_name

=item update

=item set_visibility_value

=back