Choice.pm 12.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Initial Developer of the Original Code is NASA.
# Portions created by NASA are Copyright (C) 2006 San Jose State
# University Foundation. All Rights Reserved.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# Contributor(s): Max Kanat-Alexander <mkanat@bugzilla.org>

use strict;

package Bugzilla::Field::Choice;

use base qw(Bugzilla::Object);

27
use Bugzilla::Config qw(SetParam write_params);
28 29
use Bugzilla::Constants;
use Bugzilla::Error;
30 31
use Bugzilla::Field;
use Bugzilla::Util qw(trim detaint_natural);
32 33 34 35 36 37 38 39 40 41 42

use Scalar::Util qw(blessed);

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

use constant DB_COLUMNS => qw(
    id
    value
    sortkey
43
    visibility_value_id
44 45
);

46 47 48
use constant UPDATE_COLUMNS => qw(
    value
    sortkey
49
    visibility_value_id
50 51
);

52 53 54
use constant NAME_FIELD => 'value';
use constant LIST_ORDER => 'sortkey, value';

55
use constant REQUIRED_CREATE_FIELDS => qw(value);
56

57 58 59
use constant VALIDATORS => {
    value   => \&_check_value,
    sortkey => \&_check_sortkey,
60
    visibility_value_id => \&_check_visibility_value_id,
61 62 63 64
};

use constant CLASS_MAP => {
    bug_status => 'Bugzilla::Status',
65
    product    => 'Bugzilla::Product',
66 67
};

68 69 70 71 72 73 74
use constant DEFAULT_MAP => {
    op_sys       => 'defaultopsys',
    rep_platform => 'defaultplatform',
    priority     => 'defaultpriority',
    bug_severity => 'defaultseverity',
};

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#################
# 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;

    if ($class->CLASS_MAP->{$field_name}) {
        return $class->CLASS_MAP->{$field_name};
91
    }
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

    # 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";

    # We check defined so that the package and the stored field are only
    # created once globally (at least per request). We prefix it with
    # field_ (instead of suffixing it) so that we don't somehow conflict
    # with the names of custom fields.
    if (!defined Bugzilla->request_cache->{"field_$package"}) {
        eval <<EOC;
            package $package;
            use base qw(Bugzilla::Field::Choice);
            use constant DB_TABLE => '$field_name';
EOC
        Bugzilla->request_cache->{"field_$package"} = $field_obj;
    }

    return $package;
111 112
}

113 114 115 116 117 118 119
################
# Constructors #
################

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

128 129 130
#########################
# Database Manipulation #
#########################
131

132 133 134 135 136
# 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 {
137 138
    my $class = shift;
    my ($params) = @_;
139 140 141 142 143 144
    foreach my $key (keys %$params) {
        if (!grep {$_ eq $key} $class->DB_COLUMNS) {
            delete $params->{$key};
        }
    }
    return $class->SUPER::create(@_);
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 170 171 172 173 174 175 176
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();
    return $changes;
}

177 178 179 180
sub remove_from_db {
    my $self = shift;
    if ($self->is_default) {
        ThrowUserError('fieldvalue_is_default',
181
                       { field => $self->field, value => $self,
182 183 184 185 186
                         param_name => $self->DEFAULT_MAP->{$self->field->name},
                       });
    }
    if ($self->is_static) {
        ThrowUserError('fieldvalue_not_deletable', 
187
                       { field => $self->field, value => $self });
188 189 190
    }
    if ($self->bug_count) {
        ThrowUserError("fieldvalue_still_has_bugs",
191
                       { field => $self->field, value => $self });
192
    }
193 194 195 196 197 198 199
    $self->_check_if_controller();
    $self->SUPER::remove_from_db();
}

# Factored out to make life easier for subclasses.
sub _check_if_controller {
    my $self = shift;
200 201 202
    my $vis_fields = $self->controls_visibility_of_fields;
    my $values     = $self->controlled_values;
    if (@$vis_fields || @$values) {
203
        ThrowUserError('fieldvalue_is_controller',
204 205
            { value => $self, fields => [map($_->name, @$vis_fields)],
              vals => $values });
206
    }
207 208
}

209

210 211 212
#############
# Accessors #
#############
213

214
sub sortkey { return $_[0]->{'sortkey'}; }
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

