/** * Create a resource and all its sub-resources. * * @param array $resourceConfig * @param array $parentUris * @throws \RuntimeException */ public function createResource(array $resourceConfig, array $parentUris = array()) { if (empty($resourceConfig['uri']) || empty($resourceConfig['ctl'])) { throw new \RuntimeException('Invalid resource config encountered. Config must contain uri and ctl keys'); } if ($resourceConfig['ctl'] instanceof \Closure) { //registers controller factory inline $controllerName = $this->registerController($resourceConfig['uri'], $resourceConfig['ctl'], $parentUris); } elseif (is_string($resourceConfig['ctl'])) { $controllerName = $resourceConfig['ctl']; } else { throw new \RuntimeException('Ctl must be a factory (Closure) or existing service (string name)'); } //setup routes $this->app->get($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:get', $controllerName)); $this->app->get($this->createRouteUri($resourceConfig['uri'], $parentUris, false), sprintf('%s:cget', $controllerName)); $this->app->post($this->createRouteUri($resourceConfig['uri'], $parentUris, false), sprintf('%s:post', $controllerName)); $this->app->put($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:put', $controllerName)); $this->app->patch($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:patch', $controllerName)); $this->app->delete($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:delete', $controllerName)); //handle sub resources if (!empty($resourceConfig['sub'])) { if (!is_array($resourceConfig['sub'])) { throw new \RuntimeException('sub config must contain array of sub resources'); } //append current uri as parent $parentUris[] = $resourceConfig['uri']; foreach ($resourceConfig['sub'] as $subResource) { $this->createResource($subResource, $parentUris); } } }
public function register(BaseApplication $app) { // リポジトリ $app['eccube.plugin.product_rank.repository.product_rank'] = $app->share(function () use($app) { return new ProductRankRepository($app['orm.em'], $app['orm.em']->getClassMetadata('\\Eccube\\Entity\\ProductCategory'), $app); }); $basePath = '/' . $app["config"]["admin_route"]; // 一覧 $app->match($basePath . '/product/product_rank/', '\\Plugin\\ProductRank\\Controller\\ProductRankController::index')->bind('admin_product_product_rank'); // 一覧:上 $app->put($basePath . '/product/product_rank/{category_id}/{product_id}/up', '\\Plugin\\ProductRank\\Controller\\ProductRankController::up')->assert('category_id', '\\d+')->assert('product_id', '\\d+')->bind('admin_product_product_rank_up'); // 一覧:下 $app->put($basePath . '/product/product_rank/{category_id}/{product_id}/down', '\\Plugin\\ProductRank\\Controller\\ProductRankController::down')->assert('category_id', '\\d+')->assert('product_id', '\\d+')->bind('admin_product_product_rank_down'); // 一覧:N番目へ移動 $app->post($basePath . '/product/product_rank/moveRank', '\\Plugin\\ProductRank\\Controller\\ProductRankController::moveRank')->assert('category_id', '\\d+')->assert('product_id', '\\d+')->assert('position', '\\d+')->bind('admin_product_product_rank_move_rank'); // カテゴリ選択 $app->match($basePath . '/product/product_rank/{category_id}', '\\Plugin\\ProductRank\\Controller\\ProductRankController::index')->assert('category_id', '\\d+')->bind('admin_product_product_rank_show'); // メッセージ登録 $app['translator'] = $app->share($app->extend('translator', function ($translator, \Silex\Application $app) { $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader()); $file = __DIR__ . '/../Resource/locale/message.' . $app['locale'] . '.yml'; if (file_exists($file)) { $translator->addResource('yaml', $file, $app['locale']); } return $translator; })); // メニュー登録 $app['config'] = $app->share($app->extend('config', function ($config) { $addNavi['id'] = "product_rank"; $addNavi['name'] = "商品並び替え"; $addNavi['url'] = "admin_product_product_rank"; self::addNavi($config['nav'], $addNavi, array('product')); return $config; })); }
public function register(BaseApplication $app) { // 定休日テーブル用リポジトリ $app['eccube.plugin.holiday.repository.holiday'] = $app->share(function () use($app) { return $app['orm.em']->getRepository('Plugin\\Holiday\\Entity\\Holiday'); }); $basePath = '/' . $app["config"]["admin_route"]; // 一覧 $app->match($basePath . '/system/shop/holiday/', '\\Plugin\\Holiday\\Controller\\HolidayController::index')->bind('admin_setting_shop_holiday'); // 新規作成 $app->match($basePath . '/system/shop/holiday/new', '\\Plugin\\Holiday\\Controller\\HolidayController::edit')->bind('admin_setting_shop_holiday_new'); // 編集 $app->match($basePath . '/system/shop/holiday/{id}/edit', '\\Plugin\\Holiday\\Controller\\HolidayController::edit')->assert('id', '\\d+')->bind('admin_setting_shop_holiday_edit'); // 一覧:削除 $app->delete($basePath . '/system/shop/holiday/{id}/delete', '\\Plugin\\Holiday\\Controller\\HolidayController::delete')->assert('id', '\\d+')->bind('admin_setting_shop_holiday_delete'); // 一覧:上 $app->put($basePath . '/system/shop/holiday/{id}/up', '\\Plugin\\Holiday\\Controller\\HolidayController::up')->assert('id', '\\d+')->bind('admin_setting_shop_holiday_up'); // 一覧:下 $app->put($basePath . '/system/shop/holiday/{id}/down', '\\Plugin\\Holiday\\Controller\\HolidayController::down')->assert('id', '\\d+')->bind('admin_setting_shop_holiday_down'); $app->match('/block/holiday_calendar_block', '\\Plugin\\Holiday\\Controller\\Block\\HolidayController::index')->bind('block_holiday_calendar_block'); // 型登録 $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app) { $types[] = new \Plugin\Holiday\Form\Type\HolidayType($app); return $types; })); // メッセージ登録 $app['translator'] = $app->share($app->extend('translator', function ($translator, \Silex\Application $app) { $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader()); $file = __DIR__ . '/../Resource/locale/message.' . $app['locale'] . '.yml'; if (file_exists($file)) { $translator->addResource('yaml', $file, $app['locale']); } return $translator; })); // load config $conf = $app['config']; $app['config'] = $app->share(function () use($conf) { $confarray = array(); $path_file = __DIR__ . '/../Resource/config/path.yml'; if (file_exists($path_file)) { $config_yml = Yaml::parse(file_get_contents($path_file)); if (isset($config_yml)) { $confarray = array_replace_recursive($confarray, $config_yml); } } return array_replace_recursive($conf, $confarray); }); // メニュー登録 $app['config'] = $app->share($app->extend('config', function ($config) { $addNavi['id'] = "holiday"; $addNavi['name'] = "定休日管理"; $addNavi['url'] = "admin_setting_shop_holiday"; self::addNavi($config['nav'], $addNavi, array('setting', 'shop')); return $config; })); }
/** * @depends testRegister */ public function testDecodingOfRequestBody(Application $app) { $app->put('/api/user/{id}', function ($id) use($app) { return $app['request']->get('name'); }); $request = Request::create('/api/user/1', 'put', array(), array(), array(), array(), '{"name":"igor"}'); $request->headers->set('Content-Type', 'application/json'); $response = $app->handle($request); $this->assertEquals('igor', $response->getContent()); }
/** * {@inheritDoc} */ public function register(SilexApplication $app) { $app['payum.api.controller.root'] = $app->share(function () { return new RootController(); }); $app['payum.api.controller.payment'] = $app->share(function () use($app) { return new PaymentController($app['payum.security.token_factory'], $app['payum.security.http_request_verifier'], $app['payum'], $app['api.view.order_to_json_converter'], $app['form.factory'], $app['api.view.form_to_json_converter']); }); $app['payum.api.controller.gateway'] = $app->share(function () use($app) { return new GatewayController($app['form.factory'], $app['url_generator'], $app['api.view.form_to_json_converter'], $app['payum.gateway_config_storage'], $app['api.view.gateway_config_to_json_converter']); }); $app['payum.api.controller.gateway_meta'] = $app->share(function () use($app) { return new GatewayMetaController($app['form.factory'], $app['api.view.form_to_json_converter'], $app['payum']); }); $app->get('/', 'payum.api.controller.root:rootAction')->bind('api_root'); $app->get('/payments/meta', 'payum.api.controller.payment:metaAction')->bind('payment_meta'); $app->get('/payments/{payum_token}', 'payum.api.controller.payment:getAction')->bind('payment_get'); $app->put('/payments/{payum_token}', 'payum.api.controller.payment:updateAction')->bind('payment_update'); $app->delete('/payments/{payum_token}', 'payum.api.controller.payment:deleteAction')->bind('payment_delete'); $app->post('/payments', 'payum.api.controller.payment:createAction')->bind('payment_create'); $app->get('/payments', 'payum.api.controller.payment:allAction')->bind('payment_all'); $app->get('/gateways/meta', 'payum.api.controller.gateway_meta:getAllAction')->bind('payment_factory_get_all'); $app->get('/gateways', 'payum.api.controller.gateway:allAction')->bind('gateway_all'); $app->get('/gateways/{name}', 'payum.api.controller.gateway:getAction')->bind('gateway_get'); $app->delete('/gateways/{name}', 'payum.api.controller.gateway:deleteAction')->bind('gateway_delete'); $app->post('/gateways', 'payum.api.controller.gateway:createAction')->bind('gateway_create'); $app->before(function (Request $request, Application $app) { if (in_array($request->getMethod(), array('GET', 'OPTIONS', 'DELETE'))) { return; } if ('json' !== $request->getContentType()) { throw new BadRequestHttpException('The request content type is invalid. It must be application/json'); } $decodedContent = json_decode($request->getContent(), true); if (null === $decodedContent) { throw new BadRequestHttpException('The request content is not valid json.'); } $request->attributes->set('content', $decodedContent); }); $app->after(function (Request $request, Response $response) use($app) { if ($response instanceof JsonResponse && $app['debug']) { $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); } }); $app->after($app["cors"]); $app->error(function (\Exception $e, $code) use($app) { if ('json' !== $app['request']->getContentType()) { return; } return new JsonResponse(array('exception' => get_class($e), 'message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'stackTrace' => $e->getTraceAsString())); }, $priority = -100); }
public function testMatchReturnValue() { $app = new Application(); $returnValue = $app->match('/foo', function () { }); $this->assertInstanceOf('Silex\\Controller', $returnValue); $returnValue = $app->get('/foo', function () { }); $this->assertInstanceOf('Silex\\Controller', $returnValue); $returnValue = $app->post('/foo', function () { }); $this->assertInstanceOf('Silex\\Controller', $returnValue); $returnValue = $app->put('/foo', function () { }); $this->assertInstanceOf('Silex\\Controller', $returnValue); $returnValue = $app->delete('/foo', function () { }); $this->assertInstanceOf('Silex\\Controller', $returnValue); }
public function register(Application $app, $uri) { $resource = $this->get($uri); $metadata = $resource->getMetadata(); $base = '/' . $uri; if (is_callable(array($resource, 'get'))) { $app->get($base, 'controller.resourcehub:get')->bind($uri . ':list'); } if (is_callable(array($resource, 'getOne'))) { $app->get($base . '/{id}', 'controller.resourcehub:get')->bind($uri . ':get'); } if (is_callable(array($resource, 'post'))) { $app->post($base . '/{id}', 'controller.resourcehub:post')->bind($uri . ':post'); } if (is_callable(array($resource, 'put'))) { $app->put($base, 'controller.resourcehub:put')->bind($uri . ':put'); } if (is_callable(array($resource, 'delete'))) { $app->delete($base . '/{id}', 'controller.resourcehub:delete')->bind($uri . ':delete'); } }
<?php require_once __DIR__ . '/../vendor/autoload.php'; use Silex\Application; use Symfony\Component\HttpFoundation\Response; use Symfony\component\HttpFoundation\Request; use Notes\Api\UserApi; $app = new Application(); $app['debug'] = true; $userApi = new UserApi(); $app->get('/', function () { return new Response('<h1>Rest API Final Project</h1>', 200); }); $app->get('/users', function (Request $request) use($userApi) { return $userApi->getAllUsers($request); }); $app->get('/users/{id}', function ($id) use($userApi) { return $userApi->getUserById($id); }); $app->post('/users', function (Request $request) use($userApi) { return $userApi->insertUser($request); }); $app->put('/users/{id}', function (Request $request, $id) use($userApi) { return $userApi->updateUserById($request, $id); }); $app->delete('/users/{id}', function ($id) use($userApi) { return $userApi->removeUserById($id); }); $app->run();
return new Response($cervejas['marcas'][$key], 200); })->value('id', null); $app->post('/cerveja', function (Request $request) use($app, $db) { $db->exec("create table if not exists beer (id INTEGER PRIMARY KEY AUTOINCREMENT, name text not null, style text not null)"); if (!$request->get('name') || !$request->get('style')) { return new Response('Faltam parâmetros', 400); } $cerveja = ['name' => $request->get('name'), 'style' => $request->get('style')]; $stmt = $db->prepare('insert into beer (name, style) values (:name, :style)'); $stmt->bindParam(':name', $cerveja['name']); $stmt->bindParam(':style', $cerveja['style']); $stmt->execute(); $cerveja['id'] = $db->lastInsertId(); return $cerveja; }); $app->put('/cerveja/{id}', function (Request $request, $id) use($app) { }); $app->delete('/cerveja/{id}', function (Request $request, $id) use($app) { }); $app->before(function (Request $request) use($app) { if (!$request->headers->has('authorization')) { return new Response('Unauthorized', 401); } $clients = (require_once 'config/clients.php'); if (!in_array($request->headers->get('authorization'), array_keys($clients))) { return new Response('Unauthorized', 401); } }); $app->after(function (Request $request, Response $response) use($app) { $content = explode(',', $response->getContent()); if ($request->headers->get('accept') == 'text/json') { $response->headers->set('Content-Type', 'text/json');
}); /* read */ $app->get('/notes/{id}', function (Application $app, Request $request, $id) use($notes) { $singleNote = $notes[$id]; if (!isset($singleNote)) { $app->abort(404, 'Note with ID $id does not exist.'); } return new Response(json_encode($notes[$id]), 201, ['content-type' => 'application/json']); }); /* update */ $app->put('/notes/{id}', function (Application $app, Request $request, $id) use($notes) { $contentTypeValid = in_array('application/json', $request->getAcceptableContentTypes()); if (!$contentTypeValid) { $app->abort(406, 'Client must accept content type of "application/json"'); } $content = json_decode($request->getContent(), true); if (!isset($notes[$id])) { $app->abort(404, 'Note with ID $id does not exist.'); } $notes[$id] = ['name' => $content->name, 'body' => $content->body, 'tags' => $content->tags]; return new Response(json_encode(['result' => 'success', 'status' => 'updated']), 200, ['Content-Type' => 'application/json', 'Location' => 'http://localhost:8080/notes/' . $id]); }); /* delete */ $app->delete('/notes/{id}', function (Application $app, $id) use($notes) { if (!isset($notes[$id])) { $app->abort(404, 'Note with ID $id does not exist.'); } unset($notes[$id]); return new Response(null, 204); }); /* list */ $app->get('/notes', function (Application $app) use($notes) {
//get all notes $app->get('/notes', function () use($notes) { return new Response(json_encode($notes), 200); }); //get notes by ID $app->get('/notes/{id}', function (Application $app, $id) use($notes) { if (!isset($notes[$id])) { $app->abort(404, "Note ID {id} not found!"); } return new Response(json_encode($notes[$id]), 200); }); //Modify notes by ID $app->put('/notes/{id}', function (Application $app, Request $request, $id) use($notes) { if (!isset($notes[$id])) { $app->abort(404, "Note ID {id} not found!"); } $payload = json_decode($request->getContent()); $notes[$id] = $payload; return new Response(json_encode($notes), 200); }); //Delete notes by ID $app->delete('/notes/{id}', function (Application $app, $id) use($notes) { if (!isset($notes[$id])) { $app->abort(404, "Note ID {id} not found!"); } unset($notes[$id]); return new Response(null, 204); }); //Add notes - Autogenerate ID $app->post('/notes', function (Application $app, Request $request) use($notes) { //Validate content $contentTypeValid = in_array('application/json', $request->getAcceptableContentTypes());
use Silex\Application; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; $app = new Application(); $app['debug'] = true; $app->register(new SilexMemcache\MemcacheExtension()); $app->register(new Silex\Provider\DoctrineServiceProvider(), include __DIR__ . '/../share/config.php'); $app->before(function (Request $request) { if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) { $data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); $app->error(function (\Exception $e, $code) { return new JsonResponse(['error' => $e->getMessage()], 400); }); $app->get('/api/v1/vote', function (Application $app) { // FIXME $sql = 'SELECT * FROM sf_vote'; $post = $app['db']->fetchAssoc($sql); return $app->json($post); }); $app->put('/api/v1/vote/{name}', function (Application $app, $name) { // FIXME $app->abort(403); }); $app->put('/api/v1/user/{name}', function (Application $app, $name) { // FIXME $app->abort(400); }); return $app;
/** * @param Application $app * @param array $vars * @param array $roles * * @return mixed */ protected function addSubSubTypeUpdateResourceOperation(Application $app, $vars, $roles) { $pattern = sprintf('/%ss/{id}/%ss/{itemId}/%ss/{subItemId}', $vars['type'], $vars['subType'], $vars['subSubType']); $that = $this; return $app->put($pattern, function (Application $app, Request $request, $id, $itemId, $subItemId) use($vars, $roles, $that) { $r = $that->executeOperation($app, $request, $roles, $vars, sprintf('update%s', ucfirst($vars['subSubType'])), [$id, $itemId, $subItemId, $request->request->get('parsedJsonData')]); if (!is_object($r) && is_array($r) && [] !== $r) { return $app->json($r, 200); } return $app->json(null, 204); }); }
$app['logger'] = new Logger('log'); $app['logger']->pushHandler(new ErrorLogHandler()); $app->register(new ConfigProvider()); $app->register(new StoreProvider()); $app->register(new QueueClientProvider()); /** * Return token for the key */ $app->get('/tokens/{key}', function (Request $request, $key) use($app) { return new Response($app['store']->get($key), 200); }); /** * Add token for the key */ $app->put('/tokens/{key}', function (Request $request, $key) use($app) { $app['store']->add($key, $request->get('token')); return new Response('', 200); }); /** * List all token keys - ie. owner names */ $app->get('/tokens', function (Request $request) use($app) { return new Response(json_encode($app['store']->all(), JSON_UNESCAPED_SLASHES), 200); }); /** */ $app->error(function (Exception $e, $code) use($app) { $app['logger']->addError($e->getMessage()); return new Response($e->getMessage(), $e->getCode()); }); return $app;
$app->post('/cervejas', function (Request $request) use($app) { //pega os dados if (!($data = $request->get('cerveja'))) { return new Response('Faltam parâmetros', 400); } $app['db']->insert('cervejas', array('nome' => $data['nome'], 'estilo' => $data['estilo'])); //redireciona para a nova cerveja return $app->redirect('/cervejas/' . $data['nome'], 201); }); $app->put('/cervejas/{id}', function (Request $request, $id) use($app) { //pega os dados if (!($data = $request->get('cerveja'))) { return new Response('Faltam parâmetros', 400); } $sql = "SELECT * FROM cervejas WHERE nome = ?"; $cerveja = $app['db']->fetchAssoc($sql, array($id)); if (!$cerveja) { return new Response(json_encode('Não encontrada'), 404); } //Persiste na base de dados $app['db']->update('cervejas', array('nome' => $data['nome'], 'estilo' => $data['estilo']), array('id' => $cerveja['id'])); return new Response('Cerveja atualizada', 200); }); $app->delete('/cervejas/{id}', function (Request $request, $id) use($app) { //busca da base de dados $sql = "SELECT * FROM cervejas WHERE nome = ?"; $cerveja = $app['db']->fetchAssoc($sql, array($id)); if (!$cerveja) { return new Response(json_encode('Não encontrada'), 404); } $app['db']->delete('cervejas', array('id' => $cerveja['id'])); return new Response('Cerveja removida', 200);
} return $app->json(all('select id, name from dogs_race limit ' . $pp . ' offset ' . $p * $pp), 200, ['X-Total-Count' => col('select count(*) from dogs_race')]); }); $app->options('/races', function () { return ''; }); $app->post('/races', function (Application $app, Request $req) { insert('dogs_race', $req->request->all()); return $app->json(one('select * from dogs_race order by id desc limit 1')); }); $app->get('/races/{id}', function (Application $app, Request $req, $id) { return $app->json(one('select * from dogs_race where id =' . q($id))); }); $app->put('/races/{id}', function (Application $app, Request $req, $id) { $json = $req->request->all(); unset($json['id']); update('dogs_race', $id, $json); return $app->json(); }); $app->options('/races/{id}', function (Application $app, Request $req, $id) { return new Response('', 204); }); $app->delete('/races/{id}', function (Application $app, Request $req, $id) { query('delete from dogs_race where id=' . q($id)); return new Response('', 204); }); $app->get('/dogs', function (Application $app, Request $req) { $pp = (int) $req->get('_perPage'); $p = (int) $req->get('_page') - 1; if ($pp == 0) { $pp = 30; }
/** * @param string $pattern * @param Endpoint $to * @return \Silex\Controller */ public function put($pattern, $to = null) { return parent::put($pattern, $to); }
public function testMethodRouting() { $app = new Application(); $app->match('/foo', function () { return 'foo'; }); $app->match('/bar', function () { return 'bar'; })->method('GET|POST'); $app->get('/resource', function () { return 'get resource'; }); $app->post('/resource', function () { return 'post resource'; }); $app->put('/resource', function () { return 'put resource'; }); $app->patch('/resource', function () { return 'patch resource'; }); $app->delete('/resource', function () { return 'delete resource'; }); $this->checkRouteResponse($app, '/foo', 'foo'); $this->checkRouteResponse($app, '/bar', 'bar'); $this->checkRouteResponse($app, '/bar', 'bar', 'post'); $this->checkRouteResponse($app, '/resource', 'get resource'); $this->checkRouteResponse($app, '/resource', 'post resource', 'post'); $this->checkRouteResponse($app, '/resource', 'put resource', 'put'); $this->checkRouteResponse($app, '/resource', 'patch resource', 'patch'); $this->checkRouteResponse($app, '/resource', 'delete resource', 'delete'); }
}; $app['collection.service'] = function () use($app) { return new CollectionService($app['resource.service'], $app['triplestore'], $app['fedora']); }; $app['collection.controller'] = function () use($app) { return new CollectionController($app['collection.service']); }; $app['transaction.service'] = function () use($app) { return new TransactionService($app['fedora']); }; $app['transaction.controller'] = function () use($app) { return new TransactionController($app['transaction.service']); }; $app->get('islandora/resource/{id}', 'resource.controller:find'); $app->post('islandora/resource/', 'resource.controller:create'); $app->put('islandora/resource/{id}', 'resource.controller:upsert'); $app->patch('islandora/resource/{id}', 'resource.controller:sparqlUpdate'); $app->delete('islandora/resource/{id}', 'resource.controller:delete'); $app->get('islandora/transaction/{id}', 'transaction.controller:status'); $app->post('islandora/transaction/', 'transaction.controller:create'); $app->post('islandora/transaction/{id}', 'transaction.controller:extend'); $app->post('islandora/transaction/{id}/commit', 'transaction.controller:commit'); $app->post('islandora/transaction/{id}/rollback', 'transaction.controller:rollback'); //$app->get('islandora/members/{id}', 'members.controller:find'); //$app->post('islandora/members/{id}/{child_id}', 'members.controller:add'); //$app->delete('islandora/members/{id}/{child_id}', 'members.controller:remove'); //$app->patch('islandora/members/{id}/{child_id}/{destination_id}', 'members.controller:migrate'); $app->get('islandora/collection/', 'collection.controller:index'); $app->post('islandora/collection/', 'collection.controller:create'); //$app->get('islandora/files/{id}', 'files.controller:find'); //$app->post('islandora/files/{id}/{child_id}', 'files.controller:add');
$app->get('/', function () { return new Response('Project 1 - POC API', 200); }); $app->get('/notes', function () use($notes) { return new Response(json_encode($notes), 200, ['Content-Type' => 'application/json']); }); $app->get('/notes/{id}', function (Application $app, $id) use($notes) { if (!isset($notes[$id])) { $app->abort(404, "Note with ID {id} does not exist."); } return new Response(json_encode($notes[$id]), 200, ['Content-Type' => 'application/json']); }); $app->put('/notes/{id}', function (Application $app, Request $request, $id) use($notes) { if (!isset($notes[$id])) { $app->abort(404, "Note with ID {id} does not exist."); } $payload = json_decode($request->getContent()); $notes[$id] = $payload; return new Response(json_encode($notes), 200, ['Location' => 'http://localhost:8888/notes/' . $id]); }); $app->delete('/notes/{id}', function (Application $app, $id) use($notes) { if (!isset($notes[$id])) { $app->abort(404, "Note with ID {id} does not exist."); } unset($notes[$id]); return new Response(null, 204); }); $app->post('/notes', function (Application $app, Request $request) use($notes) { $contentTypeValid = in_array('application/json', $request->getAcceptableContentTypes()); if (!$contentTypeValid) { $app->abort(406, 'Client must accept content type of "application/json"'); }
$em = $app['orm.em']; $post = $em->getRepository('App\\Entities\\Post')->find($id); $hydrator = new DoctrineHydrator($em); return $app->json($hydrator->extract($post)); }); $app->post('/posts', function (Request $request) use($app) { $em = $app['orm.em']; $post = new Post(); $post->setTitle($request->get('title')); $post->setContent($request->get('content')); $em->persist($post); $em->flush(); return $app->json($hydrator->extract($post)); }); $app->put('/posts/{id}', function ($id, Request $request) use($app) { $em = $app['orm.em']; $post = $em->getRepository('App\\Entities\\Post')->find($id); $post->setTitle($request->get('title')); $post->setContent($request->get('content')); $em->persist($post); $em->flush(); return $app->json($hydrator->extract($post)); }); $app->delete('/posts/{id}', function ($id) use($app) { $em = $app['orm.em']; $post = $em->getRepository('App\\Entities\\Post')->find($id); $em->remove($post); $em->flush(); return $app->json(true); }); $app->run();