Passed
Branchmaster (ef65d2)
by Plamen
02:16 queued 16s
created

trait_tfoot_setter::qOrder()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 7
rs 10
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
    /** Adds conditions, orderBy and Limits to query.
78
     * @param string $q
79
     * @param mixed $cond
80
     * @param array $order
81
     * @param mixed $limit -> 5 or [$start, $count]
82
     * @param bool $h Having flag - to use HAVING instead of WHERE
83
     * @return (string) */
84
    protected static function q($q, $cond = null, array $order = [], $limit = 0, $h = false)
85
    {
86
        //Condition: '' | ' (HAVING|WHERE|AND) ' . $cond
87
        self::qConditions($q, $cond, $h);
88
        
89
        //Order: '' | 'ORDER BY ' . array_keys($order)[0] . ' ' . $order[0]
90
        self::qOrder($q, $order);
91
        
92
        //Limit: '' | ' LIMIT ' . '(20, 40|20)'
93
        self::qLimit($q, $limit);
94
95
        return $q;
96
    }
97
    
98
    private static function qConditions(&$q, $cond, $h)
99
    {
100
        if(!empty($cond)){
101
            $clause = !$h ? 'WHERE' : 'HAVING';
102
            $clue = !strpos($q, $clause) ? $clause : 'AND';
103
            $q .= (' ' . $clue . ' ' . $cond);
104
        }
105
    }
106
    
107
    private static function qOrder(&$q, $order)
108
    {
109
        if(!empty($order)){
110
            $arr = array_map(function(&$v, $k) {
111
                    return $k . ' ' . strtoupper($v);
112
                }, $order, array_keys($order));
113
            $q .= (' ORDER BY ' . implode(', ', $arr));
114
        }
115
    }
116
    
117
    private static function qLimit(&$q, $limit)
118
    {
119
        if(!empty($limit)){
120
            $l = (is_array($limit) ? implode(', ', $limit) : $limit);
121
            $q .= (' LIMIT ' . $l);
122
        }
123
    }
124
125
    protected static function err($message = null)
126
    {
127
        if (isset($message)) {
128
            self::$errors[] = $message;
129
        } else {
130
            return empty(self::$errors) ? null :
131
                    '<p class="tbl-err">' . implode('</br>', self::$errors) . '</p>';
132
        }
133
    }
134
135
    /** Converts array to space separated key value list
136
     * @param array $attributes
137
     * @return string */
138
    protected static function attributes(array $attributes)
139
    {
140
        $list = [];
141
        foreach ($attributes as $key => $value) {
142
            if (is_bool($value)) {
143
                if ($value === true) {
144
                    $list[] = $key;
145
                }
146
            } else if (empty($value) && $value != 0) {
147
                $list[] = $key;
148
            } else {
149
                $list[] = $key . '="' . $value . '"';
150
            }
151
        }
152
        return (count($list) > 0 ? ' ' : '') . join(' ', $list);
153
    }
154
155
    /** Parses view to string
156
     * @param string $template
157
     * @param array $vars
158
     * @return string */
159
    protected static function view($template, $vars = [])
160
    {
161
        extract($vars);
162
        ob_start();
163
        require $template;
164
        return (string) ob_get_clean();
165
    }
166
    /*     * Makes code radey for the next table
167
     * @param type $tableId
168
     */
169
170
    protected static function reset($tableId)
171
    {
172
        if (!in_array($tableId, self::$t["tables"])) {
173
            self::$t["tables"][] = $tableId;
174
            self::$cols = [];
175
            self::$t['rows'] = null;
176
        } else {
177
            echo 'Existing table-id used in table::create(): ' . $tableId;
178
        }
179
    }
180
}
181