Skip to content

Instantly share code, notes, and snippets.

@nateabele
Last active December 17, 2015 20:28
Show Gist options
  • Save nateabele/5667381 to your computer and use it in GitHub Desktop.
Save nateabele/5667381 to your computer and use it in GitHub Desktop.
Example of configuring `li3_resources` queries to automatically extract values from request parameters, with fallbacks to default values. **Note:** exposing elements of a query to arbitrary input (i.e., high query limits) is not advisable. The needs and context of the application should always be considered, and input should be filtered and/or s…
<?php
/**
* Snippet extracted from `config/bootstrap/action.php`.
*/
/**
* ## Mapping HTTP Request Parameters to Query Parameters
*
* The `$replacer` function is used by the `Resources` filter below to allow resource classes to
* automatically map values from the `Request` object in their query configurations.
*
* For example, a resource object may specify a limit on a query by doing the following:
*
* protected $_parameters = [
* 'index' => ['items' => ['call' => ['limit' => 'query:limit | 10']]]
* ];
*
* In this example, the `index()` method of the resource would query the `Items` model with a
* default limit of 10 documents. However, an HTTP request could override this by appending
* `?limit=11` to the URL.
*/
$replacer = function($request, array $data) use (&$replacer) {
foreach ($data as $key => $value) {
if (is_array($value)) {
$data[$key] = $replacer($request, $value);
continue;
}
if (is_string($value) && preg_match('/^(params|data|query):.+/', $value)) {
list($getter, $default) = array_map('trim', explode('|', $value) + ['', '']);
if (($value = $request->get($getter)) === null) {
$value = strtotime($default) ?: $default;
}
}
$data[$key] = $value;
}
return $data;
};
Resources::applyFilter('get', function($self, $params, $chain) use ($replacer) {
/**
* Get parameters and process the query configuration through `$replacer`.
*/
$params['options']['call'] = $replacer($params['request'], (array) $params['options']['call']);
return $chain->next($self, $params, $chain);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment