summaryrefslogtreecommitdiff
path: root/app/Model/Setting.php
blob: 6d29c6ec35cabe361fb032b7b83f439109feb41b (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
89
90
91
92
93
94
95
96
97
98
99
<?php

namespace Kanboard\Model;

/**
 * Application Settings
 *
 * @package  model
 * @author   Frederic Guillot
 */
abstract class Setting extends Base
{
    /**
     * SQL table name
     *
     * @var string
     */
    const TABLE = 'settings';

    /**
     * Prepare data before save
     *
     * @abstract
     * @access public
     * @return array
     */
    abstract public function prepare(array $values);

    /**
     * Get all settings
     *
     * @access public
     * @return array
     */
    public function getAll()
    {
        return $this->db->hashtable(self::TABLE)->getAll('option', 'value');
    }

    /**
     * Get a setting value
     *
     * @access public
     * @param  string   $name
     * @param  string   $default
     * @return mixed
     */
    public function getOption($name, $default = '')
    {
        $value = $this->db
            ->table(self::TABLE)
            ->eq('option', $name)
            ->findOneColumn('value');

        return $value === null || $value === false || $value === '' ? $default : $value;
    }

    /**
     * Return true if a setting exists
     *
     * @access public
     * @param  string   $name
     * @return boolean
     */
    public function exists($name)
    {
        return $this->db
            ->table(self::TABLE)
            ->eq('option', $name)
            ->exists();
    }

    /**
     * Update or insert new settings
     *
     * @access public
     * @param  array    $values
     * @return boolean
     */
    public function save(array $values)
    {
        $results = array();
        $values = $this->prepare($values);

        $this->db->startTransaction();

        foreach ($values as $option => $value) {
            if ($this->exists($option)) {
                $results[] = $this->db->table(self::TABLE)->eq('option', $option)->update(array('value' => $value));
            } else {
                $results[] = $this->db->table(self::TABLE)->insert(array('option' => $option, 'value' => $value));
            }
        }

        $this->db->closeTransaction();

        return ! in_array(false, $results, true);
    }
}