Filtering by Date in a Mock Drupal 8 API
While working on a visualization, I was using a JSON file from an internal API for development purposes. I then needed to test date filters so I created a route to mimic the API using the JSON file as the response.
The JSON file lived at my_module/data/data.json
. All I needed after that is a route and a method to process the request:
Route in my_module.routing.yml
:
my_module.mock:
path: '/my_module/api/documents'
defaults:
_controller: '\Drupal\my_module\Controller\MyModuleController::getDocuments'
requirements:
_permission: 'access content'
Here is the method that processes the rquest (in my_module/src/Controller/MyModuleController.php
):
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Serialization\Json;
use Symfony\Component\HttpFoundation\JsonResponse;
...
class MyModuleController extends ControllerBase {
private $fromDate = null;
private $toDate = null;
...
/**
* Returns mock proceedings data for debugging purposes.
*/
public function getDocuments(Request $request) {
// Get date filters.
$params = $request->query->all();
if (!empty($params)) {
if (isset($params['fromDate'])) {
$fdate = \DateTime::createFromFormat('Y-m', $params['fromDate']);
$this->fromDate = $fdate->format('Y-m');
}
if (isset($params['toDate'])) {
$tdate = \DateTime::createFromFormat('Y-m', $params['toDate']);
$this->toDate = $tdate->format('Y-m');
}
}
// Get module path.
$handler = \Drupal::service('module_handler');
$path = $handler->getModule('my_module')->getPath();
// Read file.
$json = file_get_contents($path . '/data/data');
$data = Json::decode($json);
// Filter data if requested.
if (!empty($this->fromDate) && !empty($this->fromDate)) {
$filtered = array_filter($data['results'], function($value, $key) {
$create_date_raw = \DateTime::createFromFormat('m-d-Y', $value['createDate']);
$create_date = $create_date_raw->format('Y-m');
return ($create_date >= $this->fromDate && $create_date <= $this->toDate);
}, ARRAY_FILTER_USE_BOTH);
$data['results'] = array_values($filtered);
}
return new JsonResponse($data);
}
...
}
- Request the data:
curl -s 'http://dev.local/my_module/api/documents?fromDate=2018-01&toDate=2018-01' | python -m 'json.tool'
{
"results": [
{
"createDate": "01-03-2018",
"name": "document1",
}
]
}