/**
  * 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);
         }
     }
 }
 /**
  * register.
  *
  * @param Application $app
  */
 public function register(BaseApplication $app)
 {
     $app->post('/related_product/search_product', '\\Plugin\\RelatedProduct\\Controller\\Admin\\RelatedProductController::searchProduct')->bind('admin_related_product_search');
     $app->post('/related_product/get_product', '\\Plugin\\RelatedProduct\\Controller\\Admin\\RelatedProductController::getProduct')->bind('admin_related_product_get_product');
     $app->match('/' . $app['config']['admin_route'] . '/related_product/search/product/page/{page_no}', '\\Plugin\\RelatedProduct\\Controller\\Admin\\RelatedProductController::searchProduct')->assert('page_no', '\\d+')->bind('admin_related_product_search_product_page');
     // イベントの追加
     $app['eccube.plugin.relatedproduct.event'] = $app->share(function () use($app) {
         return new Event($app);
     });
     $app['eccube.plugin.relatedproduct.event.legacy'] = $app->share(function () use($app) {
         return new EventLegacy($app);
     });
     // Formの定義
     $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app) {
         $types[] = new RelatedProductType($app);
         return $types;
     }));
     // @deprecated for since v3.0.0, to be removed in 3.1.
     if (!Version::isSupportGetInstanceFunction()) {
         // Form/Extension
         $app['form.type.extensions'] = $app->share($app->extend('form.type.extensions', function ($extensions) {
             $extensions[] = new RelatedCollectionExtension();
             return $extensions;
         }));
     }
     // Repository
     $app['eccube.plugin.repository.related_product'] = function () use($app) {
         return $app['orm.em']->getRepository('\\Plugin\\RelatedProduct\\Entity\\RelatedProduct');
     };
     // メッセージ登録
     $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;
     }));
     // Add config file.
     $app['config'] = $app->share($app->extend('config', function ($config) {
         // 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);
     }
 }
 /**
  * {@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);
 }
Example #4
0
 private function loadSave()
 {
     $this->application->post('/api/' . $this->version . '/address-books.json', function (Application $application) {
         $controller = new AddressBook($application);
         return $controller->save($application['request']);
     });
     $this->application->post('/api/' . $this->version . '/address-books/{id}.json', function (Application $application, $id) {
         $controller = new AddressBook($application);
         return $controller->save($application['request'], $id);
     })->convert('id', function ($id) {
         return (int) $id;
     })->assert('id', '\\d+');
 }
 /**
  * @test
  */
 public function notReplaceIfBodyContentIsNotJson()
 {
     $self = $this;
     $body = array("number" => 123, "string" => "foo", "array" => array(5, 27, 42), "object" => (object) array("bar" => "baz"), "true" => true, "false" => false);
     $this->app->register(new JsonBodyProvider());
     $this->app->post("/", function (Request $req) use($self) {
         $self->assertCount(0, $req->request);
         return "Done.";
     });
     $client = new Client($this->app);
     $client->request('POST', '/', array(), array(), array('CONTENT_TYPE' => 'application/json'), json_encode($body) . "..broken!!!");
     $response = $client->getResponse();
     $this->assertEquals("Done.", $response->getContent());
 }
 public function setup()
 {
     // Taken from the README.md: START
     $app = new \Silex\Application();
     $app->register(new \AIV\Integration\SilexProvider(), ['aiv.namespaced' => true, 'aiv.validators' => ['test-name' => ['options' => ['allow.extra.params' => true, 'allow.missing.params' => true], 'params' => ['name' => ['not.blank', ['type' => 'length', 'options' => ['min' => 2, 'max' => 20]]], 'email' => ['not.blank', '%email.validator%'], 'password' => ['not.blank']]]]]);
     $app['email.validator'] = $app->share(function () {
         return new \Symfony\Component\Validator\Constraints\Email();
     });
     $app->post('/', function (Application $app) {
         $apiValidator = $app['validator'];
         $validator = $apiValidator->getValidator('test-name');
         if ($validator->hasErrors()) {
             $errors = [];
             foreach ($validator->getErrors() as $violation) {
                 $path = preg_replace('/[\\[\\]]/', '', $violation->getPropertyPath());
                 $errors[$path] = $violation->getMessage();
             }
             return sprintf('You have errors: <pre>%s</pre>', print_r($errors, true));
         } else {
             return sprintf('You sent me valid data:<br /><pre>%s</pre>', print_r($validator->getData(), true));
         }
     });
     // Taken from the README.md: END
     $this->app = $app;
 }
 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;
     }));
 }
 private function getSilexApplication()
 {
     $app = new Application();
     $app->register(new AngularPostRequestServiceProvider());
     $app->post("/post", function (Application $app, Request $request) {
         return $app->json(['status' => true, 'name' => $request->get('name')]);
     });
     return $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')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_list');
     // おすすめ商品の新規先
     $app->match('/' . $app["config"]["admin_route"] . '/recommend/new', '\\Plugin\\Recommend\\Controller\\RecommendController::create')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_new');
     // おすすめ商品の新規作成・編集確定
     $app->match('/' . $app["config"]["admin_route"] . '/recommend/commit', '\\Plugin\\Recommend\\Controller\\RecommendController::commit')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_commit');
     // おすすめ商品の編集
     $app->match('/' . $app["config"]["admin_route"] . '/recommend/edit/{id}', '\\Plugin\\Recommend\\Controller\\RecommendController::edit')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_edit');
     // おすすめ商品の削除
     $app->match('/' . $app["config"]["admin_route"] . '/recommend/delete/{id}', '\\Plugin\\Recommend\\Controller\\RecommendController::delete')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_delete');
     // おすすめ商品のランク移動(上)
     $app->match('/' . $app["config"]["admin_route"] . '/recommend/rank_up/{id}', '\\Plugin\\Recommend\\Controller\\RecommendController::rankUp')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_rank_up');
     // おすすめ商品のランク移動(下)
     $app->match('/' . $app["config"]["admin_route"] . '/recommend/rank_down/{id}', '\\Plugin\\Recommend\\Controller\\RecommendController::rankDown')->value('id', null)->assert('id', '\\d+|')->bind('admin_recommend_rank_down');
     // 商品検索画面表示
     $app->post('/' . $app["config"]["admin_route"] . '/recommend/search/product', '\\Plugin\\Recommend\\Controller\\RecommendSearchModelController::searchProduct')->bind('admin_recommend_search_product');
     // ブロック
     $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 \Plugin\Recommend\Form\Type\RecommendProductType($app);
         return $types;
     }));
     // サービスの登録
     $app['eccube.plugin.recommend.service.recommend'] = $app->share(function () use($app) {
         return new \Plugin\Recommend\Service\RecommendService($app);
     });
     // メッセージ登録
     $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'] = '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;
         return $config;
     }));
 }
