aboutsummaryrefslogtreecommitdiff
path: root/lib/models/ConfigValue.php
blob: f5410c93a0c22698227d67e039620abfe542ca8f (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/**
 * ConfigValue.php - model class for table config_value.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * @author      Elmar Ludwig <elmar.ludwig@uos.de>
 * @copyright   2017 Stud.IP Core-Group
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 *
 * @category    Stud.IP
 *
 * @property array $id
 * @property string $field
 * @property string $range_id
 * @property string $value
 * @property int $mkdate
 * @property int $chdate
 * @property string $comment
 *
 * @property ConfigEntry $entry
 */

class ConfigValue extends SimpleORMap
{
    const RANGE_STUDIP = 'studip';

    /**
     * Configures this model.
     *
     * @param array $config Configuration array
     */
    protected static function configure($config = [])
    {
        $config['db_table'] = 'config_values';

        $config['belongs_to']['entry'] = [
            'class_name' => \ConfigEntry::class,
            'foreign_key' => 'field',
        ];

        $config['registered_callbacks']['after_delete'][] = function (ConfigValue $value) {
            if (isset($value->entry) && $value->entry->type === 'i18n') {
                $value->getTypedValue()->removeTranslations();
            }
        };

        parent::configure($config);
    }

    public function isGlobalRange(): bool
    {
        return $this->content['range_id'] === self::RANGE_STUDIP;
    }

    public function getConfigObject(): ?\Config
    {
        if ($this->isGlobalRange()) {
            return \Config::get();
        }

        return ($range = $this->getRange()) ? $range->getConfiguration() : null;
    }

    public function getRange(): ?\Range
    {
        if ($this->isGlobalRange()) {
            return null;
        }

        return \RangeFactory::find($this->content['range_id']);
    }

    public function getTypedValue()
    {
        $config = $this->getConfigObject();

        return $config ? $config->getValue($this->content['field']) : $this->content['value'];
    }

    public function getTypedDefaultValue()
    {
        return \Config::get()->{$this->content['field']};
    }
}