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->delete('islandora/files/{id}/{child_id}', 'files.controller:remove'); //$app->patch('islandora/files/{id}/{child_id}/{destination_id}', 'files.controller:migrate');
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; } return $app->json(all('select * from dogs_dogs limit ' . $pp . ' offset ' . $p * $pp), 200, ['X-Total-Count' => col('select count(*) from dogs_dogs')]); }); $app->get('/dogs/{id}', function (Application $app, Request $req, $id) { return $app->json(one('select * from dogs_dogs where id = ' . q($id))); }); $app->run();
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); }); // $app->before(function (Request $request) use ($app) { // if( ! $request->headers->has('authorization')){ // return new Response('Unauthorized', 401); // } // require_once 'configs/clients.php'; // if (!in_array($request->headers->get('authorization'), array_keys($clients))) { // return new Response('Unauthorized', 401); // } // }); $app->after(function (Request $request, Response $response) { $response->headers->set('Content-Type', 'text/json');
/** * @param Application $app * @param array $vars * @param array $roles * * @return mixed */ protected function addSubSubTypeDeleteResourceOperation(Application $app, $vars, $roles) { $pattern = sprintf('/%ss/{id}/%ss/{itemId}/%ss/{subItemId}', $vars['type'], $vars['subType'], $vars['subSubType']); $that = $this; return $app->delete($pattern, function (Application $app, Request $request, $id, $itemId, $subItemId) use($vars, $roles, $that) { $r = $that->executeOperation($app, $request, $roles, $vars, sprintf('delete%s', ucfirst($vars['subSubType'])), [$id, $itemId, $subItemId]); if (!is_object($r) && is_array($r) && [] !== $r) { return $app->json($r, 200); } return $app->json(null, 204); }); }
public function register(Application $app) { $app["bbsapi.thread.management"] = function (Application $app) { return new ThreadManagement($app["entity_manager"]); }; $app["bbsapi.thread.post_management"] = function (Application $app) { return new ThreadPostManagement($app["entity_manager"]); }; $app["bbsapi.tag.registration"] = function (Application $app) { return new TagRegistration($app["entity_manager"]); }; $app["bbsapi.spec.thread_spec"] = function () { return new ThreadSpec(); }; $app["bbsapi.spec.post_spec"] = function () { return new PostSpec(); }; $app["bbsapi.spec.tags_spec"] = function () { return new TagsSpec(); }; $app->post("/threads", function (Application $app, Request $req) { /** @var ThreadSpec $threadSpec */ $threadSpec = $app["bbsapi.spec.thread_spec"]; /** @var TagsSpec $tagsSpec */ $tagsSpec = $app["bbsapi.spec.tags_spec"]; /** @var ThreadManagement $service */ $service = $app["bbsapi.thread.management"]; /** @var TagRegistration $tagRegistration */ $tagRegistration = $app["bbsapi.tag.registration"]; $user = $req->getUser(); if (!$user) { return $app->json([], 401); } $title = trim($req->request->get("title")); $tagNames = $req->request->get("tags"); if (is_array($tagNames) || is_null($tagNames)) { $tags = new Tags($tagNames); } else { return $app->json(["errors" => ["tags" => "The tags field must be array strings."]], 400); } $thread = new Thread(); $thread->setTitle($title); $threadResult = $threadSpec->validate($thread); $tagsResult = $tagsSpec->validate($tags); if (!$threadResult->isValid() || !$tagsResult->isValid()) { $errors = array_merge($threadResult->getErrors(), $tagsResult->getErrors()); return $app->json(["errors" => $errors], 400); } foreach ($tags as $tag) { $thread->addTag($tagRegistration->register($tag)); } $thread = $service->create($thread, $user); return $app->json($threadSpec->format($thread), 201); }); $app->get("/threads/{id}", function (Application $app, $id) { /** @var ThreadSpec $threadSpec */ $threadSpec = $app["bbsapi.spec.thread_spec"]; /** @var ThreadManagement $service */ $service = $app["bbsapi.thread.management"]; $thread = $service->findOne($id); if (!$thread) { return $app->json([], 404); } return $app->json($threadSpec->format($thread)); })->assert('id', '^\\d+$'); $app->get("/threads", function (Application $app, Request $req) { /** @var ThreadSpec $threadSpec */ $threadSpec = $app["bbsapi.spec.thread_spec"]; /** @var ThreadManagement $service */ $service = $app["bbsapi.thread.management"]; $tags = $req->query->get("tags"); if (is_null($tags) || $tags === "") { return $app->json([]); } $tags = new Tags(explode(',', $tags)); $threads = $service->findByTags($tags); return $app->json(array_map(function ($thread) use($threadSpec) { return $threadSpec->format($thread); }, $threads)); }); $app->delete("/threads/{id}", function (Application $app, Request $req, $id) { /** @var ThreadManagement $service */ $service = $app["bbsapi.thread.management"]; $thread = $service->findOne($id); if (!$thread) { return $app->json([], 404); } $user = $req->getUser(); if (!$user) { return $app->json([], 401); } $result = $service->remove($thread, $user); if (!$result) { return $app->json([], 403); } return $app->json([], 200); })->assert('id', '^\\d+$'); $app->post("/threads/{id}/posts", function (Application $app, Request $req, $id) { /** @var ThreadManagement $threadService */ $threadService = $app["bbsapi.thread.management"]; /** @var ThreadPostManagement $postService */ $postService = $app["bbsapi.thread.post_management"]; /** @var PostSpec $postSpec */ $postSpec = $app["bbsapi.spec.post_spec"]; $thread = $threadService->findOne($id); if (!$thread) { return $app->json([], 404); } $content = trim($req->request->get("content")); $post = new Post(); $post->setContent($content); $result = $postSpec->validate($post); if (!$result->isValid()) { return $app->json(["errors" => $result->getErrors()], 400); } $post = $postService->register($thread, $post); return $app->json($postSpec->format($post), 201); })->assert('id', '^\\d+$'); $app->get("/threads/{id}/posts", function (Application $app, $id) { /** @var ThreadManagement $threadService */ $threadService = $app["bbsapi.thread.management"]; /** @var PostSpec $postSpec */ $postSpec = $app["bbsapi.spec.post_spec"]; $thread = $threadService->findOne($id); if (!$thread) { return $app->json([], 404); } return $app->json(array_map(function ($post) use($postSpec) { /** @var Post $post */ return $postSpec->format($post); }, $thread->getPosts()), 200); })->assert('id', '^\\d+$'); $app->get("/threads/{threadId}/posts/{postId}", function (Application $app, $threadId, $postId) { /** @var ThreadManagement $threadService */ $threadService = $app["bbsapi.thread.management"]; /** @var PostSpec $postSpec */ $postSpec = $app["bbsapi.spec.post_spec"]; $thread = $threadService->findOne($threadId); if (!$thread) { return $app->json([], 404); } $post = $thread->getPost($postId); if (!$post) { return $app->json([], 404); } return $app->json($postSpec->format($post), 200); })->assert('threadId', '^\\d+$')->assert('postId', '^\\d+$'); }
/** * 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); } } }
private function loadDelete() { $this->application->delete('/api/' . $this->version . '/address-books/{id}.json', function (Application $application, $id) { $controller = new AddressBook($application); return $controller->delete($id); })->convert('id', function ($id) { return (int) $id; })->assert('id', '\\d+'); }
/** * {@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 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; })); }
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'); } }
/** * Builds the routes that can be accesses all the time without being logged in. * * @param Application $app */ private function constructPublicRoutes(Application $app) { // Home $app->get('/v1/', 'WineTasting\\Controller\\HomeController::info'); // User $app->post('/v1/user/register', 'WineTasting\\Controller\\UserController::register'); $app->get('/v1/user/{id}/votes', 'WineTasting\\Controller\\UserController::getVotes'); $app->get('/v1/user/{id}/tasted', 'WineTasting\\Controller\\UserController::getTasted'); $app->post('/v1/user/{id}/tasted/{idWine}', 'WineTasting\\Controller\\UserController::addTasted'); $app->delete('/v1/user/{id}/tasted/{idWine}', 'WineTasting\\Controller\\UserController::removeTasted'); // Wine $app->get('/v1/wine', 'WineTasting\\Controller\\WineController::getWines'); $app->get('/v1/wine/ranking', 'WineTasting\\Controller\\WineController::getRankedWines'); $app->get('/v1/wine/{id}', 'WineTasting\\Controller\\WineController::getWine'); $app->post('/v1/wine', 'WineTasting\\Controller\\WineController::create'); $app->post('/v1/wine/vote1', 'WineTasting\\Controller\\WineController::vote1'); $app->post('/v1/wine/vote2', 'WineTasting\\Controller\\WineController::vote2'); $app->post('/v1/wine/vote3', 'WineTasting\\Controller\\WineController::vote3'); // Config $app->post('/v1/config/{name}', 'WineTasting\\Controller\\ConfigController::setValue'); $app->get('/v1/config/{name}', 'WineTasting\\Controller\\ConfigController::getValue'); }
public function register(BaseApplication $app) { // 管理画面:一覧 $app->match('/' . $app['config']['admin_route'] . '/plugin/uzaitaikai/config', 'Plugin\\Uzaitaikai\\Controller\\ConfigController::index')->bind('plugin_Uzaitaikai_config'); // 管理画面:新規登録 $app->match('/' . $app['config']['admin_route'] . '/plugin/uzaitaikai/config/new', 'Plugin\\Uzaitaikai\\Controller\\ConfigController::edit')->bind('plugin_Uzaitaikai_config_new'); // 管理画面:編集 $app->match('/' . $app['config']['admin_route'] . '/plugin/uzaitaikai/config/{id}/edit', 'Plugin\\Uzaitaikai\\Controller\\ConfigController::edit')->assert('id', '\\d+')->bind('plugin_Uzaitaikai_config_edit'); // 管理画面:削除 $app->delete('/' . $app['config']['admin_route'] . '/plugin/uzaitaikai/config/{id}/delete', 'Plugin\\Uzaitaikai\\Controller\\ConfigController::delete')->assert('id', '\\d+')->bind('plugin_Uzaitaikai_config_delete'); // マイページ:退会画面 ※本体のルーティングを上書き. $app->match('/mypage/withdraw', 'Plugin\\Uzaitaikai\\Controller\\WithdrawController::index')->bind('mypage_withdraw'); // Repository $app['plugin.Uzaitaikai.repository.question'] = $app->share(function () use($app) { return $app['orm.em']->getRepository('Plugin\\Uzaitaikai\\Entity\\Question'); }); // Form $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app) { $types[] = new Mypage\QuestionType($app); $types[] = new Admin\QuestionType($app); return $types; })); }
} function storage_file_name(Request $request, $name) { return __DIR__ . '/../../../../state/' . $name . '-' . $request->server->get('SERVER_PORT'); } function clear(Request $request, $name) { $fileName = storage_file_name($request, $name); if (file_exists($fileName)) { unlink($fileName); } } $app = new Application(); $app['debug'] = true; $app->delete('/_expectation', static function (Request $request) { clear($request, 'expectations'); return new Response('', 200); }); $app->post('/_expectation', static function (Request $request) { $matcher = []; if ($request->request->has('matcher')) { $matcher = silent_deserialize($request->request->get('matcher')); $validator = static function ($closure) { return is_callable($closure); }; if (!is_array($matcher) || count(array_filter($matcher, $validator)) !== count($matcher)) { return new Response('POST data key "matcher" must be a serialized list of closures', 417); } } if (!$request->request->has('response')) { return new Response('POST data key "response" not found in POST data', 417); }
$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"'); } $content = json_decode($request->getContent()); // the content of the request is gotten $newId = uniqid(); // makes a key for the new value to be input $notes[$newId] = ['name' => $content->name, 'body' => $content->body, 'username' => $content->username, 'tags' => $content->tags]; //write notes to disk return new Response(json_encode($notes), 201, ['Location' => 'http://localhost:8888/notes/' . $newId]);
$idEstado = $request->request->get('idEstado'); $r = 0; if ($id) { $sql = "UPDATE Cidades SET nome = ?, idEstado = ? WHERE id = ?"; $r = $db->executeUpdate($sql, array($nome, $idEstado, $id)); } else { $sql = "INSERT INTO Cidades(nome, idEstado) VALUES(?, ?)"; $db->executeUpdate($sql, array($nome, $idEstado)); $r = $db->lastInsertId(); } return $r; }); // exclui uma cidade $app->delete('/cidades/{id}', function ($id) use($app, $db) { $sql = "DELETE FROM Cidades WHERE id = ?"; $r = $db->executeUpdate($sql, array($id)); return $r; }); // estados // retorna a lista de estados $app->get('/estados', function () use($app, $db) { $sql = "SELECT * FROM Estados ORDER BY nome"; $query = $db->executeQuery($sql); $estados = $query->fetchAll(); return $app->json($estados); }); // retorna um estado específico, com base no id (parâmetro de rota) $app->get('/estados/{id}', function ($id) use($app, $db) { $sql = "SELECT * FROM Estados WHERE id = ? ORDER BY nome"; $query = $db->executeQuery($sql, array($id)); $estado = $query->fetch();
$autoloaderFound = false; foreach ($autoloadFiles as $autoloadFile) { if (file_exists($autoloadFile)) { require_once $autoloadFile; $autoloaderFound = true; break; } } if (!$autoloaderFound) { throw new RuntimeException(sprintf('Could not locate autoloader file. Tried "%s"', implode($autoloadFiles, '", "'))); } $app = new Application(); $app['debug'] = true; $app['storage'] = new RequestStorage(getmypid(), __DIR__ . '/../state/'); $app->delete('/_expectation', static function (Request $request) use($app) { $app['storage']->clear($request, 'expectations'); return new Response('', Response::HTTP_OK); }); $app->post('/_expectation', static function (Request $request) use($app) { $matcher = []; if ($request->request->has('matcher')) { $matcher = Util::silentDeserialize($request->request->get('matcher')); $validator = static function ($closure) { return is_callable($closure); }; if (!is_array($matcher) || count(array_filter($matcher, $validator)) !== count($matcher)) { return new Response('POST data key "matcher" must be a serialized list of closures', Response::HTTP_EXPECTATION_FAILED); } } if (!$request->request->has('response')) { return new Response('POST data key "response" not found in POST data', Response::HTTP_EXPECTATION_FAILED); }
<?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();
$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'); $response->setContent(json_encode($content)); }
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()); if (!$contentTypeValid) { $app->abort(406, 'Invalid content'); } $content = json_decode($request->getContent()); $newId = uniqid(); // creates ID for note $notes[$newId] = ['name' => $content->name, 'body' => $content->body, 'username' => $content->username, 'tags' => $content->tags]; return new Response(json_encode($notes), 201);
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'); }
/** * @param string $pattern * @param Endpoint $to * @return \Silex\Controller */ public function delete($pattern, $to = null) { return parent::delete($pattern, $to); }
$application->delete('/unique-number-repository/{name}', function (Application $application, Request $request) use($locator) { //begin of runtime parameters $name = urldecode($request->get('name')); $user = urldecode($request->get('applicant_name')); //end of runtime parameters //begin of dependencies $repositoryStorage = $locator->getRepositoryStorage(); $uniqueNumberStorage = $locator->getUniqueNumberStorage(); //end of dependencies //begin of validation $repositoryStorage->resetRuntimeProperties(); $repositoryStorage->filterByApplicantName($user); $repositoryStorage->filterByName($name); $repositoryNameDoesNotExist = !$repositoryStorage->has(); if ($repositoryNameDoesNotExist) { $application->abort(404); } $repositoryStorage->resetRuntimeProperties(); //end of validation //begin of process $repositoryStorage->filterByApplicantName($user); $repositoryStorage->filterByName($name); $result = $repositoryStorage->delete(); if ($result === true) { $uniqueNumberStorage->resetRuntimeProperties(); $uniqueNumberStorage->filterByRepositoryName($name); $result = $uniqueNumberStorage->delete(); if ($result !== true) { $application->abort(503); } } else { $application->abort(503); } return $application->json('ok'); //end of process });
public function connect(Application $app) { $controllers = new ControllerCollection($app['route_factory']); $app->get('/users/', function () use($app) { /** @var $request \Symfony\Component\HttpFoundation\Request */ $request = $app['request']; $rows = (int) $request->get('rows', 10); $offset = (int) $request->get('offset', 0); /** @var $em \Doctrine\ORM\EntityManager */ //@todo refactor to use repo $em = $app['doctrine_orm.em']; $query = $em->createQuery('SELECT u.surname, u.lastname, u.email, u.birthdate, u.name FROM Bibi\\Entity\\User u '); $query->setMaxResults($rows); $query->setFirstResult($offset); $result = $query->getResult(); return $app->json($result); })->bind('users.index'); $app->get('/users/{id}', function ($id) use($app) { /** @var $em \Doctrine\ORM\EntityManager */ $em = $app['doctrine_orm.em']; $user = $em->getRepository("Bibi\\Entity\\User"); $result = $user->findOneById($id); $data = new \stdClass(); $status = 500; if (!empty($result)) { $data->users = array($result->getSimpleObject()); $status = 200; } else { $data->messageId = "user.notfound"; $status = 404; } return $app->json($data, $status); })->bind('user.id')->convert('id', function ($id) { return (int) $id; }); $app->post('/users/', function () use($app) { /** @var $request \Symfony\Component\HttpFoundation\Request */ $request = $app['request']; $requestData = json_decode($request->get('data', "")); $data = new \stdClass(); $status = 500; $headers = array(); if (!empty($requestData)) { /** @var $validator Symfony\Component\Validator\Validator*/ $validator = $app['validator']; $errors = $validator->validate($requestData); if (count($errors) > 0) { $data->messageId = "user.datainvalid"; $status = 404; } else { /** @var $em \Doctrine\ORM\EntityManager */ $em = $app['doctrine_orm.em']; /** @var $userRepo \Bibi\Repo\UserRepo */ $userRepo = $em->getRepository("Bibi\\Entity\\User"); /** @var $result \Bibi\Entity\User */ $result = $userRepo->findOneByName($requestData->name); if (empty($result)) { $user = new \Bibi\Entity\User(); foreach (get_object_vars($requestData) as $attr => $value) { $methodName = "set" . ucfirst($attr); call_user_func_array(array($user, $methodName), array($value)); } $em->persist($user); $em->flush(); $url = $app['url_generator']->generate('user.id', array("id" => $user->getId())); $status = 201; } else { $url = $app['url_generator']->generate('user.id', array("id" => $result->getId())); $data->messageId = "user.exists"; $status = 303; } $headers = array("Location" => $url); } } else { $data->messageId = "user.datainvalid"; $status = 404; } return $app->json($data, $status, $headers); })->bind('user.add'); $app->delete('/users/{id}', function ($id) use($app) { /** @var $em \Doctrine\ORM\EntityManager */ $em = $app['doctrine_orm.em']; /** @var $userRepo \Bibi\Repo\UserRepo */ $userRepo = $em->getRepository("Bibi\\Entity\\User"); /** @var $result \Bibi\Entity\User */ $result = $userRepo->findOneById((int) $id); $status = 500; $data = new \stdClass(); if (empty($result)) { $status = 410; $data->messageId = 'user.notexists'; } else { $em->remove($result); $em->flush(); $status = 200; $data->messageId = 'user.removed'; } return $app->json($data, $status); })->bind('user.delete')->convert('id', function ($id) { return (int) $id; }); /* * @todo * update user * Application tests */ return $controllers; }
/** * @param BaseApplication $app */ public function register(BaseApplication $app) { // おすすめ情報テーブルリポジトリ $app['eccube.plugin.recommend.repository.recommend_product'] = $app->share(function () use($app) { return $app['orm.em']->getRepository('Plugin\\Recommend\\Entity\\RecommendProduct'); }); // おすすめ商品の一覧 $app->match('/' . $app['config']['admin_route'] . '/recommend', '\\Plugin\\Recommend\\Controller\\RecommendController::index')->bind('admin_recommend_list'); // おすすめ商品の新規先 $app->match('/' . $app['config']['admin_route'] . '/recommend/new', '\\Plugin\\Recommend\\Controller\\RecommendController::edit')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_new'); // おすすめ商品の編集 $app->match('/' . $app['config']['admin_route'] . '/recommend/{id}/edit', '\\Plugin\\Recommend\\Controller\\RecommendController::edit')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_edit'); // おすすめ商品の削除 $app->delete('/' . $app['config']['admin_route'] . '/recommend/{id}/delete', '\\Plugin\\Recommend\\Controller\\RecommendController::delete')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_delete'); // move rank $app->post('/' . $app['config']['admin_route'] . '/recommend/rank/move', '\\Plugin\\Recommend\\Controller\\RecommendController::moveRank')->bind('admin_recommend_rank_move'); // 商品検索画面表示 $app->post('/' . $app['config']['admin_route'] . '/recommend/search/product', '\\Plugin\\Recommend\\Controller\\RecommendSearchModelController::searchProduct')->bind('admin_recommend_search_product'); $app->match('/' . $app['config']['admin_route'] . '/recommend/search/product/page/{page_no}', '\\Plugin\\Recommend\\Controller\\RecommendSearchModelController::searchProduct')->assert('page_no', '\\d+')->bind('admin_recommend_search_product_page'); // ブロック $app->match('/block/recommend_product_block', '\\Plugin\\Recommend\\Controller\\Block\\RecommendController::index')->bind('block_recommend_product_block'); // 型登録 $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app) { $types[] = new RecommendProductType($app); return $types; })); // サービスの登録 $app['eccube.plugin.recommend.service.recommend'] = $app->share(function () use($app) { return new RecommendService($app); }); // メッセージ登録 $app['translator'] = $app->share($app->extend('translator', function (Translator $translator, Application $app) { $file = __DIR__ . '/../Resource/locale/message.' . $app['locale'] . '.yml'; if (file_exists($file)) { $translator->addResource('yaml', $file, $app['locale']); } return $translator; })); // Config $app['config'] = $app->share($app->extend('config', function ($config) { // menu bar $addNavi['id'] = 'admin_recommend'; $addNavi['name'] = 'おすすめ管理'; $addNavi['url'] = 'admin_recommend_list'; $nav = $config['nav']; foreach ($nav as $key => $val) { if ('content' == $val['id']) { $nav[$key]['child'][] = $addNavi; } } $config['nav'] = $nav; // Update path $pathFile = __DIR__ . '/../Resource/config/path.yml'; if (file_exists($pathFile)) { $path = Yaml::parse(file_get_contents($pathFile)); if (!empty($path)) { // Replace path $config = array_replace_recursive($config, $path); } } // Update constants $constantFile = __DIR__ . '/../Resource/config/constant.yml'; if (file_exists($constantFile)) { $constant = Yaml::parse(file_get_contents($constantFile)); if (!empty($constant)) { // Replace constants $config = array_replace_recursive($config, $constant); } } return $config; })); // initialize logger (for 3.0.0 - 3.0.8) if (!Version::isSupportGetInstanceFunction()) { eccube_log_init($app); } }
// user $app->get('/user/{userId}', function ($userId) use($app) { $query = "SELECT id, userName, userEmail, userAddress FROM users where id = {$userId}"; $events = $app['db']->fetchAll($query); return new Response(json_encode($events)); }); // user add $app->post('/user/add', function (Request $request) use($app) { $post = array('userName' => $request->request->get('userName'), 'userEmail' => $request->request->get('userEmail'), 'userAddress' => $request->request->get('userAddress')); $app['db']->insert('users', $post); return $app->json($post, 201); }); // remove $app->delete('/user/del/{userId}', function ($userId) use($app) { $delete = array('id' => $userId); echo $delete; $app['db']->delete('users', $delete); return $app->json($delete, 200); }); // update $app->post('/user/upd', function (Request $request) use($app) { $update = array('id' => $request->request->get('id'), 'userName' => $request->request->get('userName'), 'userEmail' => $request->request->get('userEmail'), 'userAddress' => $request->request->get('userAddress')); $identify = array('id' => $request->request->get('id')); $app['db']->update('users', $update, $identify); return $app->json("all UPDATED ok", 201); }); // // CHECKOUT // checkout object $app->get('/cko', function () use($app) { $query = "SELECT * FROM orders"; $events = $app['db']->fetchAll($query);
$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();