Skip to content

Instantly share code, notes, and snippets.

@eminetto
Created August 29, 2015 19:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eminetto/f9e44c18314b7aaaf66b to your computer and use it in GitHub Desktop.
Save eminetto/f9e44c18314b7aaaf66b to your computer and use it in GitHub Desktop.
<?php
use Aura\Router\RouterFactory;
use Zend\Expressive\AppFactory;
use Zend\Expressive\Router\Aura as AuraBridge;
use Zend\Diactoros\Response\JsonResponse;
use RestBeer\Auth;
$loader = require __DIR__.'/vendor/autoload.php';
$loader->add('RestBeer', __DIR__.'/src');
$auraRouter = (new RouterFactory())->newInstance();
$router = new AuraBridge($auraRouter);
$api = AppFactory::create(null, $router);
$db = new PDO('sqlite:beers.db');
$beers = array(
'brands' => array('Heineken', 'Guinness', 'Skol', 'Colorado'),
'styles' => array('Pilsen' , 'Stout')
);
$api->get('/', function ($request, $response, $next) {
$response->getBody()->write('Hello, beers of world!');
return $response;
});
$api->get('/brand', function ($request, $response, $next) use ($beers) {
return new JsonResponse($beers['brands']);
});
$api->get('/style', function ($request, $response, $next) use ($beers) {
return new JsonResponse($beers['styles']);
});
$api->get('/beer{/id}', function ($request, $response, $next) use ($beers) {
$id = $request->getAttribute('id');
if ($id == null) {
return new JsonResponse($beers['brands']);
}
$key = array_search($id, $beers['brands']);
if ($key === false) {
return new JsonResponse('Not found', 404);
}
return new JsonResponse($beers['brands'][$key]);
});
$api->post('/beer', function ($request, $response, $next) use ($db) {
$db->exec(
"create table if not exists beer (id INTEGER PRIMARY KEY AUTOINCREMENT, name text not null, style text not null)"
);
$data = $request->getParsedBody();
if (! isset($data['name']) || ! isset($data['style'])) {
return new JsonResponse('Missing parameters', 400);
}
//@TODO: clean form data before insert into the database ;)
$stmt = $db->prepare('insert into beer (name, style) values (:name, :style)');
$stmt->bindParam(':name',$data['name']);
$stmt->bindParam(':style', $data['style']);
$stmt->execute();
$data['id'] = $db->lastInsertId();
return new JsonResponse($data);
});
$app = AppFactory::create();
$app->pipe(new Auth);
$app->pipe($api);
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment