Skip to content
Permalink
Browse files

Add support for persisting scores

  • Loading branch information
flack committed Nov 17, 2019
1 parent dd96510 commit f6925184a79898a9aee7eb183167166284b5535b
Showing with 28 additions and 3 deletions.
  1. +28 −3 src/midcom/datamanager/storage/mnrelation.php
@@ -42,15 +42,37 @@ public function save()
$new = array_diff_key($selection, $existing);
$delete = array_diff_key($existing, $selection);
foreach (array_keys($new) as $member_key) {
$this->create_relation($member_key);
foreach (array_keys($new) as $key) {
$this->create_relation($key, $this->get_score($key, $selection));
}
foreach ($delete as $key => $member) {
if (!$member->delete()) {
throw new midcom_error("Failed to delete member record for key {$key}: " . midcom_connection::get_error_string());
}
}
if (!empty($this->config['type_config']['sortable'])) {
foreach ($existing as $key => $member) {
if (array_key_exists($key, $selection)) {
$score = $this->get_score($key, $selection);
if ($member->metadata->score != $score) {
$member->metadata->score = $score;
if (!$member->update()) {
throw new midcom_error("Failed to update member record for key {$key}: " . midcom_connection::get_error_string());
}
}
}
}
}
}
private function get_score($key, array $selection) : int
{
// if the sort order is descending, the first element needs the highest score
if ($this->config['type_config']['sortable'] == 'DESC') {
return abs($selection[$key] - count($selection));
}
return $selection[$key];
}
/**
@@ -67,7 +89,7 @@ public function load()
return key($this->load_objects());
}
private function create_relation($member_key)
private function create_relation($member_key, int $score)
{
$member = new $this->config['type_config']['mapping_class_name']();
$member->{$this->config['type_config']['master_fieldname']} = $this->get_master_foreign_key();
@@ -95,6 +117,9 @@ private function create_relation($member_key)
$member->{$fieldname} = $value;
}
if (!empty($this->config['type_config']['sortable'])) {
$member->metadata->score = $score;
}
if (!$member->create()) {
throw new midcom_error("Failed to create a new member record for key {$member_key}: " . midcom_connection::get_error_string());

0 comments on commit f692518

Please sign in to comment.
You can’t perform that action at this time.