Passed
Branchmaster (131059)
by Plamen
01:29
created

trait_tfoot_setter::config()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 5
eloc 12
c 3
b 1
f 0
nc 8
nop 1
dl 0
loc 16
rs 9.5555
1
<?php
2
3
trait trait_tfoot_setter
4
{
5
    /** @param array Columns (config) */
6
    public static $cols;
7
    /** @param array Query result, allows altering before table::load() */
8
    public static $data = [];
9
    /** @param bool Export flag (for current request) */
10
    public static $export;
11
    /** @param bool Export is allowed (shows buttons in the tfoot) */
12
    public static $exportActive = true;
13
    /** @param bool Export data altered (use false for pure result) */
14
    public static $exportDataAsDisplayed = true;
15
    /** @param array Collector (values for current table call) */
16
    protected static $t = ['page' => 1, 'tables' => []];
17
    /** @param array Re-settable values for current table call */
18
    protected static $config = [
19
                    'APP' => 'App',
20
                    'DB_COLLATION_CI' => 'utf8mb4_general_ci', //UTF8_GENERAL_CI
21
                    'EMPTY_TABLE_MSG' => 'No results found.',
22
                    'EXPORT_FILE_NAME' => ':app - :items export (:datetime)',
23
                    'FILTER_ACTIVE' => true,
24
                    'FILTER_CASE_SENSITIVE' => false,
25
                    'SAVES' => ['CSV', 'Excel'],
26
                    'UTF8_ASC_SYMBOL' => '&#9650;',
27
                    'UTF8_DESC_SYMBOL' => '&#9660;',
28
                    'UTF8_LEFT_SYMBOL' => '&lsaquo;',
29
                    'UTF8_RIGHT_SYMBOL' => '&rsaquo;'
30
                ];
31
    /** @param array Errors collector */
32
    protected static $errors = [];
33
34
    static function assets($path = "/public/table")
35
    {
36
        return "<script src=\"{$path}/table.js\"></script>\n\t" .
37
                "<link href=\"{$path}/table.css\" rel=\"stylesheet\">\n";
38
    }
39
40
    /** Set/Get config value
41
     * @param mixed $c (string) Get if exists, (array) Set if valid
42
     * @return mixed */
43
    public static function config($c)
44
    {
45
        try {
46
            switch (gettype($c)) {
47
                case 'array';
48
                    foreach ($c as $k => $v) {
49
                        self::$config[$k] = self::getValid((string) $k, $v);
50
                    }
51
                    break;
52
                case 'string':
53
                    return self::getValid($c);
54
                default:
55
                    throw new Exception("Invalid value type.");
56
            }
57
        } catch (Exception $e) {
58
            self::err('ERROR: ' . $e->getMessage());
59
        }
60
    }
61
    
62
    private static function getValid($k, $v = null)
63
    {
64
         if (!array_key_exists($k, self::$config)) {
65
                throw new Exception('Request to undefined value: ' . $k);
66
        }
67
68
        if ($v !== null) {
69
            if (empty($v) || gettype($v) !== gettype(self::$config[$k])) {
70
                throw new Exception("Setting invalid value: $v (:$k)");
71
            }
72
        }
73
74
        return $v === null ? self::$config[$k] : $v;
75
    }
76
77
78
    /** Adds conditions, orderBy and Limits to query.
79
     * @param string $q
80
     * @param mixed $cond
81
     * @param array $order
82
     * @param mixed $limit -> 5 or [$start, $count]
83
     * @param bool $h Having flag - to use HAVING instead of WHERE
84
     * @return (string) */
85
    protected static function q($q, $cond = null, array $order = [], $limit = 0, $h = false)
86
    {
87
        //Condition: '' | '(HAVING|WHERE|AND) ' . $cond
88
        $c = !empty($cond) && !strpos($q, ($cl = !$h ? 'WHERE' : 'HAVING')) ?
89
                (' ' . (!strpos($q, $cl) ? $cl : ' AND ') . ' ' . $cond ) :
90
                '';
91
        //Order: '' | 'ORDER BY ' . array_keys($order)[0] . ' ' . $order[0]
92
        $o = !empty($order) ?
93
                ' ORDER BY ' . implode(', ',
94
                        array_map(function(&$v, $k) {
95
                            return $k . ' ' . strtoupper($v);
96
                        }, $order, array_keys($order))
97
                ) :
98
                '';
99
        //Limit: '' | ' LIMIT ' . '(20, 40|20)'
100
        $l = !empty($limit) ?
101
                (' LIMIT ' . (is_array($limit) ? implode(', ', $limit) : $limit)) :
102
                '';
103
104
        return $q . $c . $o . $l;
105
    }
106
107
    protected static function err($message = null)
108
    {
109
        if (isset($message)) {
110
            self::$errors[] = $message;
111
        } else {
112
            return empty(self::$errors) ? null :
113
            '<p class="tbl-err">' . implode('</br>', self::$errors) . '</p>';
114
        }
115
    }
116
117
    /** Converts array to space separated key value list
118
     * @param array $attributes
119
     * @return string */
120
    protected static function attributes(array $attributes)
121
    {
122
        $list = [];
123
        foreach ($attributes as $key => $value) {
124
            if (is_bool($value)) {
125
                if ((bool) $value) {
126
                    $list[] = $key;
127
                }
128
            } else if (empty($value) && !is_int($value)) {
129
                $list[] = $key;
130
            } else {
131
                $list[] = $key . '="' . $value . '"';
132
            }
133
        }
134
        return (count($list) > 0 ? ' ' : '') . join(' ', $list);
135
    }
136
137
    /** Parses view to string
138
     * @param string $template
139
     * @param array $vars
140
     * @return string */
141
    protected static function view($template, $vars = [])
142
    {
143
        extract($vars);
144
        ob_start();
145
        require $template;
146
        return (string) ob_get_clean();
147
    }
148
149
    /**Makes code radey for the next table
150
     * @param type $tableId
151
     */
152
    protected static function reset($tableId)
153
    {
154
        if (!in_array($tableId, self::$t["tables"])) {
155
            self::$t["tables"][] = $tableId;
156
            self::$cols = [];
157
            self::$t['rows'] = null;
158
        } else {
159
            echo 'Existing table-id used in table::create(): ' . $tableId;
160
        }
161
    }
162
}
163