sub bug_count {
    my $self = shift;
    return $self->{bug_count} if defined $self->{bug_count};
    my $dbh = Bugzilla->dbh;
    my $fname = $self->field->name;
    my $count;
    if ($self->field->type == FIELD_TYPE_MULTI_SELECT) {
        $count = $dbh->selectrow_array("SELECT COUNT(*) FROM bug_$fname
                                         WHERE value = ?", undef, $self->name);
    }
    else {
        $count = $dbh->selectrow_array("SELECT COUNT(*) FROM bugs 
                                         WHERE $fname = ?",
                                       undef, $self->name);
    }
    $self->{bug_count} = $count;
    return $count;
}

235 236 237 238 239 240 241 242 243
sub field {
    my $invocant = shift;
    my $class = ref $invocant || $invocant;
    my $cache = Bugzilla->request_cache;
    # This is just to make life easier for subclasses. Our auto-generated
    # subclasses from type() already have this set.
    $cache->{"field_$class"} ||=  
        new Bugzilla::Field({ name => $class->DB_TABLE });
    return $cache->{"field_$class"};
244 245
}

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
sub is_default {
    my $self = shift;
    my $param_value = 
        Bugzilla->params->{ $self->DEFAULT_MAP->{$self->field->name} };
    return 0 if !defined $param_value;
    return $self->name eq $param_value ? 1 : 0;
}

sub is_static {
    my $self = shift;
    # If we need to special-case Resolution for *anything* else, it should
    # get its own subclass.
    if ($self->field->name eq 'resolution') {
        return grep($_ eq $self->name, ('', 'FIXED', 'MOVED', 'DUPLICATE'))
               ? 1 : 0;
    }
    elsif ($self->field->custom) {
        return $self->name eq '---' ? 1 : 0;
    }
    return 0;
}

268 269 270 271 272 273 274 275
sub controls_visibility_of_fields {
    my $self = shift;
    $self->{controls_visibility_of_fields} ||= Bugzilla::Field->match(
        { visibility_field_id => $self->field->id, 
          visibility_value_id => $self->id });
    return $self->{controls_visibility_of_fields};
}

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
sub visibility_value {
    my $self = shift;
    if ($self->{visibility_value_id}) {
        $self->{visibility_value} ||=
            Bugzilla::Field::Choice->type($self->field->value_field)->new(
                $self->{visibility_value_id});
    }
    return $self->{visibility_value};
}

sub controlled_values {
    my $self = shift;
    return $self->{controlled_values} if defined $self->{controlled_values};
    my $fields = $self->field->controls_values_of;
    my @controlled_values;
    foreach my $field (@$fields) {
        my $controlled = Bugzilla::Field::Choice->type($field)
                         ->match({ visibility_value_id => $self->id });
        push(@controlled_values, @$controlled);
    }
    $self->{controlled_values} = \@controlled_values;
    return $self->{controlled_values};
}

300 301 302 303 304 305
############
# Mutators #
############

sub set_name    { $_[0]->set('value', $_[1]);   }
sub set_sortkey { $_[0]->set('sortkey', $_[1]); }
306 307 308 309 310
sub set_visibility_value {
    my ($self, $value) = @_;
    $self->set('visibility_value_id', $value);
    delete $self->{visibility_value};
}
311

312 313 314 315 316 317 318 319 320 321
##############
# Validators #
##############

sub _check_value {
    my ($invocant, $value) = @_;

    my $field = $invocant->field;

    $value = trim($value);
322 323 324 325 326 327

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

331 332 333 334 335
    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 });
336
    if ($exists && (!blessed($invocant) || $invocant->id != $exists->id)) {
337
        ThrowUserError('fieldvalue_already_exists', 
338
                       { field => $field, value => $exists });
339 340
    }

341
    return $value;
342 343
}

344 345 346 347 348 349 350 351 352 353 354 355
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;
    detaint_natural($value)
        || ThrowUserError('fieldvalue_sortkey_invalid',
                          { sortkey => $orig_value,
                            field   => $invocant->field });
    return $value;
}
356

357 358 359 360 361 362 363 364 365
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;
}
366 367 368 369 370 371 372 373 374 375 376 377 378

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'});

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

381 382 383
 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 }); 
384 385 386 387

=head1 DESCRIPTION

This is an implementation of L<Bugzilla::Object>, but with a twist.
388 389 390 391 392 393 394
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.
395

396
See the L</SYNOPSIS> for examples of how this works.
397 398 399

=head1 METHODS

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
=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

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
=head2 Accessors

These are in addition to the standard L<Bugzilla::Object> accessors.

=over

=item C<sortkey>

The key that determines the sort order of this item.

=item C<field>

The L<Bugzilla::Field> object that this field value belongs to.

=back