]> git.ipfire.org Git - thirdparty/bugzilla.git/commitdiff
Bug 1508201 - add a better flatten_to_hash method to User
authorDylan William Hardison <dylan@hardison.net>
Tue, 20 Nov 2018 22:32:52 +0000 (17:32 -0500)
committerGitHub <noreply@github.com>
Tue, 20 Nov 2018 22:32:52 +0000 (17:32 -0500)
Bugzilla/Role/FlattenToHash.pm [new file with mode: 0644]
Bugzilla/User.pm

diff --git a/Bugzilla/Role/FlattenToHash.pm b/Bugzilla/Role/FlattenToHash.pm
new file mode 100644 (file)
index 0000000..c11f97f
--- /dev/null
@@ -0,0 +1,42 @@
+# 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/.
+#
+# This Source Code Form is "Incompatible With Secondary Licenses", as
+# defined by the Mozilla Public License, v. 2.0.
+
+package Bugzilla::Role::FlattenToHash;
+
+use 5.10.1;
+use strict;
+use warnings;
+use Role::Tiny;
+use Scalar::Util qw(blessed);
+
+requires 'DB_TABLE', '_get_db_columns';
+
+my $_error = sub { die "cannot determine attribute name from $_[0]\n" };
+
+sub _get_db_keys {
+  my ($self, $object)  = @_;
+  my $class   = blessed($self) // $self;
+  my $table   = $class->DB_TABLE;
+  my @columns = $class->_get_db_columns;
+  my $re      = qr{
+    ^\s*(?<name>\w+)\s*$
+    | ^\s*\Q$table.\E(?<name>\w+)\s*$
+    | \s+AS\s+(?<name>\w+)\s*$
+  }six;
+
+  return map { $_ =~ $re ? $+{name} : $_error->($_) } @columns;
+}
+
+sub flatten_to_hash {
+  my ($self) = @_;
+  my %hash;
+  my @keys = $self->_get_db_keys();
+  @hash{ @keys } = @$self{ @keys };
+  return \%hash;
+}
+
+1;
index b15cad3968e90cc6717110e448641a097ec9cc1c..aa5405ba9f88d0d41a9cbf8b1d31e18684debedc 100644 (file)
@@ -33,6 +33,10 @@ use URI::QueryParam;
 use Role::Tiny::With;
 
 use base qw(Bugzilla::Object Exporter);
+
+with 'Bugzilla::Elastic::Role::Object', 'Bugzilla::Role::Storable',
+  'Bugzilla::Role::FlattenToHash';
+
 @Bugzilla::User::EXPORT = qw(is_available_username
     login_to_id user_id_to_login
     USER_MATCH_MULTIPLE USER_MATCH_FAILED USER_MATCH_SUCCESS
@@ -129,8 +133,6 @@ use constant VALIDATOR_DEPENDENCIES => {
 
 use constant EXTRA_REQUIRED_FIELDS => qw(is_enabled);
 
-with 'Bugzilla::Elastic::Role::Object', 'Bugzilla::Role::Storable';
-
 sub ES_INDEX {
     my ($class) = @_;
     sprintf("%s_%s", Bugzilla->params->{elasticsearch_index}, $class->ES_TYPE);