Passed
Branchmaster (9e6d59)
by Plamen
01:23
created

table.php (1 issue)

1
<?php
2
3
/** Note: table::prepare() - call must come before `headers_sent()`;
4
 *     1. Create (initial setup):
5
 *        <code>table::create('tableId', 'sortByDbCol', 'sortDirection');</code>
6
 *     1.1. Set columns to be displayed: <code>
7
 *          table::$cols[] = ['innerHtml', 'dbColumn|Name',
8
 *                                      ['width'=>'?px','sort'=>false]];</code>
9
 *     2. Execute (data query)
10
 *        <code>table::execute(sqlQuery);</code>
11
 *     2.1. Alter loaded data, before table load <code>
12
 *          foreach(table::$data as $r => &$cells){
13
 *              $cells['id'] = $cells['id']==3 ?
14
 *                              [$cells['id'] ,['class'=>'red']] : $cells['id'];
15
 *          }</code>
16
 *     3. Loads the markup, or json data (on sort/page/export etc. actions).
17
 *        <code>table::load();</code> */
18
class table extends table_getter
19
{
20
    /** @param string class name, where $helper::prepare() is expected */
21
    public static $helper_class;
22
    /** @param closure to MySql select function (example: db::select()) */
23
    public static $select;
24
25
    /** #1. Create (setup)
26
     * @param string $items - The items name
27
     * @param string $orderBy - a db column name
28
     * @param string $orderDir - (Default: self::DEFAULT_SORT_ORDER)
29
     * @param int $paging - Rows per page */
30
    public static function create(
31
            $items,
32
            $orderBy,
33
            $orderDir = 'asc',
34
            $paging = 10
35
    )
36
    {
37
        self::reset((self::$t['items'] = $items));
38
        self::prepare(true);
39
        self::$t['order']['col'] = $orderBy;
40
        $dir = strtolower($orderDir);
41
        self::$t['order']['dir'] = in_array($dir, ['asc', 'desc']) ?
42
                $dir : self::err('Invalid orderDir (Asc/Desc): ' . $orderDir);
43
        self::$t['paging'] = ($p = abs($paging)) > 10 ?
44
                $p : self::err('Invalid paging (>10): ' . $paging);
45
    }
46
47
    /** #2. Execute (queries)
48
     * @param string $q - query for the table data;
49
     * @param (null)|string $qTotal - simple version of $sql if applicable
50
     * (used only for Total count in the table footer).<br>
51
     * Example: <pre>$sql = 'SELECT `id`, ... FROM `table` WHERE ...'</pre>
52
     * For query to many thousands results, will be faster to have:
53
     * <pre>$sqlTotals = 'SELECT `id` FROM `table` WHERE ...'</pre> */
54
    public static function execute($q, $qTotal = null)
55
    {
56
        self::$t['order']['col'] = self::requestOrderCol();
57
        self::$t['order']['dir'] = self::requestOrderDir();
58
        self::$t['page'] = self::requestPage();
59
        self::$export = self::requestExport();
60
61
        $filter = self::requestFilter();
62
        $order = [self::$t['order']['col'] => self::$t['order']['dir']];
63
        $offset = (self::$t['page'] - 1) * self::$t['paging'];
64
        $limit = [$offset, self::$t['paging']];
65
        self::$t['q'] = self::q($q, $filter, $order, $limit, true);
66
67
        $qAll = isset($qTotal) && !$filter ? $qTotal : $q;
68
        $orderAll = !self::$export ? [] : $order;
69
        self::$t['qAll'] = self::q($qAll, $filter, $orderAll, 0, true);
70
71
        $query = !self::$export ? self::$t['q'] : self::$t['qAll'];
72
73
        try {
74
            self::$data = self::select($query);
75
        } catch (Exception $e) {
76
            self::err('ERROR: ' . $q . '<br />' . $e->getMessage());
77
        }
78
    }
79
80
    /** #3. Loads output (html, json or csv file) */
81
    public static function load()
82
    {
83
        if (self::$pageExt !== 'json') {
84
            echo parent::load();
85
        } else {
86
            ob_get_clean();
87
            $tableId = filter_input(INPUT_GET, 'table-id') ?: null;
88
            if ($tableId === self::$t['items'] . '-table') {
89
                if (!self::$export) {
90
                    header('Content-Type: application/json');
91
                    $jsonArr = ['body' => self::jsonGetBodyData(),
92
                        'footer' => self::jsonGetFooterData()];
93
                    die(json_encode($jsonArr));
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
94
                } else {
95
                    self::exportData();
96
                }
97
            }
98
        }
99
    }
100
101
    /** Adds needed JavaScript and CSS into the page header, it has to be
102
     * included before "headers_sent()"
103
     * @param str|bool $setOrCheck - uses helper class to verify own load */
104
    public static function prepare($setOrCheck = false)
105
    {
106
        //@see  http://php.net/manual/es/function.filter-input.php#77307
107
        $uri = filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_URL) ?:
108
                filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL);
109
110
        $extension = pathinfo(strtok($uri, '?'), PATHINFO_EXTENSION);
111
112
        self::$t['slug'] = pathinfo($uri, PATHINFO_BASENAME);
113
        self::$pageExt = strtolower($extension);
114
115
        if (self::$helper_class::prepare(__METHOD__, $setOrCheck) !== true) {
116
            if (self::$pageExt === 'json' && !isset(self::$t['prepared'])) {
117
                ob_start();
118
                self::$t['prepared'] = true;
119
            }
120
        }
121
    }
122
}
123