Hello,
I need to create REST API that publishes data obtained from another application in form of JSON for example in following form (simplified)
$container['json'] = function($c) {
//sensorstatus -a
$sensor = '{"SensorType": "s1", "MessageType": "s1", "AppVersion": "3.3.18+", "HwInfo": "0x100", "Threshold": 50, "Temperature": "25.4", "Humidity": "31.4" }';
return $sensor;
};
I have some mapping table that contains useful info like whether the value can be written, ranges etc.
$device_d = array(
"SensorType" => array(R, NULL),
"AppVersion" => array(R, NULL),
"HwInfo" => array(R, NULL),
"Threshold" => array(RW, v::numeric()->positive()->between(1, 100)),
"Antiflicker" => array(R, NULL),
"Temperature" => array(R, NULL),
"Humidity" => array(R, NULL),
"Restart" => array(W, NULL),
);
$validators_device = array_filter(array_combine(array_keys($device_d), array_column(array_values($device_d), 1)));
I do not want to have separate route for each key so I use route placeholder and the table helps me to check if the placeholder is valid.
$mw = function ($request, $response, $next) use ($device_d) {
$key = $request->getAttribute('route')->getArgument('key');
if (!in_array($key, array_keys($device_d)))
throw new \Slim\Exception\NotFoundException($request, $response);
$response = $next($request, $response);
return $response;
};
$app->group('/device', function (App $app) {
$this->get('/{key:[a-zA-Z]+}', function (Request $request, Response $response, array $args) {
$key = $args['key'];
$json = $this->json;
$j = json_decode($json, true);
$response = $response->withJson(json_encode(array($key => $j[$key])));
return $response;
});
$this->post('/{key:[a-zA-Z]+}', function (Request $request, Response $response, array $args) {
echo var_dump($request->getParams());
echo var_dump($request->getAttribute('errors'));
});
})->add($mw)->add(new \DavidePastore\Slim\Validation\Validation($validators_device));
I would like to get some opinions here if this is a suitable way.
I’m also not sure how to use validators correctly here. In fact I need them just for input data (post route) and I need to check only the active key at a time…
best regards
Jan