aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/ConfigValues/HelperTrait.php
blob: 126995dd02a11b4493541cc64025c1fa1c1db7f4 (plain)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php

namespace JsonApi\Routes\ConfigValues;

use ConfigValue;
use JsonApi\Errors\RecordNotFoundException;

trait HelperTrait
{
    private function generateId(ConfigValue $resource): string
    {
        return join('_', [$resource['range_id'], $resource['field']]);
    }

    private function parseId(string $userConfigId): array
    {
        return explode('_', $userConfigId, 2);
    }

    private function getRange(string $rangeId): ?\Range
    {
        if ('studip' === $rangeId) {
            return null;
        }

        if (!($range = \RangeFactory::find($rangeId))) {
            throw new RecordNotFoundException();
        }

        return $range;
    }

    private function findOrFakeConfigValue(?\Range $range, string $field): ConfigValue
    {
        // first search optimistically for this config value
        if ($configValue = ConfigValue::find([$field, $range->id])) {
            return $configValue;
        }

        // try to find a default config entry
        if (!($configEntry = \ConfigEntry::find($field))) {
            throw new RecordNotFoundException();
        }

        return ConfigValue::build([
            'field' => $field,
            'range_id' => $range->id ?? 'studip',
            'value' => $configEntry->value,
            'mkdate' => $configEntry->mkdate,
            'chdate' => $configEntry->chdate,
        ]);
    }
}