Example #10
0
 public function connect(Application $app)
 {
     // creates a new controller based on the default route
     $front = $app['controllers_factory'];
     $front->get("/", 'FrontController\\Homepage::index')->bind("homepage");
     $front->match("/final_test", 'FrontController\\FinalTest::index')->bind("final_test");
     $front->match("/control_test", 'FrontController\\ControlTest::index')->bind("control_test");
     $front->match("/{course_type}", 'FrontController\\CourseType::index')->bind("course_type");
     //$front->post("/{course_type}", 'FrontController\Score::index')->bind("course_type");
     $app->get('/logout', function (Request $request) use($app) {
         $app['session']->set('username', '');
         $app['session']->set('id', '');
         $redirect = $app["url_generator"]->generate("homepage");
         return $app->redirect($redirect);
     })->bind("logout");
     $app->post('/login-check', function (Request $request) use($app) {
         $em = $app['orm.em'];
         $qb = $em->createQueryBuilder();
         if (null !== $request->get('username2')) {
             $username = $request->get('username2');
             $query = $qb->select('u')->from('models\\User', 'u')->where("u.username = '******'")->getQuery();
             $result = $query->getResult();
             $result_count = count($result);
             if ($result_count > 0) {
                 return 'Helaas, de gebruikersnaam die je hebt ingevoerd bestaat al, probeer eens een andere.';
             } else {
                 $user = new User();
                 $user->setUsername($username);
                 $user->setRoles("ROLE_USER");
                 $em->persist($user);
                 $em->flush();
                 $id = $user->getId();
                 $app['session']->set('id', $id);
                 $app['session']->set('username', $username);
                 return 'succes';
             }
         } else {
             if ($request->get('username') != '') {
                 $username = $request->get('username');
                 $query = $qb->select('u')->from('models\\User', 'u')->where("u.username = '******'")->getQuery();
                 $result = $query->getResult();
                 $result_count = count($result);
                 if ($result_count < 1) {
                     return 'De gebruikersnaam die je hebt ingevoerd bestaat niet, probeer het eens opnieuw.';
                 } else {
                     $id = $result[0]->id;
                     $app['session']->set('id', $id);
                     $app['session']->set('username', $username);
                     return 'succes';
                 }
             }
         }
     })->bind("login_check");
     return $front;
 }
 public function register(Application $app)
 {
     $app['webmentions_root'] = getenv("ROOT_DIR") . "/webmentions";
     $app['action.receive_webmention'] = $app->share(function () use($app) {
         $adapter = new Local($app['webmentions_root']);
         $filesystem = new Filesystem($adapter);
         $eventWriter = new EventWriter($filesystem);
         return new ReceiveWebmentionAction(new ReceiveWebmentionResponder($app['response'], $app['twig'], new RenderPost($app['twig'])), new ReceiveWebmentionHandler(new VerifyWebmentionRequest(), $eventWriter));
     });
     $app->post('/webmention', 'action.receive_webmention:__invoke');
 }
 /**
  * @inheritdoc
  */
 public function register(Application $app)
 {
     $app->get('/', 'DashboardController:index')->bind('dashboard');
     $app->post('/api', 'ApiController:save');
     $app->get('/applications', 'ApplicationsController:index')->bind('applications');
     $app->post('/applications/add', 'ApplicationsController:index')->bind('applications_add');
     $app->get('/login', 'LoginController:index')->bind('login');
     $app->get('/reports', 'ReportsController:index')->bind('reports');
     $app->get('/reports/{id}', 'ReportsController:view')->bind('reports_view');
     $app->get('/search/{query}', 'SearchController:query')->bind('search');
     $app->get('/settings', 'SettingsController:index')->bind('settings');
     $app->post('/settings/update', 'SettingsController:index')->bind('settings_update');
     /** var $datatables \Silex\ControllerCollection */
     $datatables = $app['controllers_factory'];
     $datatables->post('/applications', 'DatatablesController:applications')->bind('datatables_applications');
     $datatables->post('/reports', 'DatatablesController:reports')->bind('datatables_reports');
     $app->mount('/datatables', $datatables);
     /** var $delete \Silex\ControllerCollection */
     $delete = $app['controllers_factory'];
     $delete->post('/applications', 'DeleteController:applications')->bind('delete_applications');
     $delete->post('/reports', 'DeleteController:reports')->bind('delete_reports');
     $app->mount('/delete', $delete);
 }
 /**
  * @return \Silex\Application
  */
 public function createApplication()
 {
     $app = new Application();
     $app['debug'] = true;
     $callback = function () use($app) {
         $subRequestHandler = new SubRequestHandler($app);
         return $subRequestHandler->handleSubRequest(new Request(), self::URL_SUB_REQUEST);
     };
     $app->get(self::URL_MASTER_REQUEST, $callback);
     $app->post(self::URL_MASTER_REQUEST, $callback);
     $app->get(self::URL_SUB_REQUEST, function () use($app) {
         return new RedirectResponse(self::URL_SUB_REQUEST);
     });
     return $app;
 }
 /**
  * Setup the application.
  * 
  * @param Application $app 
  */
 public function boot(Application $app)
 {
     // the direct api route
     $app->get('/api.js', function (Application $app) {
         return $app['direct.api']->getApi();
     })->bind('directapi');
     // the direct api route remoting description
     $app->get('/remoting.js', function (Application $app) {
         return $app['direct.api']->getRemoting();
     });
     // the direct router route
     $app->post('/route', function (Application $app) {
         // handle the route
         return $app['direct.router']->route();
     });
 }
 public function register(Application $app)
 {
     $app['action.create_post'] = $app->share(function () use($app) {
         return new CreatePostAction($app["create_post.handler"], new CreatePostResponder($app['response'], $app['twig'], new RenderPost($app['twig'])));
     });
     $app['access_token'] = $app->share(function () use($app) {
         return new VerifyAccessToken($app['http_client'], $app['token_endpoint'], $app['me_endpoint']);
     });
     $app['create_post.handler'] = $app->share(function () use($app) {
         return new CreatePostHandler($app['posts_repository_writer'], $app['access_token']);
     });
     $app['posts_repository_writer'] = $app->share(function () use($app) {
         $adapter = new \League\Flysystem\Adapter\Local($app['posts_root']);
         $filesystem = new \League\Flysystem\Filesystem($adapter);
         return new PostRepositoryWriter($filesystem, $app['db_cache']);
     });
     $app->post('/micropub', 'action.create_post:__invoke');
 }
