Passed
Branchmaster (334046)
by Plamen
01:29
created

trait_tfoot_setter::config()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 30
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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