Passed
Push — master ( 59f31d...a30cf1 )
by Plamen
01:35
created

TraitConfig::config()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 8
nop 1
dl 0
loc 16
rs 9.5555
c 0
b 0
f 0
1
<?php
2
3
trait TraitConfig
4
{
5
    /** @param array Re-settable values for current table call */
6
    protected static $config = [
7
        'APP' => 'App',
8
        'DB_COLLATION_CI' => 'utf8mb4_general_ci', //UTF8_GENERAL_CI
9
        'EMPTY_TABLE_MSG' => 'No results found.',
10
        'EXPORT_FILE_NAME' => ':app - :items export (:datetime)',
11
        'FILTER_ACTIVE' => true,
12
        'FILTER_CASE_SENSITIVE' => false,
13
        'SAVES' => ['CSV', 'Excel'],
14
        'UTF8_ASC_SYMBOL' => '&#9650;',
15
        'UTF8_DESC_SYMBOL' => '&#9660;',
16
        'UTF8_LEFT_SYMBOL' => '&lsaquo;',
17
        'UTF8_RIGHT_SYMBOL' => '&rsaquo;'
18
    ];
19
    /** @param array Errors collector */
20
    protected static $errors = [];
21
22
    /** Set/Get config value
23
     * @param mixed $value (string) Get if exists, (array) Set if valid
24
     * @return mixed */
25
    public static function config($value)
26
    {
27
        try {
28
            switch (gettype($value)) {
29
                case 'array':
30
                    foreach ($value as $k => $v) {
31
                        self::$config[$k] = self::valid((string) $k, $v);
32
                    }
33
                    break;
34
                case 'string':
35
                    return self::valid($value);
36
                default:
37
                    throw new Exception("Invalid value type.");
38
            }
39
        } catch (Exception $e) {
40
            self::error('ERROR: ' . $e->getMessage());
41
        }
42
    }
43
44
    protected static function error($message = null)
45
    {
46
        if (isset($message)) {
47
            self::$errors[] = $message;
48
        } else {
49
            return empty(self::$errors) ? null :
50
                '<p class="tbl-err">' . implode('</br>', self::$errors) . '</p>';
51
        }
52
    }
53
54
    private static function valid($key, $val = null)
55
    {
56
        if (!array_key_exists($key, self::$config)) {
57
            throw new Exception('Request to undefined value: ' . $key);
58
        }
59
60
        if ($val !== null) {
61
            if (empty($val) || gettype($val) !== gettype(self::$config[$key])) {
62
                throw new Exception("Setting invalid value: $val (:$key)");
63
            }
64
        }
65
66
        return $val === null ? self::$config[$key] : $val;
67
    }
68
}
69