TraitConfig::config()   A
last analyzed

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
    /**
23
     * Set/Get config value.
24
     *
25
     * @param mixed $value (string) Get if exists, (array) Set if valid
26
     *
27
     * @return mixed
28
     */
29
    public static function config($value)
30
    {
31
        try {
32
            switch (gettype($value)) {
33
                case 'array':
34
                    foreach ($value as $k => $v) {
35
                        self::$config[$k] = self::valid((string) $k, $v);
36
                    }
37
                    break;
38
                case 'string':
39
                    return self::valid($value);
40
                default:
41
                    throw new Exception('Invalid value type.');
42
            }
43
        } catch (Exception $e) {
44
            self::error('ERROR: '.$e->getMessage());
45
        }
46
    }
47
48
    protected static function error($message = null)
49
    {
50
        if (isset($message)) {
51
            self::$errors[] = $message;
52
        } else {
53
            return empty(self::$errors) ? null :
54
                '<p class="tbl-err">'.implode('</br>', self::$errors).'</p>';
55
        }
56
    }
57
58
    private static function valid($key, $val = null)
59
    {
60
        if (!array_key_exists($key, self::$config)) {
61
            throw new Exception('Request to undefined value: '.$key);
62
        }
63
64
        if ($val !== null) {
65
            if (empty($val) || gettype($val) !== gettype(self::$config[$key])) {
66
                throw new Exception("Setting invalid value: $val (:$key)");
67
            }
68
        }
69
70
        return $val === null ? self::$config[$key] : $val;
71
    }
72
}
73