Passed
Branchmaster (fe8a83)
by Plamen
01:34
created

table.php (4 issues)

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 :
43
                die('Invalid orderDir(Asc/Desc): ' . $orderDir);
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...
44
        self::$t['paging'] = ($p = abs($paging)) > 10 ?
45
                $p :
46
                die('Invalid paging(>10): ' . $paging);
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...
47
    }
48
49
    /** #2. Execute (queries)
50
     * @param string $q - query for the table data;
51
     * @param (null)|string $qTotal - simple version of $sql if applicable
52
     * (used only for Total count in the table footer).<br>
53
     * Example: <pre>$sql = 'SELECT `id`, ... FROM `table` WHERE ...'</pre>
54
     * For query to many thousands results, will be faster to have:
55
     * <pre>$sqlTotals = 'SELECT `id` FROM `table` WHERE ...'</pre> */
56
    public static function execute($q, $qTotal = null)
57
    {
58
        self::$t['order']['col'] = self::requestOrderCol();
59
        self::$t['order']['dir'] = self::requestOrderDir();
60
        self::$t['page'] = self::requestPage();
61
        self::$export = self::requestExport();
62
63
        $filter = self::requestFilter();
64
        $order = [self::$t['order']['col'] => self::$t['order']['dir']];
65
        $offset = (self::$t['page'] - 1) * self::$t['paging'];
66
        $limit = [$offset, self::$t['paging']];
67
        self::$t['q'] = self::q($q, $filter, $order, $limit, true);
68
69
        $qAll = isset($qTotal) && !$filter ? $qTotal : $q;
70
        $orderAll = !self::$export ? [] : $order;
71
        self::$t['qAll'] = self::q($qAll, $filter, $orderAll, 0, true);
72
73
        $query = !self::$export ? self::$t['q'] : self::$t['qAll'];
74
75
        try {
76
            self::$data = self::select($query);
77
        } catch (Exception $e) {
78
            die('ERROR (query in the table): ' . "\n$q\n" . $e->getMessage());
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...
79
        }
80
    }
81
82
    /** #3. Loads output (html, json or csv file) */
83
    public static function load()
84
    {
85
        if (self::$pageExt !== 'json') {
86
            echo parent::load();
87
        } else {
88
            ob_get_clean();
89
            $tableId = filter_input(INPUT_GET, 'table-id') ?: null;
90
            if ($tableId === self::$t['items'] . '-table') {
91
                if (!self::$export) {
92
                    header('Content-Type: application/json');
93
                    $jsonArr = ['body' => self::jsonGetBodyData(),
94
                        'footer' => self::jsonGetFooterData()];
95
                    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...
96
                } else {
97
                    self::exportData();
98
                }
99
            }
100
        }
101
    }
102
103
    /** Adds needed JavaScript and CSS into the page header, it has to be
104
     * included before "headers_sent()"
105
     * @param str|bool $setOrCheck - uses helper class to verify own load */
106
    public static function prepare($setOrCheck = false)
107
    {
108
        //@see  http://php.net/manual/es/function.filter-input.php#77307
109
        $uri = filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_URL) ?:
110
                filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL);
111
112
        $extension = pathinfo(strtok($uri, '?'), PATHINFO_EXTENSION);
113
114
        self::$t['slug'] = pathinfo($uri, PATHINFO_BASENAME);
115
        self::$pageExt = strtolower($extension);
116
117
        if (self::$helper_class::prepare(__METHOD__, $setOrCheck) !== true) {
118
            if (self::$pageExt === 'json' && !isset(self::$t['prepared'])) {
119
                ob_start();
120
                self::$t['prepared'] = true;
121
            }
122
        }
123
    }
124
}
125