summaryrefslogtreecommitdiff
path: root/public/app/controllers/api/Common_api.php
blob: a8bd75f428bf865983f2994d0d7c9acb3f3d6d1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<?php 

namespace app\controllers\api;

use \Registry;
use app\models\market\Product_model;
use app\models\market\ProductCategories_model;

/** Common_api
 * ---
 * Controller for handling common API calls
 * about main tables of the project;
 * 
 * includes aglo for passing special filters and sorting
 * (check parse_Where_OrderBy() method)
 */
class Common_api
{

    /** APITables
     * Method returns allowed tables to accept API calls
     * The return is an array of [label => data-source] pairs
     * where 'label' is a friendly name of the datasource
     * (and 'datasource' the actual table/data-source)
     */
    public static function APITables()
    {
        /** allowed tables for api call
         * @return: (array) an of api-call arrays
         * each api-call array has the folloing form:
         * [ label => [
         *     'table' => (string) actual table in database,
         *     (optional) 'filter' => (array) of allowed filtering fields,
         *     (optional) 'sort' => (array) of allowed sorting fields,
         *   ]
         * ]
         */
        return [
            'page' => [
                'table' => 'pages',
                'filter' => ['Title']
            ],
            'product' => [
                'table' => 'products',
                'filter' => [ 'ID', 'Title' ],
                'sort' => ['ID']
            ],
            'category' => [
                'table' => 'product_categories',
                'filter' => ['Title', 'Hierarchy', 'Level']
            ]
        ];
    }


    /** select anything on any (allowed table)
     * + supports filtering and sorting
     * check self::parse_Where_OrderBy() for options;
     * sets a limti of 1000 records
     */
    public static function table($table)
    {
        $sources = self::APITables();
        if (array_key_exists($table, $sources)) {

            $query = Registry::get('REQUEST')->QUERY;

            // Get parametres? => parse filters
            if ($query !== false) {

                $parsed = self::parse_Where_OrderBy(
                    $query,
                    ($sources[$table]['filter'] ?? []),
                    ($sources[$table][ 'sort' ] ?? [])
                );
                $where = $parsed['filter'] ? (' WHERE ' . $parsed['filter']) : '';
                $orderBy = $parsed['sort'] ? (' ORDER BY '. $parsed['sort']) : '' ;
                $bindArguments = $parsed['bind'];

            } else {
                $where = '';
                $orderBy = '';
                $bindArguments = [];
            }

            $db = Registry::use('database');
            $result = $db->runQuery('SELECT *
                FROM '. $sources[$table]['table']
                . $where
                . $orderBy
                .' LIMIT 1000',
                $bindArguments
            );

            reply_json([
                'success' => true,
                'client' => Registry::get('REQUEST')->SIGNATURE,
                'result' => $result
            ]);

        } else {
            reply_json(['success' => false]);
        }
        die();
    }


    /** get record of {table} by ID
     * (if table has no ID then return false)
     */
    public static function record($table, $id)
    {
        $sources = self::APITables();
        if (array_key_exists($table, $sources)) {

            $db = Registry::use('database');
            $result = $db->runQuery("SELECT *
                FROM ". $sources[$table]['table'] ."
                WHERE ID = :id",
                [':id' => $id]
            );
            reply_json([
                'success' => true,
                'data' => $result[0]
            ]);
            
        } else {
            reply_json(['status' => false]);
            
        }
        die();
    }


    /** category_by_url
     * product categorie by full-friendly-URL
     * @param $url (string): full friendly url
     */
    public static function category_by_url($url)
    {
        $category = proxy(
            [\app\models\market\ProductCategories_model::class, 'categoryFromUrl'],
            [ $url ], CACHE_CATEGORY_TTL
        );
        if ($category !== false) {
            reply_json([
                'success' => true,
                'result' => $category
            ]);

        } else {
            reply_json(['status' => false]);
            
        }
        die();
    }

