/** * @Route("/graphql") * * @throws ConfigurationException * * @return JsonResponse */ public function defaultAction() { if ($this->get('request_stack')->getCurrentRequest()->getMethod() == 'OPTIONS') { return $this->createEmptyResponse(); } list($query, $variables) = $this->getPayload(); $schemaClass = $this->getParameter('graphql.schema_class'); if (!$schemaClass || !class_exists($schemaClass)) { return new JsonResponse([['message' => 'Schema class ' . $schemaClass . ' does not exist']], 200, $this->getParameter('graphql.response.headers')); } if (!$this->get('service_container')->initialized('graphql.schema')) { $schema = new $schemaClass(); if ($schema instanceof ContainerAwareInterface) { $schema->setContainer($this->get('service_container')); } $this->get('service_container')->set('graphql.schema', $schema); } /** @var Processor $processor */ $processor = $this->get('graphql.processor'); $processor->processPayload($query, $variables); $response = new JsonResponse($processor->getResponseData(), 200, $this->getParameter('graphql.response.headers')); if ($this->getParameter('graphql.response.json_pretty')) { $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); } return $response; }
public function getHttpResponse() { $result = $this->getResponseArray(); $response = new JsonResponse($result); $response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE); return $response; }
/** * @param Request $request * @param EventIdentifier $eventIdentifier * @return JsonResponse */ public function renderAction(Request $request, EventIdentifier $eventIdentifier) { if ($request->get('decimal')) { $decimal = $request->get('decimal'); } else { $decimal = 0; } if ($request->get('limit')) { $limit = max($request->get('limit'), 2); } else { $limit = 2; } $conn = $this->container->get('database_connection'); $sql = "SELECT value FROM `event` WHERE event_identifier_id=" . $eventIdentifier->getId() . " ORDER BY created desc limit " . $limit; $rows = $conn->query($sql)->fetchAll(); $chart = new \StdClass(); $datas = []; foreach ($rows as $row) { $datas[]['value'] = round($row['value'], $decimal); } $chart->item = $datas; $response = new JsonResponse($chart); $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); return $response; }
public function createJsonReponse($content) { $serializer = $this->get('jms_serializer'); $json = $serializer->serialize($content, 'json'); $response = new JsonResponse($json, 200); $response->setEncodingOptions(JSON_PRETTY_PRINT); return $response; }
/** * @param $data * @return JsonResponse */ protected function json($data) { $response = new JsonResponse($data); if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); } return $response; }
public function renderAction(Request $request, EventIdentifier $eventIdentifier) { if ($request->get('interval')) { $intervalType = $request->get('interval'); } else { $intervalType = 'd'; } if ($request->get('decimal')) { $decimal = $request->get('decimal'); } else { $decimal = 0; } if ($request->get('labelInterval')) { $labelInterval = $request->get('labelInterval'); } else { $labelInterval = 1; } switch ($intervalType) { case 'd': $groupDateForm = "%Y%m%d"; $selectDateForm = "%d.%m.%Y"; $interval = 'P1M'; break; case 'h': $groupDateForm = "%Y%m%d%H"; $selectDateForm = "%h %p"; $interval = 'P1D'; break; default: return new JsonResponse(['status' => 'error', 'message' => 'IntervalType ' . $intervalType . ' does not exists.'], 404); } $startDate = new \DateTime('now'); $startDate->sub(new \DateInterval($interval)); $conn = $this->container->get('database_connection'); $sql = "SELECT AVG(value) as avgValue, DATE_FORMAT(created, '" . $selectDateForm . "') as timespan FROM `event` WHERE event_identifier_id=" . $eventIdentifier->getId() . " and created > '" . $startDate->format('Y-m-d H:i:s') . "' GROUP BY DATE_FORMAT(created, '" . $groupDateForm . "')"; $rows = $conn->query($sql)->fetchAll(); $chart = new \StdClass(); $chart->x_axis = ['labels' => []]; $datas = []; $i = 0; foreach ($rows as $row) { if ($i % $labelInterval == 0) { $chart->x_axis['labels'][] = strtolower($row['timespan']); } else { $chart->x_axis['labels'][] = ''; } $i++; $datas[] = round($row['avgValue'], $decimal); } $chart->series = [['data' => $datas]]; $response = new JsonResponse($chart); $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); return $response; }
/** * @param Request $request * @return JsonResponse */ public function search(Request $request) { $keyword = $request->get('keyword'); $searchManager = $this->get('app.service.search_manager'); $searchManager->setSearchEngine($this->get('app.service.search_engine.kilobaitas.search')); $searchManager->setSearchEngine($this->get('app.service.search_engine.skytech.search')); $searchManager->setSearchEngine($this->get('app.service.search_engine.one_a.search')); $data = $searchManager->search($keyword); $response = new JsonResponse($data); $response->setEncodingOptions(JSON_PRETTY_PRINT); return $response; }
/** * Display one member identified by id in Json format. * * @example * { * "member": { * "id": 1, * "name": "Bland", * "firstName": "\u00a0Angie", * "phone": "0611111111" * } * } * * @Route("/api/members/{id}", requirements={"id" = "\d+"}) */ public function getAction($id) { $response = new JsonResponse(); $response->setCharset('UTF-8'); $response->setEncodingOptions(JSON_PRETTY_PRINT); try { $this->initialize(); $member = $this->memberRepository->findById($id); if ($member == null) { $response->setData('Aucun adhérent ne correspond à votre demande'); $response->setStatusCode(JsonResponse::HTTP_NOT_FOUND); } else { $response->setData($this->memberFormatter->format($member)); } } catch (\Exception $e) { $response->setStatusCode(JsonResponse::HTTP_INTERNAL_SERVER_ERROR); } return $response; }
/** * Convert some data into a JSON response. * * @param mixed $data The response data * @param integer $status The response status code * @param array $headers An array of response headers * @return JsonResponse * @see JsonResponse */ public function json($data = [], $status = 200, array $headers = []) { $request = $this['request_stack']->getMasterRequest(); if ($request->query->has('fields') && !($status >= 400 && $status < 500)) { $fields = $this['rest.fields']; $fields->addParameter('id'); $data = $this['rest.filter']->filter($data); } $flags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT; if ($request->query->get('pretty', true)) { $flags |= JSON_PRETTY_PRINT; } $response = new JsonResponse(); $response->headers->replace($headers); $response->setStatusCode($status); $response->setEncodingOptions($flags); $response->setData($data); if ($request->query->has('callback')) { $response->setCallback($request->query->get('callback')); } return $response; }
public function getConfigAction(Request $request) { if ($request->get('integration_key') != DefaultController::INTEGRATION_KEY) { return new JsonResponse('You are not allowed to call this action.'); } $collections = $this->getDoctrine()->getRepository('LeanKoalaIntegrationMissingRequestBundle:Collection')->findBy([], ['name' => 'ASC']); $systemCollections = array(); foreach ($collections as $collection) { foreach ($collection->getSystems() as $system) { if (!array_key_exists($system->getId(), $systemCollections)) { $systemCollections[$system->getId()]['system'] = $system; } $systemCollections[$system->getId()]['options'][] = $collection; } } $result = []; foreach ($systemCollections as $collection) { $result[] = $collection; } $response = new JsonResponse($result); $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); return $response; }
/** * Exports the widgets of current user into a json file * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response */ public function exportAction() { /** @var \Mautic\DashboardBundle\Model\DashboardModel $model */ $model = $this->factory->getModel('dashboard'); $widgetsPaginator = $model->getWidgets(); $usersName = $this->factory->getUser()->getName(); $dateTime = new \DateTime(); $dateStamp = $dateTime->format('Y-m-d H:i:s'); $name = $this->request->get('name', 'dashboard-of-' . str_replace(' ', '-', $usersName) . '-' . $dateStamp); $description = $this->get('translator')->trans('mautic.dashboard.generated_by', array('%name%' => $usersName, '%date%' => $dateStamp)); $dashboard = array('name' => $name, 'description' => $description, 'widgets' => array()); foreach ($widgetsPaginator as $widget) { $dashboard['widgets'][] = array('name' => $widget->getName(), 'width' => $widget->getWidth(), 'height' => $widget->getHeight(), 'ordering' => $widget->getOrdering(), 'type' => $widget->getType(), 'params' => $widget->getParams(), 'template' => $widget->getTemplate()); } // Make the filename safe $filename = InputHelper::alphanum($name, false, '_') . '.json'; if ($this->request->get('save', false)) { // Save to the user's folder $dir = $this->factory->getSystemPath('dashboard.user'); file_put_contents($dir . '/' . $filename, json_encode($dashboard)); return $this->redirect($this->get('router')->generate('mautic_dashboard_action', array('objectAction' => 'import'))); } $response = new JsonResponse($dashboard); $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); $response->headers->set('Content-Length', strlen($response->getContent())); $response->headers->set('Content-Type', 'application/force-download'); $response->headers->set('Content-Type', 'application/octet-stream'); $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"'); $response->headers->set('Expires', 0); $response->headers->set('Cache-Control', 'must-revalidate'); $response->headers->set('Pragma', 'public'); return $response; }
public function testSetEncodingOptions() { $response = new JsonResponse(); $response->setData(array(array(1, 2, 3))); $this->assertEquals('[[1,2,3]]', $response->getContent()); $response->setEncodingOptions(JSON_FORCE_OBJECT); $this->assertEquals('{"0":{"0":1,"1":2,"2":3}}', $response->getContent()); }
protected function returnJson($resource) { $response = new JsonResponse($resource); $response->setEncodingOptions(JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); return $response; }
/** * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function send() { $jsonResponse = new JsonResponse($this->response->toArray(), Response::HTTP_OK, ['X-Zed-Host' => 1]); if ($this->repeatIsActive) { $jsonResponse->setEncodingOptions(JSON_PRETTY_PRINT); } return $jsonResponse; }
public function restGetSystemsForProjectAction(Request $request) { $this->assertApiKey($request->get('api_key')); $response = new JsonResponse($this->getActiveSystemsForProject($this->getProject())); $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); return $response; }
/** * @param $results array * @return JsonResponse */ public function format($results) { $response = new JsonResponse($results, 200); $response->setEncodingOptions(JSON_PRETTY_PRINT); return $response; }
protected function getJsonResponse(array $parameter) { $response = new JsonResponse($parameter); $response->setEncodingOptions(defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : 0); return $response; }
/** * @param Request $request */ public function run(Request $request) { $routes = $this->generateRoutes(); $response = new Response(); $context = new RequestContext($this->uri->getBasepath()); $matcher = new UrlMatcher($routes, $context); $prefs = $this->service->getPreferenceLoader()->getSystemPreferences(); try { $match = $matcher->match($this->getDestination()); $main = print_r($match, true); $route = $match['_route']; $css = []; $scripts = []; switch ($route) { case 'json': $repo = $this->service->getResourceRepository(); $module = $this->findModuleBySlug($match['module']); if ($module !== null && $module['model'] !== null) { $components = parse_url($prefs->getApiUrl() . $module['slug']); $prefs = $this->service->getPreferenceLoader()->getSystemPreferences(); $model = $module['model']; $filename = sprintf('/packages/%s/api.json', $model->getName()); $json = Json::decode($repo->get($filename)->getBody()); $swagger = new Swagger($json); $swagger->getInfo()->setVersion($prefs->getApiVersion()); $swagger->setHost($components['host']); $swagger->setBasePath($components['path']); $swagger->getSchemes()->add($components['scheme']); $swagger->getConsumes()->add('application/vnd.api+json'); $swagger->getProduces()->add('application/vnd.api+json'); $response = new JsonResponse($swagger->toArray()); $response->setEncodingOptions(Json::HEX_TAG | Json::HEX_APOS | Json::HEX_AMP | Json::HEX_QUOT | Json::UNESCAPED_SLASHES); return $response; } break; case 'reference': case 'module': $current = ''; $content = $main; if ($route == 'module') { $scripts = ['/assets/jquery-migrate/jquery-migrate.min.js', '/assets/swagger-ui/dist/lib/jquery.slideto.min.js', '/assets/swagger-ui/dist/lib/jquery.wiggle.min.js', '/assets/swagger-ui/dist/lib/jquery.ba-bbq.min.js', '/assets/swagger-ui/dist/lib/handlebars-2.0.0.js', '/assets/swagger-ui/dist/lib/underscore-min.js', '/assets/swagger-ui/dist/lib/backbone-min.js', '/assets/swagger-ui/dist/swagger-ui.min.js', '/assets/swagger-ui/dist/lib/highlight.7.3.pack.js', '/assets/swagger-ui/dist/lib/jsoneditor.min.js', '/assets/swagger-ui/dist/lib/marked.js']; $css = ['/assets/swagger-ui/dist/css/screen.css']; $current = $match['module']; $content = $this->render('/keeko/developer-app/templates/api.twig', ['base' => $this->getBaseUrl(), 'url' => $this->getBaseUrl() . '/reference/' . $match['module'] . '.json', 'module' => $this->findModuleBySlug($match['module'])]); } else { $content = $this->render('/keeko/developer-app/templates/reference/index.twig'); } $main = $this->render('/keeko/developer-app/templates/reference.twig', ['base' => $this->getBaseUrl(), 'content' => $content, 'modules' => $this->loadModules(), 'current' => $current]); break; case 'index': $main = $this->render('/keeko/developer-app/templates/index.twig', ['plattform_name' => $prefs->getPlattformName(), 'base' => $this->getBaseUrl()]); break; case 'area': case 'topic': $current = isset($match['topic']) ? $match['topic'] : 'index'; $content = $this->render(sprintf('/keeko/developer-app/templates/%s/%s.twig', $match['area'], $current), ['base' => $this->getBaseUrl(), 'api_url' => $prefs->getApiUrl()]); $main = $this->render(sprintf('/keeko/developer-app/templates/%s.twig', $match['area']), ['content' => $content, 'menu' => $this->getMenu($match['area']), 'current' => $current, 'base' => $this->getBaseUrl()]); break; } $response->setContent($this->render('/keeko/developer-app/templates/main.twig', ['plattform_name' => $prefs->getPlattformName(), 'root' => $this->getBaseUrl(), 'base' => $this->getBaseUrl(), 'destination' => $this->getDestination(), 'styles' => $css, 'scripts' => $scripts, 'main' => $main])); } catch (ResourceNotFoundException $e) { $response->setStatusCode(Response::HTTP_NOT_FOUND); } return $response; }
/** * Instantiate Symfony HTTP Foundation's JsonResponse * using Symfony's HTTP Foundation Request * * The Response Interface is used to populate RAISe Response */ public function __construct() { $this->httpResponse = new JsonResponse(); $this->httpResponse->prepare(Request::createFromGlobals()); $this->httpResponse->setEncodingOptions(JSON_PRETTY_PRINT); }
} /*========== Sectors ==========*/ public function getSectors() { $sql = "SELECT * FROM company_sectors"; return $this->db->fetchAll($sql); } } $DataProvider = new DataProvider($app['db']); /*=============================== = CLIENTS = ===============================*/ $app->get('/clients', function () use($app, $DataProvider) { $clients = $DataProvider->getClients(); $response = new JsonResponse(); $response->setEncodingOptions(JSON_NUMERIC_CHECK); $response->setData($clients); return $response; }); $app->get('/client/{clientId}', function ($clientId) use($app, $DataProvider) { $clientDetails = $DataProvider->getClient($clientId); if (!$clientDetails) { return $app->json(['errorMessage' => 'Client Not Found'], 404); } return $app->json($clientDetails); }); $app->put('/client/{clientId}', function (Request $request, $clientId) use($app, $DataProvider) { $clientDetails = $DataProvider->getClient($clientId); if (!$clientDetails) { return $app->json(['errorMessage' => 'Client Not Found'], 404); }
$app->abort(403, 'Bad input'); } } $extension = strtolower(preg_replace('/^[.]+/', '', $extension)); $extension = preg_replace('/[.]+/', '.', $extension); if (!preg_match('/[A-Za-z0-9.]/', $extension)) { $app->abort(500, 'Invalid filename extension'); } $authorized = password_verify($password, $app['password']); if (!$authorized) { $app->abort(403, "You aren't allowed to be here, fucko"); } $file = $request->files->get('file'); if (!$file instanceof UploadedFile || !$file->isValid()) { $app->abort(500, 'Either there was no file or the upload failed'); } $app['db']->beginTransaction(); $sth = $app['db']->prepare('INSERT INTO extensions (extension, mime_type) VALUES (?, ?)'); $sth->bindValue(1, $extension); $sth->bindValue(2, $mimeType); $sth->execute(); $file->move(__DIR__ . '/repository', 'tidus_laugh.' . $extension); $app['db']->commit(); return $app->redirect('/manage', 303); }); $app->get('/repository.json', function () use($app) { $all = $app['db']->fetchAll('SELECT * FROM extensions ORDER BY extension ASC'); $response = new JsonResponse(['extensions' => $all]); $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT); return $response; });