Example #16
0
 public function __construct(\Silex\Application $app)
 {
     $app->register(new \Silex\Provider\UrlGeneratorServiceProvider());
     $conn = new DataBaseHelper();
     $db = $conn->autoConnect();
     $view = new ViewHelper($app);
     $view->setPath(dirname(__DIR__) . "/Views");
     // A query está sendo feita aqui porque é utilizadas em todos os métodos
     $headings = $db::table("exemplos")->get();
     // Essa variavel é adicionada aqui pois ela será usada em todos os métodos
     $view->assign(array("headings" => $headings));
     // Aqui ficarão as rotas/controllers desse módulo
     //=========== Home ===========//
     $app->get('/exemplo', function () use($app, $view) {
         $view->render("exemplo");
         return PHP_EOL;
     })->bind("exemplo_home");
     //=========== Heading ===========//
     $app->get('/exemplo/heading/{id}', function (Request $request) use($app, $view, $db) {
         // Pega o Heading atual
         $actual = $db::table("exemplos")->find($request->get("id"));
         $view->assign(array("actual" => $actual));
         $view->render("exemplo");
         return PHP_EOL;
     })->bind("exemplo_heading");
     //=========== Login (GET) ===========//
     $app->get('/exemplo/login', function (Request $request) use($app, $view) {
         return $app->redirect($app['url_generator']->generate('exemplo_home'));
     })->bind("exemplo_login_get");
     //=========== Login (POST) ===========//
     $app->post('/exemplo/login', function (Request $request) use($app, $view) {
         $view->assign(array("nome" => $request->get("name")));
         $mail = new SwiftMailerHelper($app);
         $mail->autoConfig();
         $mail->setSubject("Teste de Helper [Silex]");
         $mail->setTo(array("*****@*****.**"));
         $mail->setTitle("Testando 1, 2, 3...");
         $mail->setBody("Ola mundo :)");
         $mail->setAttach(__DIR__ . "/Exemplo.php");
         $mail->send();
         $view->render("exemplo");
         return PHP_EOL;
     })->bind("exemplo_login");
 }