    /** parse Where & OrderBy
     * -------------------------------------------------------------------------
     * parses SAFELY the query string to Where {CONDITIONS} and ORDER BY clauses
     * according to the specified rules.
     * 
     * The rules:
     * ** filters: ?fieldname=[operator]:value &...
     * where operators:[ like | startlike | endlike | eq | gt | gteq | lt |t leq ]
     * 
     * ** Order by: ?_sort=fieldname[:[asc|desc]][,field[,]]
     * 
     * for example: ?id=gt:4&active=1&_sort:reputation:desc,category
     * parses to WHERE id > 4 AND active = 4 ORDER BY reputation desc, catetory asc
     * 
     * -------------------------------------------------------------------------
     * arguments:
     * @param $query (string): string to be parsed
     * @param $filters (array): the allowed fields to apply filters
     * @param $sortings (array): the allowed fields to sort the result
     * @return array('filter'=>(string) , 'sort'=>(string) , 'bind'=>(array))
     */
    private static function parse_Where_OrderBy($query, $filters=[], $sortings=[])
    {
        // break query to [key => value] pairs
        parse_str($query, $queryArray);

        $filterClause = [];     // array to hold filter/WHERE clauses
        $sortClause = [];       // array to hold sort/ORDER-BY caluses
        $bindings = [];         // array to hold variable bindigs 

        // parse filers
        // ---------------------------------------------------------------------
        foreach($queryArray as $filter => $value) {

            if (in_array($filter, $filters)) {

                $parts = explode(':', $value );  // that is => [operator], value
                if (count($parts) == 0) {
                    // forget it

                } else if (count($parts) == 1) {
                    $filterClause[] = "{$filter} = :{$filter}";
                    $bindings[$filter] = $parts[0];

                } else {

                    switch ($parts[0]) {
                        case 'like':
                            $filterClause[] = "{$filter} LIKE :{$filter}";
                            $bindings[':'.$filter] = '%'.$parts[1].'%';
                            break;

                        case 'startlike':
                            $filterClause[] = "{$filter} LIKE :{$filter}";
                            $bindings[':'.$filter] = $parts[1].'%';
                            break;

                        case 'endlike':
                            $filterClause[] = "{$filter} LIKE :{$filter}";
                            $bindings[':'.$filter] = '%'.$parts[1];
                            break;

                        case 'gt':
                            $filterClause[] = "{$filter} > :{$filter}";
                            $bindings[':'.$filter] = $parts[1];
                            break;

                        case 'gteq':
                            $filterClause[] = "{$filter} >= :{$filter}";
                            $bindings[':'.$filter] = $parts[1];
                            break;

                        case 'lt':
                            $filterClause[] = "{$filter} < :{$filter}";
                            $bindings[':'.$filter] = $parts[1];
                            break;

                        case 'lteq':
                            $filterClause[] = "{$filter} <= :{$filter}";
                            $bindings[':'.$filter] = $parts[1];
                            break;
                        
                        case 'eq':
                        default:
                            $filterClause[] = "{$filter} = :{$filter}";
                            $bindings[':'.$filter] = $parts[1];
                    }
                }
            }
        }
        $whereSQL = ($filterClause == [])
            ? false
            : implode(' AND ', $filterClause);


        // parse sort options
        // ---------------------------------------------------------------------
        if (isset($queryArray['_sort'])) {
            $sortTerms = explode(',', $queryArray['_sort']);

            foreach($sortTerms as $term) {

                $parts = explode(':', $term);
                if ($parts != [] && in_array($parts[0], $sortings) ) {
                    $sortClause[] = (count($parts)==1)
                        ? $parts[0]
                        : $parts[0] .' '. (($parts[1] == 'desc') ? 'desc' : 'asc');
                }
            }

        }
        $sortSQL = ($sortClause == [])
            ? false
            : implode(', ', $sortClause);
              
        return ([
            'filter' => $whereSQL,
            'sort' => $sortSQL,
            'bind' => $bindings
        ]);

    }

}