Example #17
0
 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);
 }
Example #18
0
 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');
     }
 }
 public function register(BaseApplication $app)
 {
     $app->post('/related_product/search_product', '\\Plugin\\RelatedProduct\\Controller\\Admin\\RelatedProductController::searchProduct')->bind('admin_related_product_search');
     // Formの定義
     $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app) {
         $types[] = new \Plugin\RelatedProduct\Form\Type\Admin\RelatedProductType();
         return $types;
     }));
     $app['form.type.extensions'] = $app->share($app->extend('form.type.extensions', function ($extensions) use($app) {
         $extensions[] = new \Plugin\RelatedProduct\Form\Extension\Admin\RelatedCollectionExtension();
         return $extensions;
     }));
     // Repositoy
     $app['eccube.plugin.repository.related_product'] = function () use($app) {
         return $app['orm.em']->getRepository('\\Plugin\\RelatedProduct\\Entity\\RelatedProduct');
     };
     // Service
     $app['eccube.plugin.service.related_product'] = $app->share(function () use($app) {
         return new \Plugin\RelatedProduct\Service\RelatedProductService($app);
     });
 }
Example #20
0
 /**
  * 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');
 }
 /**
  * @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);
     }
 }
Example #22
0
<?php

require_once 'vendor/autoload.php';
require_once 'FileHelper.php';
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app->post('/upload', function (Request $request) use($app) {
    // get file from requests
    $file = $request->files->get('image');
    // if null return error
    if ($file == null) {
        $obj = new stdClass();
        $obj->success = false;
        $obj->error = "No image provided";
        return json_encode($obj);
    }
    // upload the file and return the json with the data
    return json_encode(FileHelper::writeFile($file));
});
$app->run();
Example #23
0
 /**
  * @param \Silex\Application $app
  */
 protected function run(\Silex\Application $app)
 {
     $app->register(new \Silex\Provider\UrlGeneratorServiceProvider());
     $this->startRequestTime = $this->getStartRequestTime();
     $conn = new DataBaseHelper();
     $db = $conn->autoConnect();
     $query = $db::table($this->dbTable);
     // Obtem todos os registros no banco
     // Opicional: Passa paramentro "page" para obter informações paginadas
     $app->get("/" . $this->uri, function (\Silex\Application $app, Request $request) use($db, $query) {
         if (!is_null($request->get('page'))) {
             $query->limit($this->perPage)->offset($request->get('page'));
         }
         $fetch = $query->get();
         $total = $db::table($this->dbTable)->count();
         $res = array();
         $res['data'] = $fetch;
         $res['total'] = $total;
         if (!is_null($request->get('page'))) {
             if (count($fetch) == $this->perPage && ($request->get('page') + 1) * $this->perPage < $total) {
                 $res['next_page'] = sprintf("%s://%s%s?page=%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], $app['url_generator']->generate($this->uri . "_fetch_all"), (int) $request->get('page') + 1);
             }
             if ((int) $request->get('page') > 0) {
                 $res['prev_page'] = sprintf("%s://%s%s?page=%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], $app['url_generator']->generate($this->uri . "_fetch_all"), (int) $request->get('page') - 1);
             }
             $res['first_page'] = sprintf("%s://%s%s?page=0", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], $app['url_generator']->generate($this->uri . "_fetch_all"));
             $res['last_page'] = sprintf("%s://%s%s?page=%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], $app['url_generator']->generate($this->uri . "_fetch_all"), $total / $this->perPage - 1);
         }
         $res['time_request'] = $this->getFinishRequestTime($this->startRequestTime);
         return $app->json($res);
     })->bind($this->uri . "_fetch_all");
     // Obtem registro via ID
     // Obs: A chave primaria da tabela deve ter o nome "id"
     $app->get("/" . $this->uri . "/{id}", function (\Silex\Application $app, $id) use($db, $query) {
         $fetch = $query->find($id);
         foreach ($this->foreignKey as $field => $table) {
             if (isset($fetch->{$field})) {
                 $fetch->{$field} = $db::table($table)->find($fetch->{$field});
             }
         }
         $res = array();
         $res['data'] = $fetch;
         $res['time_request'] = $this->getFinishRequestTime($this->startRequestTime);
         return $app->json($res);
     })->bind($this->uri . "_fetch_one");
     // Insere os dados enviados no banco de dados
     $app->post("/" . $this->uri, function (\Silex\Application $app, Request $request) use($db, $query) {
         $post = $request->request->all();
         $val = $this->runValidation($app, $post);
         if ($val['error']) {
             return $app->json($val);
         }
         $insert = $query->insert($val);
         $res = array();
         $res['data'] = $db::table($this->dbTable)->find($insert);
         $res['insertID'] = $insert;
         $res['time_request'] = $this->getFinishRequestTime($this->startRequestTime);
         return $app->json($res);
     })->bind($this->uri . "_insert");
     // Atualiza os dados do banco
     $app->put("/" . $this->uri . "/{id}", function (\Silex\Application $app, Request $request, $id) use($db, $query) {
         $post = $request->request->all();
         $val = $this->runValidation($app, $post);
         if ($val['error']) {
             return $app->json($val);
         }
         $query->where("id", $id)->update($val);
         $res = array();
         $res['data'] = $db::table($this->dbTable)->find($id);
         $res['time_request'] = $this->getFinishRequestTime($this->startRequestTime);
         return $app->json($res);
     })->bind($this->uri . "_update");
     // Apaga um registro do banco de dados
     $app->delete("/" . $this->uri . "/{id}", function (\Silex\Application $app, $id) use($query) {
         $query->where('id', $id)->delete();
         $res = array();
         $res['time_request'] = $this->getFinishRequestTime($this->startRequestTime);
         return $app->json($res);
     })->bind($this->uri . "_delete");
     // Realiza uma busca no banco de dados na tabela especifica utilizando o método LIKE.
     // Os parametros para busca devem ser passado via Query String. Ex: email=gmail&nome=kayo
     $app->get("/search/" . $this->uri, function (\Silex\Application $app, Request $request) use($db, $query) {
         $params = $request->query->all();
         foreach ($params as $field => $value) {
             if ($field == "limit") {
                 $query->limit($value);
             } else {
                 $exp = StringHelper::extractKeyWords($value);
                 foreach ($exp as $val) {
                     $query->orWhere($field, 'LIKE', "%" . $val . "%");
                 }
             }
         }
         $fetch = $query->get();
         $total = $db::table($this->dbTable)->count();
         $res = array();
         $res['data'] = $fetch;
         $res['total'] = $total;
         $res['time_request'] = $this->getFinishRequestTime($this->startRequestTime);
         return $app->json($res);
     })->bind($this->uri . "_search");
 }
Example #24
0
// twig templates dir
$app->register(new TwigServiceProvider(), array('twig.path' => __DIR__ . '/Views/'));
// for twig path
$app->register(new UrlGeneratorServiceProvider());
// session
$app->register(new \Silex\Provider\SessionServiceProvider());
// index
$app->get('/', function () use($app) {
    return $app['twig']->render('index.twig', array());
});
// forms
$app->get('/form/{id}', function ($id) use($app) {
    return $app['twig']->render('index.twig', array('id' => $id));
})->bind('form')->assert('id', '\\d+');
$app->post('/user', function (Request $req) use($app) {
    $app['session']->set('user', ['username' => $req->get('fio')]);
    return $app->redirect('/form/1');
})->bind('user');
$app->get('/statistics', function () use($app) {
    //    $csv = array_map('str_getcsv', file(__DIR__ . '/Logs/logs.csv'));
    return $app['twig']->render('index.twig', array('statistics' => true));
})->bind('statistics');
$app->get('/progress', function () use($app) {
    try {
        $usernames = $app['db']->fetchAll('SELECT DISTINCT username FROM logs;');
    } catch (\Exception $e) {
        return new Response('DB error', Response::HTTP_INTERNAL_SERVER_ERROR, array('content-type' => 'text/html'));
    }
    return $app['twig']->render('index.twig', array('progress' => true, 'usernames' => $usernames));
})->bind('progress');
$app->post('/form/{id}/find', function ($id, Request $req) use($app) {
    try {
 public function register(Application $app)
 {
     $app["bbsapi.user.registration"] = function (Application $app) {
         return new UserRegistration($app["entity_manager"], $app["bbsapi.utility.password_encoder"]);
     };
     $app["bbsapi.user.authentication"] = function (Application $app) {
         return new UserAuthentication($app["entity_manager"], $app["bbsapi.utility.password_encoder"], $app["bbsapi.utility.token_generator"]);
     };
     $app["bbsapi.user.token_authorization"] = function (Application $app) {
         return new UserTokenAuthorization($app["entity_manager"]);
     };
     $app["bbsapi.spec.user_spec"] = function () {
         return new UserSpec();
     };
     $app->before(function (Request $req) use($app) {
         $userId = $req->headers->get(self::HEADER_AUTHORIZATION_USER_ID);
         $tokenString = $req->headers->get(self::HEADER_AUTHORIZATION_TOKEN);
         if (!$userId || !$tokenString) {
             return;
         }
         /** @var UserTokenAuthorization $service */
         $service = $app["bbsapi.user.token_authorization"];
         $user = $service->invoke($userId, $tokenString);
         if (!$user) {
             return;
         }
         $req->setUser($user);
     });
     $app->post("/user/register", function (Application $app, Request $req) {
         /** @var UserSpec $spec */
         $spec = $app["bbsapi.spec.user_spec"];
         /** @var UserRegistration $service */
         $service = $app["bbsapi.user.registration"];
         $email = $req->request->get("email");
         $username = $req->request->get("username");
         $password = $req->request->get("password");
         $user = new User();
         $user->setEmail($email)->setUsername($username)->setPassword($password);
         $result = $spec->validate($user);
         if (!$result->isValid()) {
             return $app->json(["errors" => $result->getErrors()], 400);
         }
         $alreadyExistsErrors = ["user" => [sprintf("A username [%s] is already exists.", $user->getUsername())]];
         if ($service->findByUsername($user->getUsername())) {
             return $app->json(["errors" => $alreadyExistsErrors], 400);
         }
         try {
             $user = $service->invoke($user);
         } catch (UniqueConstraintViolationException $e) {
             return $app->json(["errors" => $alreadyExistsErrors], 400);
         }
         return $app->json($spec->format($user), 201);
     });
     $app->post("/user/authorize", function (Application $app, Request $req) {
         /** @var UserAuthentication $service */
         $service = $app["bbsapi.user.authentication"];
         $username = $req->request->get("username");
         $password = $req->request->get("password");
         $accessToken = $service->invoke($username, $password);
         if (!$accessToken) {
             return $app->json(null, 401);
         }
         return $app->json(["id" => $accessToken->getUser()->getId(), "token" => $accessToken->getToken(), "period" => $accessToken->getPeriod()]);
     });
     $app->get("/users/{username}", function (Application $app, $username) {
         /** @var UserSpec $spec */
         $spec = $app["bbsapi.spec.user_spec"];
         /** @var UserRegistration $service */
         $service = $app["bbsapi.user.registration"];
         $user = $service->findByUsername($username);
         if (!$user) {
             return $app->json(null, 404);
         }
         return $app->json($spec->format($user));
     })->assert('username', '^\\w+$');
 }
 public function testWithoutMasterRequest()
 {
     $app = new Application(['debug' => true]);
     $app->register(new RestServiceProvider());
     $app->post('/users', function (Request $request) {
         if ($request->request->has('foo')) {
             return $request->request->get('foo');
         }
         return 'error';
     });
     $request = Request::create('/users', 'POST', [], [], [], [], json_encode(['foo' => 'bar']));
     $request->setRequestFormat('json');
     $request->headers->set('Content-Type', 'application/json');
     $response = $app->handle($request);
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertEquals('bar', $response->getContent());
 }
$beers = [['name' => 'Heineken', 'stars' => '5'], ['name' => 'Antarctica', 'stars' => '4'], ['name' => 'Cristal', 'stars' => '1']];
$app->get('/beer', function () use($beers) {
    return new JsonResponse($beers, 200);
});
$app->get('/beer/{id}', function (Request $request, $id) use($beers) {
    foreach ($beers as $beer) {
        if (strtolower($id) == strtolower($beer['name'])) {
            return new JsonResponse($beer, 200);
        }
    }
    return new JsonResponse('Beer not found', 404);
});
$app->post('/auth', function (Request $request) use($app) {
    if ($request->get('usuario') == 'admin' && $request->get('senha') == 'admin') {
        $clientToken = \App\Generators\Sha2TokenGenerator::generate();
        $app['ClientToken'] = $clientToken;
        return new JsonResponse('Login ok', 200);
    }
    return new JsonResponse('Invalid username or password', 404);
});
$app->before(function (Request $request, Application $app) {
    $pathInfo = $request->getPathInfo();
    $appToken = $request->headers->get('AppToken');
    $isValidToken = false;
    $guard = new Guardian();
    if ($pathInfo == '/auth') {
        if ($guard->validateAppToken($appToken)) {
            $app['AppToken'] = $appToken;
            $isValidToken = true;
        }
    } else {
        $clientToken = $request->headers->get('ClientToken');
<?php

require_once 'vendor/autoload.php';
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Lpweb\AngularPostRequestServiceProvider;
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new AngularPostRequestServiceProvider());
$app->post('/', function (Application $app, Request $request) {
    $data = $request->request->get('data');
    $numero1 = $data['numero1'];
    $numero2 = $data['numero2'];
    return $numero1 + $numero2;
});
$app->run();
Example #29
0
 /**
  * @param Application $app
  */
 protected function registerStaticSecurityRoutes(Application $app)
 {
     $app->post($app['api.security.client.token_creation.uri'], function (Application $app, Request $request) {
         return $app->json(null, 204, $app['api.services.request']->createClientTokenFromRequestAndReturnHeaders($request));
     });
     $app->post($app['api.security.user.token_creation.uri'], function (Application $app, Request $request) {
         return $app->json(null, 204, $app['api.services.request']->createUserTokenFromRequestAndReturnHeaders($request));
     });
 }
Example #30
0
require_once __DIR__ . '/../vendor/autoload.php';
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Notes\Domain\Entity\UserBuilder;
use Notes\Persistence\Entity\MysqlUserRepository;
$app = new Application();
$app->post('/users', function (Request $request) {
    $data = json_decode($request->getContent(), true);
    $request->request->replace(is_array($data) ? $data : array());
    $data = array('email' => $request->request->get('email'), 'firstName' => $request->request->get('firstName'), 'lastName' => $request->request->get('lastName'));
    $repo = new MysqlUserRepository();
    $userBuilder = new UserBuilder();
    if (!isset($data['email'])) {
        $this->abort(406, 'Invalid Input');
    }
    $user = $userBuilder->build($data['email'], $data['firstName'], $data['lastName']);
    $repo->add($user);
    $success_message = "Success";
    $response = new Response(json_encode($success_message, 200));
    $response->headers->set('Content-Type', 'application/json');
    $response->headers->set('Content-Length', strlen($success_message));
    return $response;
});
$app->get('/', function () {
    return new Response('<h1>Final Project</h1>', 200);
});
$app->get('/users', function () {
    $sort = isset($_REQUEST['sort']) ? strtoupper(['sort']) : null;
    $repo = new MysqlUserRepository();
    $decoded_json = json_decode($repo->getAll());